diff --git a/.MetaTestOptIn.json b/.MetaTestOptIn.json new file mode 100644 index 0000000..7f445ce --- /dev/null +++ b/.MetaTestOptIn.json @@ -0,0 +1,5 @@ +[ + "Common Tests - Validate Module Files", + "Common Tests - Validate Script Files", + "Common Tests - Relative Path Length" +] diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index b3b7b81..cd2a1cb 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -36,7 +36,7 @@ Change to [x] for each task in the task list that applies to your PR. For those task that don't apply to you PR, leave those as is. --> -- [ ] Added an entry under the Unreleased section of the change log in the README.md. +- [ ] Added an entry under the Unreleased section in the CHANGELOG.md. Entry should say what was changed, and how that affects users (if applicable). - [ ] Resource documentation added/updated in README.md. - [ ] Resource parameter descriptions added/updated in README.md, schema.mof diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..bc3d3d3 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,163 @@ +# Change log for PsDscResources + +## Unreleased + +## 2.12.0.0 + +* Ports style fixes that were recently made in xPSDesiredStateConfiguration + on test related files. +* Ports most of the style upgrades from xPSDesiredStateConfiguration that have + been made in files in the DscResources folder. +* Ports fixes for the following issues: + [Issue #505](https://github.com/PowerShell/xPSDesiredStateConfiguration/issues/505) + [Issue #590](https://github.com/PowerShell/xPSDesiredStateConfiguration/issues/590) + Changes to test helper Enter-DscResourceTestEnvironment so that it only + updates DSCResource.Tests when it is longer than 120 minutes since + it was last pulled. This is to improve performance of test execution + and reduce the likelihood of connectivity issues caused by inability to + pull DSCResource.Tests. +* Fixes issue where MsiPackage Integration tests fail if the test HttpListener + fails to start. Moves the test HttpListener objects to dynamically assigned, + higher numbered ports to avoid conflicts with other services, and also checks + to ensure that the ports are available before using them. Adds checks to + ensure that no outstanding HTTP server jobs are running before attempting to + setup a new one. Also adds additional instrumentation to make it easier to + troubleshoot issues with the test HttpListener objects in the future. + Specifically fixes + [Issue #142](https://github.com/PowerShell/PSDscResources/issues/142) +* Improved speed of Test-IsNanoServer function +* Remove the Byte Order Mark (BOM) from all affected files +* Opt-in to 'Validate Module Files' and 'Validate Script Files' common meta-tests +* Opt-in to 'Common Tests - Relative Path Length' common meta-test +* Fix README markdownlint validation failures +* Move change log from README.md to CHANGELOG.md + +## 2.11.0.0 + +* Fix Custom DSC Resource Kit PSSA Rule Failures + +## 2.10.0.0 + +* Fixed CompanyName typo - Fixes [Issue #100](https://github.com/PowerShell/PSDscResources/issues/100) +* Update LICENSE file to match the Microsoft Open Source Team + standard - Fixes [Issue #120](https://github.com/PowerShell/PSDscResources/issues/120). +* Update `CommonResourceHelper` unit tests to meet Pester 4.0.0 + standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). +* Update `ResourceHelper` unit tests to meet Pester 4.0.0 + standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). +* Ported fixes from [xPSDesiredStateConfiguration](https://github.com/PowerShell/xPSDesiredStateConfiguration): + * xArchive + * Fix end-to-end tests. + * Update integration tests to meet Pester 4.0.0 standards. + * Update end-to-end tests to meet Pester 4.0.0 standards. + * Update unit and integration tests to meet Pester 4.0.0 standards. + * Wrapped all path and identifier strings in verbose messages with + quotes to make it easier to identify the limit of the string when + debugging. + * Refactored date/time checksum code to improve testability and ensure + tests can run on machines with localized datetime formats that are not + US. + * Fix 'Get-ArchiveEntryLastWriteTime' to return `[datetime]`. + * Improved verbose logging to make debugging path issues easier. +* Added .gitattributes file to ensure CRLF settings are configured correctly + for the repository. +* Updated '.vscode\settings.json' to refer to AnalyzerSettings.psd1 so that + custom syntax problems are highlighted in Visual Studio Code. +* Fixed style guideline violations in `CommonResourceHelper.psm1`. +* Updated 'appveyor.yml' to meet more recent standards. +* Removed OS image version from 'appveyor.yml' to use default image + ([Issue #127](https://github.com/PowerShell/PSDscResources/issues/127)). +* Removed code to install WMF5.1 from 'appveyor.yml' because it is already + installed in AppVeyor images ([Issue #128](https://github.com/PowerShell/PSDscResources/issues/128)). +* Removed .vscode from .gitignore so that Visual Studio code environment + settings can be committed. +* Environment + * Update tests to meet Pester 4.0.0 standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). +* Group + * Update tests to meet Pester 4.0.0 standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). + * Fix unit tests to run on Nano Server. + * Refactored unit tests to enclude Context fixtures and change functions + to Describe fixtures. +* GroupSet + * Update tests to meet Pester 4.0.0 standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). + +## 2.9.0.0 + +* Added Description and Parameter description for composite resources + +## 2.8.0.0 + +* Archive + * Added handling of directory archive entries that end with a foward slash + * Removed formatting of LastWriteTime timestamp and updated comparison of timestamps to handle dates in different formats +* WindowsProcess + * Fix unreliable tests +* Updated Test-IsNanoServer to return false if Get-ComputerInfo fails +* Registry + * Fixed bug when using the full registry drive name (e.g. HKEY\_LOCAL\_MACHINE) and using a key name that includes a drive with forward slashes (e.g. C:/) + +## 2.7.0.0 + +* MsiPackage + * Parse installation date from registry using invariant culture. + * Fix a bug in unit test failing, when regional setting differs from English-US. + +## 2.6.0.0 + +* Archive + * Fixed a minor bug in the unit tests where sometimes the incorrect DateTime format was used. +* Added MsiPackage + +## 2.5.0.0 + +* Enable codecov.io code coverage reporting +* Group + * Added support for domain based group members on Nano server. +* Added the Archive resource +* Update Test-IsNanoServer cmdlet to properly test for a Nano server rather than the core version of PowerShell +* Registry + * Fixed bug where an error was thrown when running Get-DscConfiguration if the registry already existed + +## 2.4.0.0 + +* Cleaned User +* Updated User to have non-dependent unit tests. +* Ported fixes from [xPSDesiredStateConfiguration](https://github.com/PowerShell/xPSDesiredStateConfiguration): + * WindowsProcess: Minor updates to integration tests + * Registry: Fixed support for forward slashes in registry key names +* Group: + * Group members in the "NT Authority", "BuiltIn" and "NT Service" scopes should now be resolved without an error. If you were seeing the errors "Exception calling ".ctor" with "4" argument(s): "Server names cannot contain a space character."" or "Exception calling ".ctor" with "2" argument(s): "Server names cannot contain a space character."", this fix should resolve those errors. If you are still seeing one of the errors, there is probably another local scope we need to add. Please let us know. + * The resource will no longer attempt to resolve group members if Members, MembersToInclude, and MembersToExclude are not specified. +* Added Environment + +## 2.3.0.0 + +* Updated manifest to include both WindowsOptionalFeature and WindowsOptionalFeatureSet instead of just WindowsOptionalFeature twice + +## 2.2.0.0 + +* WindowsFeature: + * Added Catch to ignore RuntimeException when importing ServerManager module. This solves the issue described [here](https://social.technet.microsoft.com/Forums/en-US/9fc314e1-27bf-4f03-ab78-5e0f7a662b8f/importmodule-servermanager-some-or-all-identity-references-could-not-be-translated?forum=winserverpowershell). + * Updated unit tests. +* Added WindowsProcess +* CommonTestHelper: + * Added Get-AppVeyorAdministratorCredential. + * Added Set-StrictMode -'Latest' and $errorActionPreference -'Stop'. +* Service: + * Updated resource module, unit tests, integration tests, and examples to reflect the changes made in xPSDesiredStateConfiguration. +* Group: + * Updated resource module, examples, and integration tests to reflect the changes made in xPSDesiredStateConfiguration. +* Added Script. +* Added GroupSet, ServiceSet, WindowsFeatureSet, WindowsOptionalFeatureSet, and ProcessSet. +* Added Set-StrictMode -'Latest' and $errorActionPreference -'Stop' to Group, Service, User, WindowsFeature, WindowsOptionalFeature, WindowsPackageCab. +* Fixed bug in WindowsFeature in which is was checking the 'Count' property of an object that was not always an array. +* Cleaned Group and Service resources and tests. +* Added Registry. + +## 2.1.0.0 + +* Added WindowsFeature. + +## 2.0.0.0 + +* Initial release of PSDscResources. diff --git a/DscResources/CommonResourceHelper.psm1 b/DscResources/CommonResourceHelper.psm1 index f1f9d3a..1f3e32c 100644 --- a/DscResources/CommonResourceHelper.psm1 +++ b/DscResources/CommonResourceHelper.psm1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Tests if the current machine is a Nano server. #> @@ -8,21 +8,24 @@ function Test-IsNanoServer [CmdletBinding()] param () - $isNanoServer = $false + $serverLevelsRegKey = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels' - if (Test-CommandExists -Name 'Get-ComputerInfo') + if (Test-Path -Path $serverLevelsRegKey) { - $computerInfo = Get-ComputerInfo -ErrorAction 'SilentlyContinue' + $serverLevels = Get-ItemProperty -Path $serverLevelsRegKey - if ($null -ne $computerInfo) + if ($serverLevels.NanoServer -eq 1) { - $computerIsServer = 'Server' -ieq $computerInfo.OsProductType - - if ($computerIsServer) - { - $isNanoServer = 'NanoServer' -ieq $computerInfo.OsServerLevel - } + $isNanoServer = $true } + else + { + $isNanoServer = $false + } + } + else + { + $isNanoServer = $false } return $isNanoServer @@ -43,7 +46,8 @@ function Test-CommandExists ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [System.String] $Name + [System.String] + $Name ) $command = Get-Command -Name $Name -ErrorAction 'SilentlyContinue' @@ -52,13 +56,13 @@ function Test-CommandExists <# .SYNOPSIS - Creates and throws an invalid argument exception + Creates and throws an invalid argument exception. .PARAMETER Message - The message explaining why this error is being thrown + The message explaining why this error is being thrown. .PARAMETER ArgumentName - The name of the invalid argument that is causing this error to be thrown + The name of the invalid argument that is causing this error to be thrown. #> function New-InvalidArgumentException { @@ -77,9 +81,9 @@ function New-InvalidArgumentException ) $argumentException = New-Object -TypeName 'ArgumentException' ` - -ArgumentList @($Message, $ArgumentName) + -ArgumentList @($Message, $ArgumentName) $newObjectParams = @{ - TypeName = 'System.Management.Automation.ErrorRecord' + TypeName = 'System.Management.Automation.ErrorRecord' ArgumentList = @($argumentException, $ArgumentName, 'InvalidArgument', $null) } $errorRecord = New-Object @newObjectParams @@ -89,13 +93,14 @@ function New-InvalidArgumentException <# .SYNOPSIS - Creates and throws an invalid operation exception + Creates and throws an invalid operation exception. .PARAMETER Message - The message explaining why this error is being thrown + The message explaining why this error is being thrown. .PARAMETER ErrorRecord - The error record containing the exception that is causing this terminating error + The error record containing the exception that is causing this terminating + error. #> function New-InvalidOperationException { @@ -120,18 +125,17 @@ function New-InvalidOperationException elseif ($null -eq $ErrorRecord) { $invalidOperationException = New-Object -TypeName 'InvalidOperationException' ` - -ArgumentList @($Message) + -ArgumentList @( $Message ) } else { $invalidOperationException = New-Object -TypeName 'InvalidOperationException' ` - -ArgumentList @($Message, $ErrorRecord.Exception) + -ArgumentList @( $Message, $ErrorRecord.Exception ) } $newObjectParams = @{ - TypeName = 'System.Management.Automation.ErrorRecord' - ArgumentList = @( $invalidOperationException.ToString(), 'MachineStateIncorrect', - 'InvalidOperation', $null ) + TypeName = 'System.Management.Automation.ErrorRecord' + ArgumentList = @( $invalidOperationException.ToString(), 'MachineStateIncorrect', 'InvalidOperation', $null ) } $errorRecordToThrow = New-Object @newObjectParams @@ -144,7 +148,8 @@ function New-InvalidOperationException Falls back to en-US strings if the machine's culture is not supported. .PARAMETER ResourceName - The name of the resource as it appears before '.strings.psd1' of the localized string file. + The name of the resource as it appears before '.strings.psd1' of the localized + string file. For example: For WindowsOptionalFeature: MSFT_WindowsOptionalFeature For Service: MSFT_ServiceResource diff --git a/DscResources/GroupSet/GroupSet.psd1 b/DscResources/GroupSet/GroupSet.psd1 index 1d19475..22c463b 100644 --- a/DscResources/GroupSet/GroupSet.psd1 +++ b/DscResources/GroupSet/GroupSet.psd1 @@ -1,4 +1,4 @@ -@{ +@{ # Script module or binary module file associated with this manifest. RootModule = 'GroupSet.schema.psm1' diff --git a/DscResources/GroupSet/GroupSet.schema.psm1 b/DscResources/GroupSet/GroupSet.schema.psm1 index d4b1c96..4c7a785 100644 --- a/DscResources/GroupSet/GroupSet.schema.psm1 +++ b/DscResources/GroupSet/GroupSet.schema.psm1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' # Import ResourceSetHelper for New-ResourceSetConfigurationScriptBlock @@ -19,7 +19,7 @@ Import-Module -Name $script:resourceSetHelperFilePath .PARAMETER Ensure Specifies whether or not the set of groups should exist. - + Set this property to Present to create or modify a set of groups. Set this property to Absent to remove a set of groups. @@ -37,25 +37,25 @@ Configuration GroupSet [CmdletBinding()] param ( - [Parameter(Mandatory = $true, HelpMessage="The names of the groups for which you want to ensure a specific state.")] + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $GroupName, - [Parameter( HelpMessage="Indicates whether the groups exist. Set this property to Absent to ensure that the groups do not exist. Setting it to Present (the default value) ensures that the groups exist.")] + [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, - [Parameter( HelpMessage="Use this property to add members to the existing membership of the group. The value of this property is an array of strings of the form Domain\UserName. If you set this property in a configuration, do not use the Members property. Doing so will generate an error.")] - [String[]] + [Parameter()] + [System.String[]] $MembersToInclude, - [Parameter( HelpMessage="Use this property to remove members from the existing membership of the groups. The value of this property is an array of strings of the form Domain\UserName. If you set this property in a configuration, do not use the Members property. Doing so will generate an error.")] - [String[]] + [Parameter()] + [System.String[]] $MembersToExclude, - [Parameter( HelpMessage="The credentials required to access remote resources. Note: This account must have the appropriate Active Directory permissions to add all non-local accounts to the group; otherwise, an error will occur.")] + [Parameter()] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] diff --git a/DscResources/MSFT_Archive/MSFT_Archive.psm1 b/DscResources/MSFT_Archive/MSFT_Archive.psm1 index f477867..6ceb38e 100644 --- a/DscResources/MSFT_Archive/MSFT_Archive.psm1 +++ b/DscResources/MSFT_Archive/MSFT_Archive.psm1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' <# @@ -81,27 +81,27 @@ if (-not (Test-IsNanoServer)) #> function Get-TargetResource { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] - [Boolean] + [System.Boolean] $Validate = $false, [Parameter()] [ValidateSet('SHA-1', 'SHA-256', 'SHA-512', 'CreatedDate', 'ModifiedDate')] - [String] + [System.String] $Checksum = 'ModifiedDate', [Parameter()] @@ -257,26 +257,26 @@ function Set-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [Boolean] + [System.Boolean] $Validate = $false, [Parameter()] [ValidateSet('SHA-1', 'SHA-256', 'SHA-512', 'CreatedDate', 'ModifiedDate')] - [String] + [System.String] $Checksum = 'ModifiedDate', [Parameter()] @@ -285,7 +285,7 @@ function Set-TargetResource $Credential, [Parameter()] - [Boolean] + [System.Boolean] $Force = $false ) @@ -422,32 +422,32 @@ function Set-TargetResource #> function Test-TargetResource { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [Boolean] + [System.Boolean] $Validate = $false, [Parameter()] [ValidateSet('SHA-1', 'SHA-256', 'SHA-512', 'CreatedDate', 'ModifiedDate')] - [String] + [System.String] $Checksum = 'ModifiedDate', [Parameter()] @@ -456,7 +456,7 @@ function Test-TargetResource $Credential, [Parameter()] - [Boolean] + [System.Boolean] $Force = $false ) @@ -491,11 +491,11 @@ function Test-TargetResource #> function New-Guid { - [OutputType([Guid])] + [OutputType([System.Guid])] [CmdletBinding()] param () - return [Guid]::NewGuid() + return [System.Guid]::NewGuid() } <# @@ -515,7 +515,7 @@ function Invoke-NewPSDrive ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [Hashtable] + [System.Collections.Hashtable] $Parameters ) @@ -541,7 +541,7 @@ function Mount-PSDriveWithCredential ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] @@ -618,7 +618,7 @@ function Assert-PathExistsAsLeaf ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) @@ -646,7 +646,7 @@ function Assert-DestinationDoesNotExistAsFile ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination ) @@ -678,7 +678,7 @@ function Open-Archive ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) @@ -753,7 +753,7 @@ function Get-ArchiveEntries #> function Get-ArchiveEntryFullName { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( @@ -821,13 +821,13 @@ function Close-Stream #> function Test-ChecksumIsSha { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Checksum ) @@ -845,13 +845,13 @@ function Test-ChecksumIsSha #> function ConvertTo-PowerShellHashAlgorithmName { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $DscHashAlgorithmName ) @@ -874,13 +874,13 @@ function ConvertTo-PowerShellHashAlgorithmName #> function Test-FileHashMatchesArchiveEntryHash { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $FilePath, [Parameter(Mandatory = $true)] @@ -890,7 +890,7 @@ function Test-FileHashMatchesArchiveEntryHash [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $HashAlgorithmName ) @@ -1115,7 +1115,7 @@ function Get-ArchiveEntryLastWriteTime #> function Test-FileMatchesArchiveEntryByChecksum { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( @@ -1131,7 +1131,7 @@ function Test-FileMatchesArchiveEntryByChecksum [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Checksum ) @@ -1187,13 +1187,13 @@ function Test-FileMatchesArchiveEntryByChecksum #> function Test-ArchiveEntryIsDirectory { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ArchiveEntryName ) @@ -1219,23 +1219,23 @@ function Test-ArchiveEntryIsDirectory #> function Test-ArchiveExistsAtDestination { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ArchiveSourcePath, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] [ValidateSet('SHA-1', 'SHA-256', 'SHA-512', 'CreatedDate', 'ModifiedDate')] - [String] + [System.String] $Checksum ) @@ -1370,7 +1370,7 @@ function Copy-ArchiveEntryToDestination [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $DestinationPath ) @@ -1449,21 +1449,21 @@ function Expand-ArchiveToDestination ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ArchiveSourcePath, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] [ValidateSet('SHA-1', 'SHA-256', 'SHA-512', 'CreatedDate', 'ModifiedDate')] - [String] + [System.String] $Checksum, [Parameter()] - [Boolean] + [System.Boolean] $Force = $false ) @@ -1564,12 +1564,12 @@ function Remove-DirectoryFromDestination ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Directory, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination ) @@ -1623,17 +1623,17 @@ function Remove-ArchiveFromDestination ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ArchiveSourcePath, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] [ValidateSet('SHA-1', 'SHA-256', 'SHA-512', 'CreatedDate', 'ModifiedDate')] - [String] + [System.String] $Checksum ) @@ -1699,7 +1699,7 @@ function Remove-ArchiveFromDestination { $parentDirectory = Split-Path -Path $archiveEntryFullName -Parent - while (-not [String]::IsNullOrEmpty($parentDirectory)) + while (-not [System.String]::IsNullOrEmpty($parentDirectory)) { $directoriesToRemove += $parentDirectory $parentDirectory = Split-Path -Path $parentDirectory -Parent diff --git a/DscResources/MSFT_Archive/en-US/MSFT_Archive.strings.psd1 b/DscResources/MSFT_Archive/en-US/MSFT_Archive.strings.psd1 index be6af64..5f2eade 100644 --- a/DscResources/MSFT_Archive/en-US/MSFT_Archive.strings.psd1 +++ b/DscResources/MSFT_Archive/en-US/MSFT_Archive.strings.psd1 @@ -1,4 +1,4 @@ -# Localized MSFT_Archive.strings.psd1 +# Localized MSFT_Archive.strings.psd1 ConvertFrom-StringData @' RetrievingArchiveState = Retrieving the state of the archive with path "{0}" and destination "{1}"... diff --git a/DscResources/MSFT_EnvironmentResource/MSFT_EnvironmentResource.psm1 b/DscResources/MSFT_EnvironmentResource/MSFT_EnvironmentResource.psm1 index 115bc2a..4bda70b 100644 --- a/DscResources/MSFT_EnvironmentResource/MSFT_EnvironmentResource.psm1 +++ b/DscResources/MSFT_EnvironmentResource/MSFT_EnvironmentResource.psm1 @@ -29,22 +29,22 @@ $script:maxUserEnvVariableLength = 255 #> function Get-TargetResource { - [CmdletBinding()] - [OutputType([Hashtable])] + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, - + [Parameter()] [ValidateSet('Process', 'Machine')] [ValidateNotNullOrEmpty()] - [String[]] - $Target = ('Process', 'Machine') + [System.String[]] + $Target = ('Process', 'Machine') ) - + $valueToReturn = $null if ($Target -contains 'Machine') @@ -60,13 +60,13 @@ function Get-TargetResource { $valueToReturn = Get-ProcessEnvironmentVariable -Name $Name } - + $environmentResource = @{ Name = $Name Value = $null Ensure = 'Absent' } - + if ($null -eq $valueToReturn) { Write-Verbose -Message ($script:localizedData.EnvVarNotFound -f $Name) @@ -84,7 +84,7 @@ function Get-TargetResource <# .SYNOPSIS Creates, modifies, or removes an environment variable. - + .PARAMETER Name The name of the environment variable to create, modify, or remove. @@ -117,34 +117,34 @@ function Set-TargetResource { [CmdletBinding()] param - ( + ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, - + [Parameter()] [ValidateNotNull()] - [String] - $Value = [String]::Empty, - + [System.String] + $Value = [System.String]::Empty, + [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', - + [Parameter()] - [Boolean] + [System.Boolean] $Path = $false, [Parameter()] [ValidateSet('Process', 'Machine')] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Target = ('Process', 'Machine') ) - - $valueSpecified = ($Value -ne [String]::Empty) + + $valueSpecified = ($Value -ne [System.String]::Empty) $currentValueFromMachine = $null $currentValueFromProcess = $null $currentPropertiesFromMachine = $null @@ -162,7 +162,7 @@ function Set-TargetResource { $currentValueFromMachine = $currentPropertiesFromMachine.$Name } - } + } else { $currentPropertiesFromMachine = Get-ItemProperty -Path $script:envVarRegPathMachine -Name $Name -ErrorAction 'SilentlyContinue' @@ -192,8 +192,8 @@ function Set-TargetResource if ($Ensure -eq 'Present') { - $createMachineVariable = ((-not $setMachineVariable) -or ($null -eq $currentPropertiesFromMachine) -or ($currentValueFromMachine -eq [String]::Empty)) - $createProcessVariable = ((-not $setProcessVariable) -or ($null -eq $currentValueFromProcess) -or ($currentValueFromProcess -eq [String]::Empty)) + $createMachineVariable = ((-not $setMachineVariable) -or ($null -eq $currentPropertiesFromMachine) -or ($currentValueFromMachine -eq [System.String]::Empty)) + $createProcessVariable = ((-not $setProcessVariable) -or ($null -eq $currentValueFromProcess) -or ($currentValueFromProcess -eq [System.String]::Empty)) if ($createMachineVariable -and $createProcessVariable) { @@ -214,7 +214,7 @@ function Set-TargetResource #> Set-EnvironmentVariable -Name $Name -Value $Value -Target $Target - + Write-Verbose -Message ($script:localizedData.EnvVarCreated -f $Name, $Value) return } @@ -234,15 +234,15 @@ function Set-TargetResource # Check if an empty, whitespace or semi-colon only string has been specified. If yes, return unchanged. $trimmedValue = $Value.Trim(';').Trim() - if ([String]::IsNullOrEmpty($trimmedValue)) + if ([System.String]::IsNullOrEmpty($trimmedValue)) { Write-Verbose -Message ($script:localizedData.EnvVarPathUnchanged -f $Name, $currentValueToDisplay) - return + return } if (-not $Path) { - # For non-path variables, simply set the specified $Value as the new value of the specified + # For non-path variables, simply set the specified $Value as the new value of the specified # variable $Name for the given $Target if (($setMachineVariable -and ($Value -cne $currentValueFromMachine)) -or ` @@ -280,7 +280,7 @@ function Set-TargetResource if ($setProcessVariable) { $valueUnchanged = Test-PathsInValue -ExistingPaths $currentValueFromProcess -QueryPaths $trimmedValue -FindCriteria 'All' - + if ($currentValueFromProcess -and -not $valueUnchanged) { $updatedValue = Add-PathsToValue -CurrentValue $currentValueFromProcess -NewValue $trimmedValue @@ -303,10 +303,10 @@ function Set-TargetResource if ($machineVariableRemoved -and $processVariableRemoved) { # Variable not found, condition is satisfied and there is nothing to set/remove, return - Write-Verbose -Message ($script:localizedData.EnvVarNotFound -f $Name) + Write-Verbose -Message ($script:localizedData.EnvVarNotFound -f $Name) return } - + if ((-not $ValueSpecified) -or (-not $Path)) { <# @@ -323,7 +323,7 @@ function Set-TargetResource # Check if an empty string or semi-colon only string has been specified as $Value. If yes, return unchanged as we don't need to remove anything. $trimmedValue = $Value.Trim(';').Trim() - if ([String]::IsNullOrEmpty($trimmedValue)) + if ([System.String]::IsNullOrEmpty($trimmedValue)) { Write-Verbose -Message ($script:localizedData.EnvVarPathUnchanged -f $Name, $currentValueToDisplay) return @@ -334,7 +334,7 @@ function Set-TargetResource if ($setMachineVariable) { $finalPath = $null - + if ($currentValueFromMachine) { <# @@ -346,7 +346,7 @@ function Set-TargetResource $finalPath = Remove-PathsFromValue -CurrentValue $currentValueFromMachine -PathsToRemove $trimmedValue } - if ([String]::IsNullOrEmpty($finalPath)) + if ([System.String]::IsNullOrEmpty($finalPath)) { Remove-EnvironmentVariable -Name $Name -Target @('Machine') Write-Verbose -Message ($script:localizedData.EnvVarRemoved -f $Name) @@ -359,13 +359,13 @@ function Set-TargetResource { Set-EnvironmentVariable -Name $Name -Value $finalPath -Target @('Machine') Write-Verbose -Message ($script:localizedData.EnvVarPathUpdated -f $Name, $currentValueFromMachine, $finalPath) - } + } } if ($setProcessVariable) { $finalPath = $null - + if ($currentValueFromProcess) { <# @@ -377,7 +377,7 @@ function Set-TargetResource $finalPath = Remove-PathsFromValue -CurrentValue $currentValueFromProcess -PathsToRemove $trimmedValue } - if ([String]::IsNullOrEmpty($finalPath)) + if ([System.String]::IsNullOrEmpty($finalPath)) { Remove-EnvironmentVariable -Name $Name -Target @('Process') Write-Verbose -Message ($script:localizedData.EnvVarRemoved -f $Name) @@ -398,7 +398,7 @@ function Set-TargetResource <# .SYNOPSIS Tests if the environment variable is in the desired state. - + .PARAMETER Name The name of the environment variable to test. @@ -426,36 +426,36 @@ function Set-TargetResource function Test-TargetResource { [CmdletBinding()] - [OutputType([Boolean])] + [OutputType([System.Boolean])] param - ( + ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, - + [Parameter()] [ValidateNotNull()] - [String] + [System.String] $Value, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', - + [Parameter()] - [Boolean] + [System.Boolean] $Path = $false, [Parameter()] [ValidateSet('Process', 'Machine')] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Target = ('Process', 'Machine') ) - - $valueSpecified = $PSBoundParameters.ContainsKey('Value') -and ($Value -ne [String]::Empty) + + $valueSpecified = $PSBoundParameters.ContainsKey('Value') -and ($Value -ne [System.String]::Empty) $currentValueFromMachine = $null $currentValueFromProcess = $null $currentPropertiesFromMachine = $null @@ -473,7 +473,7 @@ function Test-TargetResource { $currentValueFromMachine = $currentPropertiesFromMachine.$Name } - } + } else { $currentPropertiesFromMachine = Get-ItemProperty -Path $script:envVarRegPathMachine -Name $Name -ErrorAction 'SilentlyContinue' @@ -500,7 +500,7 @@ function Test-TargetResource { $currentValueToDisplay = $currentValueFromProcess } - + if (($checkMachineTarget -and ($null -eq $currentPropertiesFromMachine)) -or ($checkProcessTarget -and ($null -eq $currentValueFromProcess))) { # Variable not found @@ -513,7 +513,7 @@ function Test-TargetResource Write-Verbose ($script:localizedData.EnvVarFound -f $Name, $currentValueToDisplay) return ($Ensure -eq 'Present') } - + if (-not $Path) { # For this non-path variable, make sure that the specified $Value matches the current value. @@ -538,7 +538,7 @@ function Test-TargetResource { if (-not (Test-PathsInValue -ExistingPaths $currentValueFromMachine -QueryPaths $Value -FindCriteria 'All')) { - # If the control reached here some part of the specified path ($Value) was not found in the existing variable, return failure + # If the control reached here some part of the specified path ($Value) was not found in the existing variable, return failure Write-Verbose ($script:localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $currentValueToDisplay, $Value) return $false } @@ -548,7 +548,7 @@ function Test-TargetResource { if (-not (Test-PathsInValue -ExistingPaths $currentValueFromProcess -QueryPaths $Value -FindCriteria 'All')) { - # If the control reached here some part of the specified path ($Value) was not found in the existing variable, return failure + # If the control reached here some part of the specified path ($Value) was not found in the existing variable, return failure Write-Verbose ($script:localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $currentValueToDisplay, $Value) return $false } @@ -560,7 +560,7 @@ function Test-TargetResource } # Ensure = 'Absent' else - { + { if ($checkMachineTarget) { if (Test-PathsInValue -ExistingPaths $currentValueFromMachine -QueryPaths $Value -FindCriteria 'Any') @@ -580,7 +580,7 @@ function Test-TargetResource return $false } } - + # If the control reached here, none of the specified paths were found in the existing path-variable, return success Write-Verbose ($script:localizedData.EnvVarFoundWithMisMatchingValue -f $Name, $currentValueToDisplay, $Value) return $true @@ -590,7 +590,7 @@ function Test-TargetResource <# .SYNOPSIS Retrieves the value of the environment variable from the given Target. - + .PARAMETER Name The name of the environment variable to retrieve the value from. @@ -602,23 +602,23 @@ function Test-TargetResource function Get-EnvironmentVariable { [CmdletBinding()] - [OutputType([String])] + [OutputType([System.String])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] [ValidateSet('Process', 'Machine')] - [String] + [System.String] $Target ) $valueToReturn = $null - if ($Target -eq 'Process') + if ($Target -eq 'Process') { $valueToReturn = Get-ProcessEnvironmentVariable -Name $Name } @@ -640,27 +640,26 @@ function Get-EnvironmentVariable $valueToReturn = $retrievedProperty.$Name } } - + return $valueToReturn } <# .SYNOPSIS Wrapper function to retrieve an environment variable from the current process. - + .PARAMETER Name The name of the variable to retrieve - #> function Get-ProcessEnvironmentVariable { [CmdletBinding()] - [OutputType([String])] + [OutputType([System.String])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name ) @@ -672,28 +671,28 @@ function Get-ProcessEnvironmentVariable If there are any paths in NewPaths that aren't in CurrentValue they will be added to the current paths value and a String will be returned containing all old paths and new paths. Otherwise the original value will be returned unchanged. - + .PARAMETER CurrentValue A semicolon-separated String containing the current path values. .PARAMETER NewPaths A semicolon-separated String containing any paths that should be added to - the current value. If CurrentValue already contains a path, it will not be added. + the current value. If CurrentValue already contains a path, it will not be added. #> function Add-PathsToValue { [CmdletBinding()] - [OutputType([String])] + [OutputType([System.String])] param - ( + ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $CurrentValue, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $NewValue ) @@ -725,7 +724,7 @@ function Add-PathsToValue paths that remain, or an empty string will be returned if all paths were removed. If none of the paths in PathsToRemove are in CurrentValue then this function will return CurrentValue since nothing needs to be changed. - + .PARAMETER CurrentValue A semicolon-separated String containing the current path values. @@ -735,18 +734,18 @@ function Add-PathsToValue #> function Remove-PathsFromValue { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param - ( + ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $CurrentValue, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $PathsToRemove ) @@ -769,12 +768,12 @@ function Remove-PathsFromValue { # the current $subpath was not part of the $specifiedPaths (to be removed) so keep this $subpath in the finalPath $finalPath += $subpath + ';' - } - } - - # Remove any extraneous ';' at the end (and potentially start - as a side-effect) of the $finalPath - $finalPath = $finalPath.Trim(';') - + } + } + + # Remove any extraneous ';' at the end (and potentially start - as a side-effect) of the $finalPath + $finalPath = $finalPath.Trim(';') + if ($varAltered) { return $finalPath @@ -789,14 +788,14 @@ function Remove-PathsFromValue .SYNOPSIS Sets the value of the environment variable with the given name if a value is specified. If no value is specified, then the environment variable will be removed. - + .PARAMETER Name The name of the environment variable to set or remove. .PARAMETER Value The value to set the environment variable to. If not provided, then the variable will be removed. - + .PARAMETER Target Indicates where to set or remove the environment variable: The machine, the process, or both. The logic for User is also included here for future expansion of this resource. @@ -805,19 +804,19 @@ function Set-EnvironmentVariable { [CmdletBinding()] param - ( + ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter()] - [String] + [System.String] $Value, [Parameter(Mandatory = $true)] [ValidateSet('Process', 'Machine')] - [String[]] + [System.String[]] $Target ) @@ -825,8 +824,8 @@ function Set-EnvironmentVariable try { - # If the Value is set to [String]::Empty then nothing should be updated for the process - if (($Target -contains 'Process') -and (-not $valueSpecified -or ($Value -ne [String]::Empty))) + # If the Value is set to [System.String]::Empty then nothing should be updated for the process + if (($Target -contains 'Process') -and (-not $valueSpecified -or ($Value -ne [System.String]::Empty))) { if (-not $valueSpecified) { @@ -847,7 +846,7 @@ function Set-EnvironmentVariable $path = $script:envVarRegPathMachine - if (-not $valueSpecified) + if (-not $valueSpecified) { $environmentKey = Get-ItemProperty -Path $path -Name $Name -ErrorAction 'SilentlyContinue' @@ -866,7 +865,7 @@ function Set-EnvironmentVariable Set-ItemProperty -Path $path -Name $Name -Value $Value $environmentKey = Get-ItemProperty -Path $path -Name $Name -ErrorAction 'SilentlyContinue' - if ($null -eq $environmentKey) + if ($null -eq $environmentKey) { $message = ($script:localizedData.GetItemPropertyFailure -f $Name, $path) New-InvalidArgumentException -Message $message -ArgumentName $Name @@ -884,7 +883,7 @@ function Set-EnvironmentVariable $path = $script:envVarRegPathUser - if (-not $valueSpecified) + if (-not $valueSpecified) { $environmentKey = Get-ItemProperty -Path $path -Name $Name -ErrorAction 'SilentlyContinue' @@ -903,7 +902,7 @@ function Set-EnvironmentVariable Set-ItemProperty -Path $path -Name $Name -Value $Value $environmentKey = Get-ItemProperty -Path $path -Name $Name -ErrorAction 'SilentlyContinue' - if ($null -eq $environmentKey) + if ($null -eq $environmentKey) { $message = ($script:localizedData.GetItemPropertyFailure -f $Name, $path) New-InvalidArgumentException -Message $message -ArgumentName $Name @@ -911,7 +910,7 @@ function Set-EnvironmentVariable } } } - catch + catch { New-InvalidOperationException -Message ($script:localizedData.EnvVarSetError -f $Name, $Value) ` -ErrorRecord $_ @@ -922,13 +921,12 @@ function Set-EnvironmentVariable <# .SYNOPSIS Wrapper function to set an environment variable for the current process. - + .PARAMETER Name The name of the environment variable to set. .PARAMETER Value The value to set the environment variable to. - #> function Set-ProcessEnvironmentVariable { @@ -937,12 +935,12 @@ function Set-ProcessEnvironmentVariable ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter()] - [String] - $Value = [String]::Empty + [System.String] + $Value = [System.String]::Empty ) [System.Environment]::SetEnvironmentVariable($Name, $Value) @@ -952,7 +950,7 @@ function Set-ProcessEnvironmentVariable .SYNOPSIS Removes an environment variable from the given target(s) by calling Set-EnvironmentVariable with no Value specified. - + .PARAMETER Name The name of the environment variable to remove. @@ -963,23 +961,23 @@ function Remove-EnvironmentVariable { [CmdletBinding()] param - ( + ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] [ValidateSet('Process', 'Machine')] - [String[]] + [System.String[]] $Target ) - + try { Set-EnvironmentVariable -Name $Name -Target $Target } - catch + catch { New-InvalidOperationException -Message ($script:localizedData.EnvVarRemoveError -f $Name) ` -ErrorRecord $_ @@ -993,7 +991,7 @@ function Remove-EnvironmentVariable paths in QueryPaths are in ExistingPaths, otherwise it will return False. If FindCriteria is set to 'Any' then it will return True if any of the paths in QueryPaths are in ExistingPaths, otherwise it will return False. - + .PARAMETER ExistingPaths A semicolon-separated String containing the path values to test against. @@ -1007,21 +1005,21 @@ function Remove-EnvironmentVariable #> function Test-PathsInValue { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( - [Parameter(Mandatory = $true)] - [String] - $ExistingPaths, - [Parameter(Mandatory = $true)] - [String] + [System.String] + $ExistingPaths, + + [Parameter(Mandatory = $true)] + [System.String] $QueryPaths, - [Parameter(Mandatory = $true)] + [Parameter(Mandatory = $true)] [ValidateSet('Any', 'All')] - [String] + [System.String] $FindCriteria ) @@ -1038,30 +1036,30 @@ function Test-PathsInValue { # Found this $queryPath in the existing paths, return $true return $true - } + } } # If the control reached here, none of the QueryPaths were found in ExistingPaths - return $false + return $false } 'All' { foreach ($queryPath in $queryPathList) { - if ($queryPath) + if ($queryPath) { if ($existingPathList -notcontains $queryPath) { - # The current $queryPath wasn't found in any of the $existingPathList, return false + # The current $queryPath wasn't found in any of the $existingPathList, return false return $false } - } + } } # If the control reached here, all of the QueryPaths were found in ExistingPaths return $true - } + } } } @@ -1072,7 +1070,7 @@ function Test-PathsInValue name and its current value on the machine. This is to most closely represent what the actual API call returns. If an environment variable with the given name is not found, then $null will be returned. - + .PARAMETER Name The name of the environment variable to retrieve the value of. #> @@ -1084,14 +1082,14 @@ function Get-EnvironmentVariableWithoutExpanding ( [Parameter(Mandatory = $true)] [ValidateNotNull()] - [String] + [System.String] $Name ) $path = $script:envVarRegPathMachine $pathTokens = $path.Split('\',[System.StringSplitOptions]::RemoveEmptyEntries) $entry = $pathTokens[1..($pathTokens.Count - 1)] -join '\' - + # Since the target registry path coming to this function is hardcoded for local machine $hive = [Microsoft.Win32.Registry]::LocalMachine @@ -1100,14 +1098,14 @@ function Get-EnvironmentVariableWithoutExpanding try { $key = $hive.OpenSubKey($entry) - + $valueNames = $key.GetValueNames() if ($valueNames -inotcontains $Name) { return $null } - - [String] $value = Get-KeyValue -Name $Name -Key $key + + [System.String] $value = Get-KeyValue -Name $Name -Key $key $noteProperties.Add($Name, $value) } finally @@ -1127,7 +1125,7 @@ function Get-EnvironmentVariableWithoutExpanding .SYNOPSIS Wrapper function to get the value of the environment variable with the given name from the specified registry key. - + .PARAMETER Name The name of the environment variable to retrieve the value of. @@ -1136,13 +1134,13 @@ function Get-EnvironmentVariableWithoutExpanding #> function Get-KeyValue { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNull()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] diff --git a/DscResources/MSFT_EnvironmentResource/en-US/MSFT_EnvironmentResource.strings.psd1 b/DscResources/MSFT_EnvironmentResource/en-US/MSFT_EnvironmentResource.strings.psd1 index 496cc10..9ff1fef 100644 --- a/DscResources/MSFT_EnvironmentResource/en-US/MSFT_EnvironmentResource.strings.psd1 +++ b/DscResources/MSFT_EnvironmentResource/en-US/MSFT_EnvironmentResource.strings.psd1 @@ -1,4 +1,4 @@ -# Localized resources for MSFT_EnvironmentResource +# Localized resources for MSFT_EnvironmentResource ConvertFrom-StringData @' ArgumentTooLong = Argument is too long. diff --git a/DscResources/MSFT_GroupResource/MSFT_GroupResource.psm1 b/DscResources/MSFT_GroupResource/MSFT_GroupResource.psm1 index 794728a..1efc25f 100644 --- a/DscResources/MSFT_GroupResource/MSFT_GroupResource.psm1 +++ b/DscResources/MSFT_GroupResource/MSFT_GroupResource.psm1 @@ -87,13 +87,13 @@ if (-not (Test-IsNanoServer)) #> function Get-TargetResource { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] @@ -186,28 +186,28 @@ function Set-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude, [Parameter()] @@ -284,34 +284,34 @@ function Set-TargetResource #> function Test-TargetResource { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude, [Parameter()] @@ -347,13 +347,13 @@ function Test-TargetResource #> function Get-TargetResourceOnFullSKU { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] @@ -416,13 +416,13 @@ function Get-TargetResourceOnFullSKU #> function Get-TargetResourceOnNanoServer { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] @@ -520,28 +520,28 @@ function Set-TargetResourceOnFullSKU ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude, [Parameter()] @@ -642,7 +642,7 @@ function Set-TargetResourceOnFullSKU if ($Members.Count -eq 0 -and $null -ne $actualMembersAsPrincipals -and $actualMembersAsPrincipals.Count -ne 0) { - Clear-GroupMembers -Group $group + Clear-GroupMember -Group $group $saveChanges = $true } elseif ($Members.Count -ne 0) @@ -877,28 +877,28 @@ function Set-TargetResourceOnNanoServer ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude, [Parameter()] @@ -992,7 +992,7 @@ function Set-TargetResourceOnNanoServer } elseif ($PSBoundParameters.ContainsKey('MembersToInclude') -or $PSBoundParameters.ContainsKey('MembersToExclude')) { - [array]$groupMembers = Get-MembersOnNanoServer -Group $group + [System.Array] $groupMembers = Get-MembersOnNanoServer -Group $group $uniqueMembersToInclude = $MembersToInclude | Select-Object -Unique $uniqueMembersToExclude = $MembersToExclude | Select-Object -Unique @@ -1110,34 +1110,34 @@ function Set-TargetResourceOnNanoServer #> function Test-TargetResourceOnFullSKU { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude, [Parameter()] @@ -1377,34 +1377,34 @@ function Test-TargetResourceOnFullSKU #> function Test-TargetResourceOnNanoServer { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude, [Parameter()] @@ -1458,7 +1458,7 @@ function Test-TargetResourceOnNanoServer } } - [array]$groupMembers = Get-MembersOnNanoServer -Group $group + [System.Array] $groupMembers = Get-MembersOnNanoServer -Group $group # Remove duplicate names as strings. $uniqueMembers = $Members | Select-Object -Unique @@ -1600,7 +1600,7 @@ function Get-MembersOnFullSKU [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Hashtable] + [System.Collections.Hashtable] [AllowEmptyCollection()] $PrincipalContextCache, @@ -1686,7 +1686,7 @@ function Get-MembersAsPrincipalsList [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Hashtable] + [System.Collections.Hashtable] [AllowEmptyCollection()] $PrincipalContextCache, @@ -1804,7 +1804,7 @@ function Assert-GroupNameValid ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName ) @@ -1813,7 +1813,7 @@ function Assert-GroupNameValid if ($GroupName.IndexOfAny($invalidCharacters) -ne -1) { New-InvalidArgumentException -ArgumentName 'GroupName' ` - -Message ($script:localizedData.InvalidGroupName -f $GroupName, [String]::Join(' ', $invalidCharacters)) + -Message ($script:localizedData.InvalidGroupName -f $GroupName, [System.String]::Join(' ', $invalidCharacters)) } $nameContainsOnlyWhitspaceOrDots = $true @@ -1821,7 +1821,7 @@ function Assert-GroupNameValid # Check if the name consists of only periods and/or white spaces. for ($groupNameIndex = 0; $groupNameIndex -lt $GroupName.Length; $groupNameIndex++) { - if (-not [Char]::IsWhiteSpace($GroupName, $groupNameIndex) -and $GroupName[$groupNameIndex] -ne '.') + if (-not [System.Char]::IsWhiteSpace($GroupName, $groupNameIndex) -and $GroupName[$groupNameIndex] -ne '.') { $nameContainsOnlyWhitspaceOrDots = $false break @@ -1831,7 +1831,7 @@ function Assert-GroupNameValid if ($nameContainsOnlyWhitspaceOrDots) { New-InvalidArgumentException -ArgumentName 'GroupName' ` - -Message ($script:localizedData.InvalidGroupName -f $GroupName, [String]::Join(' ', $invalidCharacters)) + -Message ($script:localizedData.InvalidGroupName -f $GroupName, [System.String]::Join(' ', $invalidCharacters)) } } @@ -1859,12 +1859,12 @@ function ConvertTo-UniquePrincipalsList param ( [Parameter(Mandatory = $true)] - [String[]] + [System.String[]] $MemberNames, [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Hashtable] + [System.Collections.Hashtable] [AllowEmptyCollection()] $PrincipalContextCache, @@ -1949,12 +1949,12 @@ function ConvertTo-Principal ( [Parameter(Mandatory = $true)] [ValidateNotNull()] - [String] + [System.String] $MemberName, [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Hashtable] + [System.Collections.Hashtable] [AllowEmptyCollection()] $PrincipalContextCache, @@ -2051,7 +2051,7 @@ function Resolve-SidToPrincipal $PrincipalContext, [Parameter(Mandatory = $true)] - [String] + [System.String] $Scope ) @@ -2101,7 +2101,7 @@ function Get-PrincipalContext ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Scope, [Parameter()] @@ -2111,7 +2111,7 @@ function Get-PrincipalContext [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Hashtable] + [System.Collections.Hashtable] [AllowEmptyCollection()] $PrincipalContextCache, @@ -2151,7 +2151,7 @@ function Get-PrincipalContext # Create a PrincipalContext targeting $Scope using the network credentials that were passed in. $credentialDomain = $Credential.GetNetworkCredential().Domain $credentialUserName = $Credential.GetNetworkCredential().UserName - if ($credentialDomain -ne [String]::Empty) + if ($credentialDomain -ne [System.String]::Empty) { $principalContextName = "$credentialDomain\$credentialUserName" } @@ -2191,13 +2191,13 @@ function Get-PrincipalContext #> function Test-IsLocalMachine { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Scope ) @@ -2284,7 +2284,7 @@ function Split-MemberName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $MemberName ) @@ -2370,7 +2370,7 @@ function Find-Principal $PrincipalContext, [Parameter(Mandatory = $true)] - [String] + [System.String] $IdentityValue, [Parameter()] @@ -2415,7 +2415,7 @@ function Get-Group ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter(Mandatory = $true)] @@ -2470,7 +2470,7 @@ function Get-GroupMembersFromDirectoryEntry .PARAMETER Group The group to clear the members of. #> -function Clear-GroupMembers +function Clear-GroupMember { [CmdletBinding()] param diff --git a/DscResources/MSFT_MsiPackage/MSFT_MsiPackage.psm1 b/DscResources/MSFT_MsiPackage/MSFT_MsiPackage.psm1 index 145ce96..1a24fa0 100644 --- a/DscResources/MSFT_MsiPackage/MSFT_MsiPackage.psm1 +++ b/DscResources/MSFT_MsiPackage/MSFT_MsiPackage.psm1 @@ -1,4 +1,4 @@ -# Suppress Global Vars PSSA Error because $global:DSCMachineStatus must be allowed +# Suppress Global Vars PSSA Error because $global:DSCMachineStatus must be allowed [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '')] [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')] param() @@ -30,18 +30,18 @@ $script:msiTools = $null #> function Get-TargetResource { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ProductId, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) @@ -90,7 +90,7 @@ function Get-TargetResource .PARAMETER Arguments The arguments to pass to the MSI package during installation or uninstallation if needed. - + .PARAMETER Credential The credential of a user account to be used to mount a UNC path if needed. @@ -122,51 +122,51 @@ function Set-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ProductId, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Arguments, [Parameter()] - [PSCredential] + [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter()] - [String] + [System.String] $LogPath, [Parameter()] - [String] + [System.String] $FileHash, [Parameter()] [ValidateSet('SHA1', 'SHA256', 'SHA384', 'SHA512', 'MD5', 'RIPEMD160')] - [String] + [System.String] $HashAlgorithm = 'SHA256', [Parameter()] - [String] + [System.String] $SignerSubject, [Parameter()] - [String] + [System.String] $SignerThumbprint, [Parameter()] - [String] + [System.String] $ServerCertificateValidationCallback, [Parameter()] @@ -223,7 +223,7 @@ function Set-TargetResource if ($uri.IsUnc) { $psDriveArgs = @{ - Name = [Guid]::NewGuid() + Name = [System.Guid]::NewGuid() PSProvider = 'FileSystem' Root = Split-Path -Path $localPath } @@ -269,7 +269,7 @@ function Set-TargetResource } finally { - if ($null -ne $responseStream) + if ((Test-Path -Path variable:responseStream) -and ($null -ne $responseStream)) { Close-Stream -Stream $responseStream } @@ -298,8 +298,8 @@ function Set-TargetResource # Check if the MSI package specifies the ProductCode, and if so make sure they match $productCode = Get-MsiProductCode -Path $Path - - if ((-not [String]::IsNullOrEmpty($identifyingNumber)) -and ($identifyingNumber -ne $productCode)) + + if ((-not [System.String]::IsNullOrEmpty($identifyingNumber)) -and ($identifyingNumber -ne $productCode)) { New-InvalidArgumentException -ArgumentName 'ProductId' -Message ($script:localizedData.InvalidId -f $identifyingNumber, $productCode) } @@ -369,7 +369,7 @@ function Set-TargetResource .PARAMETER ProductId The identifying number used to find the package, usually a GUID. - + .PARAMETER Path Not Used in Test-TargetResource @@ -407,57 +407,57 @@ function Set-TargetResource #> function Test-TargetResource { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ProductId, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Arguments, [Parameter()] - [PSCredential] + [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter()] - [String] + [System.String] $LogPath, [Parameter()] - [String] + [System.String] $FileHash, [Parameter()] [ValidateSet('SHA1', 'SHA256', 'SHA384', 'SHA512', 'MD5', 'RIPEMD160')] - [String] + [System.String] $HashAlgorithm = 'SHA256', [Parameter()] - [String] + [System.String] $SignerSubject, [Parameter()] - [String] + [System.String] $SignerThumbprint, [Parameter()] - [String] + [System.String] $ServerCertificateValidationCallback, [Parameter()] @@ -497,7 +497,7 @@ function Assert-PathExtensionValid ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) @@ -520,19 +520,19 @@ function Assert-PathExtensionValid #> function Convert-PathToUri { - [OutputType([Uri])] + [OutputType([System.Uri])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) try { - $uri = [Uri]$Path + $uri = [System.Uri] $Path } catch { @@ -559,20 +559,20 @@ function Convert-PathToUri #> function Convert-ProductIdToIdentifyingNumber { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ProductId ) try { Write-Verbose -Message ($script:localizedData.ParsingProductIdAsAnIdentifyingNumber -f $ProductId) - $identifyingNumber = '{{{0}}}' -f [Guid]::Parse($ProductId).ToString().ToUpper() + $identifyingNumber = '{{{0}}}' -f [System.Guid]::Parse($ProductId).ToString().ToUpper() Write-Verbose -Message ($script:localizedData.ParsedProductIdAsIdentifyingNumber -f $ProductId, $identifyingNumber) return $identifyingNumber @@ -598,7 +598,7 @@ function Get-ProductEntry param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $IdentifyingNumber ) @@ -607,7 +607,7 @@ function Get-ProductEntry $productEntry = $null - if (-not [String]::IsNullOrEmpty($IdentifyingNumber)) + if (-not [System.String]::IsNullOrEmpty($IdentifyingNumber)) { $productEntryKeyLocation = Join-Path -Path $uninstallRegistryKey -ChildPath $IdentifyingNumber $productEntry = Get-Item -Path $productEntryKeyLocation -ErrorAction 'SilentlyContinue' @@ -631,7 +631,7 @@ function Get-ProductEntry #> function Get-ProductEntryInfo { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( @@ -646,7 +646,7 @@ function Get-ProductEntryInfo { try { - $installDate = '{0:d}' -f [DateTime]::ParseExact($installDate, 'yyyyMMdd',[System.Globalization.CultureInfo]::InvariantCulture).Date + $installDate = '{0:d}' -f [System.DateTime]::ParseExact($installDate, 'yyyyMMdd',[System.Globalization.CultureInfo]::CurrentCulture).Date } catch { @@ -695,7 +695,7 @@ function Get-ProductEntryInfo #> function Get-ProductEntryValue { - [OutputType([Object])] + [OutputType([System.Object])] [CmdletBinding()] param ( @@ -704,7 +704,7 @@ function Get-ProductEntryValue $ProductEntry, [Parameter(Mandatory = $true)] - [String] + [System.String] $Property ) @@ -725,7 +725,7 @@ function New-LogFile param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $LogPath ) @@ -765,11 +765,11 @@ function Get-WebRequestResponse param ( [Parameter(Mandatory = $true)] - [Uri] + [System.Uri] $Uri, [Parameter()] - [String] + [System.String] $ServerCertificateValidationCallback ) @@ -779,23 +779,23 @@ function Get-WebRequestResponse Write-Verbose -Message ($script:localizedData.CreatingTheSchemeStream -f $uriScheme) $webRequest = Get-WebRequest -Uri $Uri - + Write-Verbose -Message ($script:localizedData.SettingDefaultCredential) $webRequest.Credentials = [System.Net.CredentialCache]::DefaultCredentials $webRequest.AuthenticationLevel = [System.Net.Security.AuthenticationLevel]::None - + if ($uriScheme -eq 'http') { # Default value is MutualAuthRequested, which applies to the https scheme Write-Verbose -Message ($script:localizedData.SettingAuthenticationLevel) $webRequest.AuthenticationLevel = [System.Net.Security.AuthenticationLevel]::None } - elseif ($uriScheme -eq 'https' -and -not [String]::IsNullOrEmpty($ServerCertificateValidationCallback)) + elseif ($uriScheme -eq 'https' -and -not [System.String]::IsNullOrEmpty($ServerCertificateValidationCallback)) { Write-Verbose -Message $script:localizedData.SettingCertificateValidationCallback $webRequest.ServerCertificateValidationCallBack = (Get-ScriptBlock -FunctionName $ServerCertificateValidationCallback) } - + Write-Verbose -Message ($script:localizedData.GettingTheSchemeResponseStream -f $uriScheme) $responseStream = Get-WebRequestResponseStream -WebRequest $webRequest @@ -822,7 +822,7 @@ function Get-WebRequest param ( [Parameter(Mandatory = $true)] - [Uri] + [System.Uri] $Uri ) @@ -848,7 +848,7 @@ function Get-WebRequestResponseStream $WebRequest ) - return (([System.Net.HttpWebRequest]$WebRequest).GetResponse()).GetResponseStream() + return (([System.Net.HttpWebRequest] $WebRequest).GetResponse()).GetResponseStream() } <# @@ -861,16 +861,16 @@ function Get-WebRequestResponseStream #> function Get-ScriptBlock { - [OutputType([ScriptBlock])] + [OutputType([System.Management.Automation.ScriptBlock])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $FunctionName ) - return [ScriptBlock]::Create($FunctionName) + return [System.Management.Automation.ScriptBlock]::Create($FunctionName) } <# @@ -959,32 +959,32 @@ function Assert-FileValid param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Path, [Parameter()] - [String] + [System.String] $FileHash, [Parameter()] - [String] + [System.String] $HashAlgorithm = 'SHA256', [Parameter()] - [String] + [System.String] $SignerThumbprint, [Parameter()] - [String] + [System.String] $SignerSubject ) - if (-not [String]::IsNullOrEmpty($FileHash)) + if (-not [System.String]::IsNullOrEmpty($FileHash)) { Assert-FileHashValid -Path $Path -Hash $FileHash -Algorithm $HashAlgorithm } - if (-not [String]::IsNullOrEmpty($SignerThumbprint) -or -not [String]::IsNullOrEmpty($SignerSubject)) + if (-not [System.String]::IsNullOrEmpty($SignerThumbprint) -or -not [System.String]::IsNullOrEmpty($SignerSubject)) { Assert-FileSignatureValid -Path $Path -Thumbprint $SignerThumbprint -Subject $SignerSubject } @@ -1010,15 +1010,15 @@ function Assert-FileHashValid param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] - [String] + [System.String] $Hash, [Parameter()] - [String] + [System.String] $Algorithm = 'SHA256' ) @@ -1051,15 +1051,15 @@ function Assert-FileSignatureValid param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Path, [Parameter()] - [String] + [System.String] $Thumbprint, [Parameter()] - [String] + [System.String] $Subject ) @@ -1076,12 +1076,12 @@ function Assert-FileSignatureValid Write-Verbose -Message ($script:localizedData.FileHasValidSignature -f $Path, $signature.SignerCertificate.Thumbprint, $signature.SignerCertificate.Subject) } - if (-not [String]::IsNullOrEmpty($Subject) -and ($signature.SignerCertificate.Subject -notlike $Subject)) + if (-not [System.String]::IsNullOrEmpty($Subject) -and ($signature.SignerCertificate.Subject -notlike $Subject)) { New-InvalidArgumentException -ArgumentName 'SignerSubject' -Message ($script:localizedData.WrongSignerSubject -f $Path, $Subject) } - if (-not [String]::IsNullOrEmpty($Thumbprint) -and ($signature.SignerCertificate.Thumbprint -ne $Thumbprint)) + if (-not [System.String]::IsNullOrEmpty($Thumbprint) -and ($signature.SignerCertificate.Thumbprint -ne $Thumbprint)) { New-InvalidArgumentException -ArgumentName 'SignerThumbprint' -Message ($script:localizedData.WrongSignerThumbprint -f $Path, $Thumbprint) } @@ -1112,31 +1112,31 @@ function Assert-FileSignatureValid #> function Start-MsiProcess { - [OutputType([Int32])] + [OutputType([System.Int32])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $IdentifyingNumber, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $Arguments, [Parameter()] - [String] + [System.String] $LogPath, [Parameter()] @@ -1149,9 +1149,9 @@ function Start-MsiProcess # Necessary for I/O redirection $startInfo.UseShellExecute = $false - + $startInfo.FileName = "$env:winDir\system32\msiexec.exe" - + if ($Ensure -eq 'Present') { $startInfo.Arguments = '/i "{0}"' -f $Path @@ -1160,31 +1160,31 @@ function Start-MsiProcess else { $productEntry = Get-ProductEntry -IdentifyingNumber $identifyingNumber - + $id = Split-Path -Path $productEntry.Name -Leaf $startInfo.Arguments = ('/x{0}' -f $id) } - - if (-not [String]::IsNullOrEmpty($LogPath)) + + if (-not [System.String]::IsNullOrEmpty($LogPath)) { $startInfo.Arguments += (' /log "{0}"' -f $LogPath) } - + $startInfo.Arguments += ' /quiet /norestart' - - if (-not [String]::IsNullOrEmpty($Arguments)) + + if (-not [System.String]::IsNullOrEmpty($Arguments)) { # Append any specified arguments with a space $startInfo.Arguments += (' {0}' -f $Arguments) } - + Write-Verbose -Message ($script:localizedData.StartingWithStartInfoFileNameStartInfoArguments -f $startInfo.FileName, $startInfo.Arguments) - + $exitCode = 0 - + try { - if (-not [String]::IsNullOrEmpty($RunAsCredential)) + if (-not [System.String]::IsNullOrEmpty($RunAsCredential)) { $commandLine = ('"{0}" {1}' -f $startInfo.FileName, $startInfo.Arguments) $exitCode = Invoke-PInvoke -CommandLine $commandLine -RunAsCredential $RunAsCredential @@ -1222,7 +1222,7 @@ function Invoke-PInvoke param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $CommandLine, [Parameter(Mandatory = $true)] @@ -1277,13 +1277,13 @@ function Invoke-Process #> function Get-MsiProductCode { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) @@ -1349,7 +1349,7 @@ function Get-MsiTool return GetPackageProperty(msi, "ProductName"); } '@ - + # Check if the the type is already defined if (([System.Management.Automation.PSTypeName]'Microsoft.Windows.DesiredStateConfiguration.MsiPackageResource.MsiTools').Type) { diff --git a/DscResources/MSFT_MsiPackage/en-US/MSFT_MsiPackage.strings.psd1 b/DscResources/MSFT_MsiPackage/en-US/MSFT_MsiPackage.strings.psd1 index ecb56be..9f33d00 100644 --- a/DscResources/MSFT_MsiPackage/en-US/MSFT_MsiPackage.strings.psd1 +++ b/DscResources/MSFT_MsiPackage/en-US/MSFT_MsiPackage.strings.psd1 @@ -1,4 +1,4 @@ -# Localized resources for MSFT_MsiPackage +# Localized resources for MSFT_MsiPackage ConvertFrom-StringData @' CheckingFileHash = Checking file '{0}' for expected {2} hash value of {1} diff --git a/DscResources/MSFT_RegistryResource/MSFT_RegistryResource.psm1 b/DscResources/MSFT_RegistryResource/MSFT_RegistryResource.psm1 index 2520083..5085010 100644 --- a/DscResources/MSFT_RegistryResource/MSFT_RegistryResource.psm1 +++ b/DscResources/MSFT_RegistryResource/MSFT_RegistryResource.psm1 @@ -39,27 +39,27 @@ $script:registryDriveRoots = @{ function Get-TargetResource { [CmdletBinding()] - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Key, [Parameter(Mandatory = $true)] [ValidateNotNull()] - [String] + [System.String] [AllowEmptyString()] $ValueName, [Parameter()] - [String[]] + [System.String[]] $ValueData, [Parameter()] [ValidateSet('String', 'Binary', 'DWord', 'QWord', 'MultiString', 'ExpandString')] - [String] + [System.String] $ValueType ) @@ -86,7 +86,7 @@ function Get-TargetResource Write-Verbose -Message ($script:localizedData.RegistryKeyExists -f $Key) # Check if the user specified a value name to retrieve - $valueNameSpecified = (-not [String]::IsNullOrEmpty($ValueName)) -or $PSBoundParameters.ContainsKey('ValueType') -or $PSBoundParameters.ContainsKey('ValueData') + $valueNameSpecified = (-not [System.String]::IsNullOrEmpty($ValueName)) -or $PSBoundParameters.ContainsKey('ValueType') -or $PSBoundParameters.ContainsKey('ValueData') if ($valueNameSpecified) { @@ -144,10 +144,10 @@ function Get-TargetResource .PARAMETER Ensure Specifies whether or not the registry key with the given path and the registry key value with the given name should exist. - + To ensure that the registry key and value exists, set this property to Present. To ensure that the registry key and value do not exist, set this property to Absent. - + The default value is Present. .PARAMETER ValueData @@ -155,7 +155,7 @@ function Get-TargetResource .PARAMETER ValueType The type of the value to set. - + The supported types are: String (REG_SZ) Binary (REG-BINARY) @@ -169,12 +169,12 @@ function Get-TargetResource If specified, DWORD/QWORD value data is presented in hexadecimal format. Not valid for other value types. - + The default value is $false. .PARAMETER Force Specifies whether or not to overwrite the registry key with the given path with the new - value if it is already present. + value if it is already present. #> function Set-TargetResource { @@ -183,36 +183,36 @@ function Set-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Key, [Parameter(Mandatory = $true)] [ValidateNotNull()] - [String] + [System.String] [AllowEmptyString()] $ValueName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] [ValidateNotNull()] - [String[]] + [System.String[]] $ValueData = @(), [Parameter()] [ValidateSet('String', 'Binary', 'DWord', 'QWord', 'MultiString', 'ExpandString')] - [String] + [System.String] $ValueType = 'String', [Parameter()] - [Boolean] + [System.Boolean] $Hex = $false, [Parameter()] - [Boolean] + [System.Boolean] $Force = $false ) @@ -239,7 +239,7 @@ function Set-TargetResource { Write-Verbose -Message ($script:localizedData.RegistryKeyExists -f $Key) - $valueNameSpecified = (-not [String]::IsNullOrEmpty($ValueName)) -or $PSBoundParameters.ContainsKey('ValueType') -or $PSBoundParameters.ContainsKey('ValueData') + $valueNameSpecified = (-not [System.String]::IsNullOrEmpty($ValueName)) -or $PSBoundParameters.ContainsKey('ValueType') -or $PSBoundParameters.ContainsKey('ValueData') # Check if the user wants to set a registry key value if ($valueNameSpecified) @@ -295,7 +295,7 @@ function Set-TargetResource Write-Verbose -Message ($script:localizedData.OverwritingRegistryKeyValue -f $valueDisplayName, $Key) $null = Set-RegistryKeyValue -RegistryKeyName $registryKeyName -RegistryKeyValueName $ValueName -RegistryKeyValue $expectedRegistryKeyValue -ValueType $ValueType } - } + } } } else @@ -304,9 +304,9 @@ function Set-TargetResource if ($null -ne $actualRegistryKeyValue) { Write-Verbose -Message ($script:localizedData.RemovingRegistryKeyValue -f $valueDisplayName, $Key) - + # If the specified registry key value exists, check if the user specified a registry key value with a name to remove - if (-not [String]::IsNullOrEmpty($ValueName)) + if (-not [System.String]::IsNullOrEmpty($ValueName)) { # If the user specified a registry key value with a name to remove, remove the registry key value with the specified name $null = Remove-ItemProperty -Path $Key -Name $ValueName -Force @@ -359,7 +359,7 @@ function Set-TargetResource .PARAMETER Ensure Specifies whether or not the registry key and value should exist. - + To test that they exist, set this property to "Present". To test that they do not exist, set the property to "Absent". The default value is "Present". @@ -369,7 +369,7 @@ function Set-TargetResource .PARAMETER ValueType The type of the value. - + The supported types are: String (REG_SZ) Binary (REG-BINARY) @@ -387,41 +387,41 @@ function Set-TargetResource function Test-TargetResource { [CmdletBinding()] - [OutputType([Boolean])] + [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Key, [Parameter(Mandatory = $true)] [AllowEmptyString()] [ValidateNotNull()] - [String] + [System.String] $ValueName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] [ValidateNotNull()] - [String[]] + [System.String[]] $ValueData = @(), [Parameter()] [ValidateSet('String', 'Binary', 'DWord', 'QWord', 'MultiString', 'ExpandString')] - [String] + [System.String] $ValueType = 'String', [Parameter()] - [Boolean] + [System.Boolean] $Hex = $false, [Parameter()] - [Boolean] + [System.Boolean] $Force = $false ) @@ -447,7 +447,7 @@ function Test-TargetResource $registryResource = Get-TargetResource @getTargetResourceParameters # Check if the user specified a value name to retrieve - $valueNameSpecified = (-not [String]::IsNullOrEmpty($ValueName)) -or $PSBoundParameters.ContainsKey('ValueType') -or $PSBoundParameters.ContainsKey('ValueData') + $valueNameSpecified = (-not [System.String]::IsNullOrEmpty($ValueName)) -or $PSBoundParameters.ContainsKey('ValueType') -or $PSBoundParameters.ContainsKey('ValueData') if ($valueNameSpecified) { @@ -542,13 +542,13 @@ function Test-TargetResource #> function Get-PathRoot { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) @@ -572,13 +572,13 @@ function Get-PathRoot #> function ConvertTo-RegistryDriveName { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $RegistryDriveRoot ) @@ -608,13 +608,13 @@ function ConvertTo-RegistryDriveName #> function Get-RegistryDriveName { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $RegistryKeyPath ) @@ -634,7 +634,7 @@ function Get-RegistryDriveName { $registryDriveName = ConvertTo-RegistryDriveName -RegistryDriveRoot $registryKeyPathRoot - if ([String]::IsNullOrEmpty($registryDriveName)) + if ([System.String]::IsNullOrEmpty($registryDriveName)) { New-InvalidArgumentException -ArgumentName 'Key' -Message ($script:localizedData.InvalidRegistryDrive -f $registryKeyPathRoot) } @@ -657,7 +657,7 @@ function Mount-RegistryDrive ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $RegistryDriveName ) @@ -707,12 +707,12 @@ function Open-RegistrySubKey $ParentKey, [Parameter(Mandatory = $true)] - [String] + [System.String] [AllowEmptyString()] $SubKey, [Parameter()] - [Switch] + [System.Management.Automation.SwitchParameter] $WriteAccessAllowed ) @@ -744,11 +744,11 @@ function Get-RegistryKey ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $RegistryKeyPath, [Parameter()] - [Switch] + [System.Management.Automation.SwitchParameter] $WriteAccessAllowed ) @@ -788,20 +788,20 @@ function Get-RegistryKey #> function Get-RegistryKeyValueDisplayName { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] [AllowNull()] [AllowEmptyString()] + [System.String] $RegistryKeyValueName ) $registryKeyValueDisplayName = $RegistryKeyValueName - if ([String]::IsNullOrEmpty($RegistryKeyValueName)) + if ([System.String]::IsNullOrEmpty($RegistryKeyValueName)) { $registryKeyValueDisplayName = $script:localizedData.DefaultValueDisplayName } @@ -822,7 +822,7 @@ function Get-RegistryKeyValueDisplayName #> function Get-RegistryKeyValue { - [OutputType([Object[]])] + [OutputType([System.Object[]])] [CmdletBinding()] param ( @@ -832,8 +832,8 @@ function Get-RegistryKeyValue [Parameter(Mandatory = $true)] [ValidateNotNull()] - [String] [AllowEmptyString()] + [System.String] $RegistryKeyValueName ) @@ -856,7 +856,7 @@ function Get-RegistryKeyValue #> function Get-RegistryKeyValueType { - [OutputType([Type])] + [OutputType([System.Type])] [CmdletBinding()] param ( @@ -866,8 +866,8 @@ function Get-RegistryKeyValueType [Parameter(Mandatory = $true)] [ValidateNotNull()] - [String] [AllowEmptyString()] + [System.String] $RegistryKeyValueName ) @@ -883,14 +883,14 @@ function Get-RegistryKeyValueType #> function Convert-ByteArrayToHexString { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Object[]] [AllowEmptyCollection()] + [System.Object[]] $ByteArray ) @@ -916,23 +916,23 @@ function Convert-ByteArrayToHexString #> function ConvertTo-ReadableString { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [Object[]] [AllowNull()] [AllowEmptyCollection()] + [System.Object[]] $RegistryKeyValue, [Parameter(Mandatory = $true)] [ValidateSet('String', 'Binary', 'DWord', 'QWord', 'MultiString', 'ExpandString')] - [String] + [System.String] $RegistryKeyValueType ) - $registryKeyValueAsString = [String]::Empty + $registryKeyValueAsString = [System.String]::Empty if ($null -ne $RegistryKeyValue) { @@ -941,13 +941,13 @@ function ConvertTo-ReadableString { $RegistryKeyValue = Convert-ByteArrayToHexString -ByteArray $RegistryKeyValue } - + if ($RegistryKeyValueType -ne 'MultiString') { - $RegistryKeyValue = [String[]]@() + $RegistryKeyValue + $RegistryKeyValue = [System.String[]] @() + $RegistryKeyValue } - if ($RegistryKeyValue.Count -eq 1 -and -not [String]::IsNullOrEmpty($RegistryKeyValue[0])) + if ($RegistryKeyValue.Count -eq 1 -and -not [System.String]::IsNullOrEmpty($RegistryKeyValue[0])) { $registryKeyValueAsString = $RegistryKeyValue[0].ToString() } @@ -983,7 +983,7 @@ function New-RegistrySubKey [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $SubKeyName ) @@ -1006,7 +1006,7 @@ function New-RegistryKey ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $RegistryKeyPath ) @@ -1038,7 +1038,7 @@ function New-RegistryKey #> function Get-RegistryKeyName { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( @@ -1059,14 +1059,14 @@ function Get-RegistryKeyName #> function ConvertTo-Binary { - [OutputType([Byte[]])] + [OutputType([System.Byte[]])] [CmdletBinding()] param ( [Parameter()] [AllowNull()] - [String[]] [AllowEmptyCollection()] + [System.String[]] $RegistryKeyValue ) @@ -1075,9 +1075,9 @@ function ConvertTo-Binary New-InvalidArgumentException -ArgumentName 'ValueData' -Message ($script:localizedData.ArrayNotAllowedForExpectedType -f 'Binary') } - $binaryRegistryKeyValue = [Byte[]] @() + $binaryRegistryKeyValue = [System.Byte[]] @() - if (($null -ne $RegistryKeyValue) -and ($RegistryKeyValue.Count -eq 1) -and (-not [String]::IsNullOrEmpty($RegistryKeyValue[0]))) + if (($null -ne $RegistryKeyValue) -and ($RegistryKeyValue.Count -eq 1) -and (-not [System.String]::IsNullOrEmpty($RegistryKeyValue[0]))) { $singleRegistryKeyValue = $RegistryKeyValue[0] @@ -1095,7 +1095,7 @@ function ConvertTo-Binary { for ($singleRegistryKeyValueIndex = 0 ; $singleRegistryKeyValueIndex -lt ($singleRegistryKeyValue.Length - 1) ; $singleRegistryKeyValueIndex = $singleRegistryKeyValueIndex + 2) { - $binaryRegistryKeyValue += [Byte]::Parse($singleRegistryKeyValue.Substring($singleRegistryKeyValueIndex, 2), 'HexNumber') + $binaryRegistryKeyValue += [System.Byte]::Parse($singleRegistryKeyValue.Substring($singleRegistryKeyValueIndex, 2), 'HexNumber') } } catch @@ -1122,12 +1122,12 @@ function ConvertTo-DWord ( [Parameter()] [AllowNull()] - [String[]] [AllowEmptyCollection()] + [System.String[]] $RegistryKeyValue, [Parameter()] - [Boolean] + [System.Boolean] $Hex = $false ) @@ -1138,7 +1138,7 @@ function ConvertTo-DWord $dwordRegistryKeyValue = [System.Int32] 0 - if (($null -ne $RegistryKeyValue) -and ($RegistryKeyValue.Count -eq 1) -and (-not [String]::IsNullOrEmpty($RegistryKeyValue[0]))) + if (($null -ne $RegistryKeyValue) -and ($RegistryKeyValue.Count -eq 1) -and (-not [System.String]::IsNullOrEmpty($RegistryKeyValue[0]))) { $singleRegistryKeyValue = $RegistryKeyValue[0] @@ -1152,7 +1152,7 @@ function ConvertTo-DWord $currentCultureInfo = [System.Globalization.CultureInfo]::CurrentCulture $referenceValue = $null - if ([System.Int32]::TryParse($singleRegistryKeyValue, 'HexNumber', $currentCultureInfo, [Ref] $referenceValue)) + if ([System.Int32]::TryParse($singleRegistryKeyValue, 'HexNumber', $currentCultureInfo, [ref] $referenceValue)) { $dwordRegistryKeyValue = $referenceValue } @@ -1179,22 +1179,22 @@ function ConvertTo-DWord #> function ConvertTo-MultiString { - [OutputType([String[]])] + [OutputType([System.String[]])] [CmdletBinding()] param ( [Parameter()] [AllowNull()] - [String[]] [AllowEmptyCollection()] + [System.String[]] $RegistryKeyValue ) - $multiStringRegistryKeyValue = [String[]] @() + $multiStringRegistryKeyValue = [System.String[]] @() if (($null -ne $RegistryKeyValue) -and ($RegistryKeyValue.Length -gt 0)) { - $multiStringRegistryKeyValue = [String[]]$RegistryKeyValue + $multiStringRegistryKeyValue = [System.String[]] $RegistryKeyValue } return $multiStringRegistryKeyValue @@ -1215,12 +1215,12 @@ function ConvertTo-QWord ( [Parameter()] [AllowNull()] - [String[]] [AllowEmptyCollection()] + [System.String[]] $RegistryKeyValue, [Parameter()] - [Boolean] + [System.Boolean] $Hex = $false ) @@ -1231,7 +1231,7 @@ function ConvertTo-QWord $qwordRegistryKeyValue = [System.Int64] 0 - if (($null -ne $RegistryKeyValue) -and ($RegistryKeyValue.Count -eq 1) -and (-not [String]::IsNullOrEmpty($RegistryKeyValue[0]))) + if (($null -ne $RegistryKeyValue) -and ($RegistryKeyValue.Count -eq 1) -and (-not [System.String]::IsNullOrEmpty($RegistryKeyValue[0]))) { $singleRegistryKeyValue = $RegistryKeyValue[0] @@ -1245,7 +1245,7 @@ function ConvertTo-QWord $currentCultureInfo = [System.Globalization.CultureInfo]::CurrentCulture $referenceValue = $null - if ([System.Int64]::TryParse($singleRegistryKeyValue, 'HexNumber', $currentCultureInfo, [Ref] $referenceValue)) + if ([System.Int64]::TryParse($singleRegistryKeyValue, 'HexNumber', $currentCultureInfo, [ref] $referenceValue)) { $qwordRegistryKeyValue = $referenceValue } @@ -1272,14 +1272,14 @@ function ConvertTo-QWord #> function ConvertTo-String { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter()] [AllowNull()] - [String[]] [AllowEmptyCollection()] + [System.String[]] $RegistryKeyValue ) @@ -1288,11 +1288,11 @@ function ConvertTo-String New-InvalidArgumentException -ArgumentName 'ValueData' -Message ($script:localizedData.ArrayNotAllowedForExpectedType -f 'String or ExpandString') } - $registryKeyValueAsString = [String]::Empty + $registryKeyValueAsString = [System.String]::Empty if (($null -ne $RegistryKeyValue) -and ($RegistryKeyValue.Count -eq 1)) { - $registryKeyValueAsString = [String]$RegistryKeyValue[0] + $registryKeyValueAsString = [System.String] $RegistryKeyValue[0] } return $registryKeyValueAsString @@ -1322,33 +1322,33 @@ function Set-RegistryKeyValue ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $RegistryKeyName, [Parameter(Mandatory = $true)] [ValidateNotNull()] - [String] [AllowEmptyString()] + [System.String] $RegistryKeyValueName, [Parameter(Mandatory = $true)] - [Object] [AllowNull()] + [System.Object] $RegistryKeyValue, [Parameter(Mandatory = $true)] [ValidateSet('String', 'Binary', 'DWord', 'QWord', 'MultiString', 'ExpandString')] - [String] + [System.String] $ValueType ) if ($ValueType -eq 'Binary') { - $RegistryKeyValue = [Byte[]]$RegistryKeyValue + $RegistryKeyValue = [System.Byte[]] $RegistryKeyValue } elseif ($ValueType -eq 'MultiString') { - $RegistryKeyValue = [String[]]$RegistryKeyValue + $RegistryKeyValue = [System.String[]] $RegistryKeyValue } $null = [Microsoft.Win32.Registry]::SetValue($RegistryKeyName, $RegistryKeyValueName, $RegistryKeyValue, $ValueType) @@ -1369,23 +1369,23 @@ function Set-RegistryKeyValue #> function Test-RegistryKeyValuesMatch { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [Object] [AllowNull()] + [System.Object] $ExpectedRegistryKeyValue, [Parameter(Mandatory = $true)] - [Object] [AllowNull()] + [System.Object] $ActualRegistryKeyValue, [Parameter(Mandatory = $true)] [ValidateSet('String', 'Binary', 'DWord', 'QWord', 'MultiString', 'ExpandString')] - [String] + [System.String] $RegistryKeyValueType ) @@ -1427,9 +1427,9 @@ function Test-RegistryKeyValuesMatch .SYNOPSIS Removes the default value of the specified registry key. This is a wrapper function for unit testing. - + .PARAMETER RegistryKey - The registry key to remove the default value of. + The registry key to remove the default value of. #> function Remove-DefaultRegistryKeyValue { @@ -1454,7 +1454,7 @@ function Remove-DefaultRegistryKeyValue #> function Get-RegistryKeySubKeyCount { - [OutputType([Int])] + [OutputType([System.Int32])] [CmdletBinding()] param ( diff --git a/DscResources/MSFT_ScriptResource/MSFT_ScriptResource.psm1 b/DscResources/MSFT_ScriptResource/MSFT_ScriptResource.psm1 index f18a809..0137f91 100644 --- a/DscResources/MSFT_ScriptResource/MSFT_ScriptResource.psm1 +++ b/DscResources/MSFT_ScriptResource/MSFT_ScriptResource.psm1 @@ -26,25 +26,25 @@ $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_ScriptResource' .PARAMETER Credential The Credential to run the get script under if needed. #> -function Get-TargetResource +function Get-TargetResource { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] - param + param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GetScript, - + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $SetScript, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $TestScript, [Parameter()] @@ -55,9 +55,9 @@ function Get-TargetResource ) Write-Verbose -Message $script:localizedData.GetTargetResourceStartVerboseMessage - + $invokeScriptParameters = @{ - ScriptBlock = [ScriptBlock]::Create($GetScript) + ScriptBlock = [System.Management.Automation.ScriptBlock]::Create($GetScript) } if ($PSBoundParameters.ContainsKey('Credential')) @@ -72,7 +72,7 @@ function Get-TargetResource New-InvalidOperationException -Message $script:localizedData.GetScriptThrewError -ErrorRecord $invokeScriptResult } - $invokeScriptResultAsHashTable = $invokeScriptResult -as [Hashtable] + $invokeScriptResultAsHashTable = $invokeScriptResult -as [System.Collections.Hashtable] if ($null -eq $invokeScriptResultAsHashTable) { @@ -101,24 +101,24 @@ function Get-TargetResource .PARAMETER Credential The Credential to run the set script under if needed. #> -function Set-TargetResource +function Set-TargetResource { [CmdletBinding()] - param - ( + param + ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GetScript, - + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $SetScript, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $TestScript, [Parameter()] @@ -131,7 +131,7 @@ function Set-TargetResource Write-Verbose -Message $script:localizedData.SetTargetResourceStartVerboseMessage $invokeScriptParameters = @{ - ScriptBlock = [ScriptBlock]::Create($SetScript) + ScriptBlock = [System.Management.Automation.ScriptBlock]::Create($SetScript) } if ($PSBoundParameters.ContainsKey('Credential')) @@ -166,25 +166,25 @@ function Set-TargetResource .PARAMETER Credential The Credential to run the test script under if needed. #> -function Test-TargetResource +function Test-TargetResource { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] - param - ( + param + ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GetScript, - + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $SetScript, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $TestScript, [Parameter()] @@ -197,7 +197,7 @@ function Test-TargetResource Write-Verbose -Message $script:localizedData.TestTargetResourceStartVerboseMessage $invokeScriptParameters = @{ - ScriptBlock = [ScriptBlock]::Create($TestScript) + ScriptBlock = [System.Management.Automation.ScriptBlock]::Create($TestScript) } if ($PSBoundParameters.ContainsKey('Credential')) @@ -208,7 +208,7 @@ function Test-TargetResource $invokeScriptResult = Invoke-Script @invokeScriptParameters # If the script is returing multiple objects, then we consider the last object to be the result of the script execution. - if ($invokeScriptResult -is [Object[]] -and $invokeScriptResult.Count -gt 0) + if ($invokeScriptResult -is [System.Object[]] -and $invokeScriptResult.Count -gt 0) { $invokeScriptResult = $invokeScriptResult[$invokeScriptResult.Count - 1] } @@ -218,7 +218,7 @@ function Test-TargetResource New-InvalidOperationException -Message $script:localizedData.TestScriptThrewError -ErrorRecord $invokeScriptResult } - if ($null -eq $invokeScriptResult -or -not ($invokeScriptResult -is [Boolean])) + if ($null -eq $invokeScriptResult -or -not ($invokeScriptResult -is [System.Boolean])) { New-InvalidArgumentException -ArgumentName 'TestScript' -Message $script:localizedData.TestScriptDidNotReturnBoolean } @@ -243,14 +243,14 @@ function Test-TargetResource #> function Invoke-Script { - [OutputType([Object])] + [OutputType([System.Object])] [CmdletBinding()] - param + param ( [Parameter(Mandatory = $true)] - [ScriptBlock] + [System.Management.Automation.ScriptBlock] $ScriptBlock, - + [Parameter()] [ValidateNotNull()] [System.Management.Automation.PSCredential] diff --git a/DscResources/MSFT_ScriptResource/en-US/MSFT_ScriptResource.strings.psd1 b/DscResources/MSFT_ScriptResource/en-US/MSFT_ScriptResource.strings.psd1 index 8a25d8d..241d133 100644 --- a/DscResources/MSFT_ScriptResource/en-US/MSFT_ScriptResource.strings.psd1 +++ b/DscResources/MSFT_ScriptResource/en-US/MSFT_ScriptResource.strings.psd1 @@ -1,4 +1,4 @@ -# Localized MSFT_ScriptResource.strings.psd1 +# Localized MSFT_ScriptResource.strings.psd1 ConvertFrom-StringData @' GetTargetResourceStartVerboseMessage = Begin executing get script. diff --git a/DscResources/MSFT_ServiceResource/MSFT_ServiceResource.psm1 b/DscResources/MSFT_ServiceResource/MSFT_ServiceResource.psm1 index 8cea484..aba524b 100644 --- a/DscResources/MSFT_ServiceResource/MSFT_ServiceResource.psm1 +++ b/DscResources/MSFT_ServiceResource/MSFT_ServiceResource.psm1 @@ -27,13 +27,13 @@ $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_ServiceResource' #> function Get-TargetResource { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name ) @@ -60,7 +60,7 @@ function Get-TargetResource 'NT Authority\LocalService' { 'LocalService'; break } default { $serviceCimInstance.StartName } } - + $serviceResource = @{ Name = $Name Ensure = 'Present' @@ -71,7 +71,7 @@ function Get-TargetResource DisplayName = $service.DisplayName Description = $serviceCimInstance.Description DesktopInteract = $serviceCimInstance.DesktopInteract - Dependencies = $dependencies + Dependencies = $dependencies } } else @@ -99,7 +99,7 @@ function Get-TargetResource .PARAMETER Ensure Specifies whether the service should exist or not. - + Set this property to Present to create or modify a service. Set this property to Absent to delete a service. @@ -168,7 +168,7 @@ function Get-TargetResource Here are the paths through which Set-TargetResource calls Invoke-CimMethod: Set-TargetResource --> Set-ServicePath --> Invoke-CimMethod - --> Set-ServiceProperty --> Set-ServiceDependencies --> Invoke-CimMethod + --> Set-ServiceProperty --> Set-ServiceDependency --> Invoke-CimMethod --> Set-ServiceAccountProperty --> Invoke-CimMethod --> Set-ServiceStartupType --> Invoke-CimMethod #> @@ -179,59 +179,59 @@ function Set-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter()] [ValidateSet('Automatic', 'Manual', 'Disabled')] - [String] + [System.String] $StartupType, [Parameter()] [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')] - [String] + [System.String] $BuiltInAccount, [Parameter()] [ValidateSet('Running', 'Stopped', 'Ignore')] - [String] + [System.String] $State = 'Running', [Parameter()] - [Boolean] + [System.Boolean] $DesktopInteract = $false, [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $DisplayName, [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] [AllowEmptyCollection()] $Dependencies, [Parameter()] - [UInt32] + [System.UInt32] $StartupTimeout = 30000, [Parameter()] - [UInt32] + [System.UInt32] $TerminateTimeout = 30000, [Parameter()] @@ -306,7 +306,7 @@ function Set-TargetResource $setServicePropertyParameters[$servicePropertyParameterName] = $PSBoundParameters[$servicePropertyParameterName] } } - + if ($setServicePropertyParameters.Count -gt 0) { Write-Verbose -Message ($script:localizedData.EditingServiceProperties -f $Name) @@ -337,14 +337,14 @@ function Set-TargetResource .PARAMETER Name The name of the service to test. - + This may be different from the service's display name. To retrieve a list of all services with their names and current states, use the Get-Service cmdlet. .PARAMETER Ensure Specifies whether the service should exist or not. - + Set this property to Present to test if a service exists. Set this property to Absent to test if a service does not exist. @@ -396,65 +396,65 @@ function Set-TargetResource #> function Test-TargetResource { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, - + [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter()] [ValidateSet('Automatic', 'Manual', 'Disabled')] - [String] + [System.String] $StartupType, [Parameter()] [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')] - [String] + [System.String] $BuiltInAccount, [Parameter()] - [Boolean] + [System.Boolean] $DesktopInteract = $false, [Parameter()] [ValidateSet('Running', 'Stopped', 'Ignore')] - [String] + [System.String] $State = 'Running', [Parameter()] [ValidateNotNull()] - [String] + [System.String] $DisplayName, [Parameter()] - [String] + [System.String] [AllowEmptyString()] $Description, [Parameter()] - [String[]] + [System.String[]] [AllowEmptyCollection()] $Dependencies, [Parameter()] - [UInt32] + [System.UInt32] $StartupTimeout = 30000, [Parameter()] - [UInt32] + [System.UInt32] $TerminateTimeout = 30000, [Parameter()] @@ -541,7 +541,7 @@ function Test-TargetResource return $false } } - + # Check the service desktop interation setting if ($PSBoundParameters.ContainsKey('DesktopInteract') -and $serviceResource.DesktopInteract -ine $DesktopInteract) { @@ -593,7 +593,7 @@ function Test-TargetResource #> function Get-ServiceCimInstance { - [OutputType([CimInstance])] + [OutputType([Microsoft.Management.Infrastructure.CimInstance])] [CmdletBinding()] param ( @@ -615,13 +615,13 @@ function Get-ServiceCimInstance #> function ConvertTo-StartupTypeString { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateSet('Auto', 'Manual', 'Disabled')] - [String] + [System.String] $StartMode ) @@ -647,24 +647,24 @@ function ConvertTo-StartupTypeString .PARAMETER State The service state to check. #> -function Assert-NoStartupTypeStateConflict +function Assert-NoStartupTypeStateConflict { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter(Mandatory = $true)] [ValidateSet('Automatic', 'Manual', 'Disabled')] - [String] + [System.String] $StartupType, [Parameter(Mandatory = $true)] [ValidateSet('Running', 'Stopped', 'Ignore')] - [String] + [System.String] $State ) @@ -700,22 +700,22 @@ function Assert-NoStartupTypeStateConflict #> function Test-PathsMatch { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ExpectedPath, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ActualPath ) - return (0 -eq [String]::Compare($ExpectedPath, $ActualPath, [System.Globalization.CultureInfo]::CurrentUICulture)) + return (0 -eq [System.String]::Compare($ExpectedPath, $ActualPath, [System.Globalization.CultureInfo]::CurrentUICulture)) } <# @@ -728,13 +728,13 @@ function Test-PathsMatch #> function ConvertTo-StartName { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Username ) @@ -773,18 +773,18 @@ function ConvertTo-StartName #> function Set-ServicePath { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) @@ -814,7 +814,7 @@ function Set-ServicePath { $serviceChangePropertyString = $changeServiceArguments.Keys -join ', ' $errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $ServiceName, $serviceChangePropertyString, $changeServiceResult.ReturnValue - New-InvalidArgumentException -ArgumentName 'Path' -Message $errorMessage + New-InvalidArgumentException -ArgumentName 'Path' -Message $errorMessage } return $true @@ -835,18 +835,18 @@ function Set-ServicePath SupportsShouldProcess is enabled because Invoke-CimMethod calls ShouldProcess. This function calls Invoke-CimMethod directly. #> -function Set-ServiceDependencies +function Set-ServiceDependency { [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter(Mandatory = $true)] - [String[]] + [System.String[]] [AllowEmptyCollection()] $Dependencies ) @@ -910,7 +910,7 @@ function Grant-LogOnAsServiceRight ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Username ) @@ -940,7 +940,7 @@ function Grant-LogOnAsServiceRight private const int UNLEN = 256; private const int DNLEN = 15; - // Extra characteres for "\","@" etc. + // Extra characteres for '\', '@' etc. private const int EXTRA_LENGTH = 3; #endregion constants @@ -1335,11 +1335,11 @@ function Set-ServiceAccountProperty ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter()] - [String] + [System.String] [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')] $BuiltInAccount, @@ -1349,7 +1349,7 @@ function Set-ServiceAccountProperty $Credential, [Parameter()] - [Boolean] + [System.Boolean] $DesktopInteract ) @@ -1422,12 +1422,12 @@ function Set-ServiceStartupType ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter(Mandatory = $true)] [ValidateSet('Automatic', 'Manual', 'Disabled')] - [String] + [System.String] $StartupType ) @@ -1498,7 +1498,7 @@ function Set-ServiceStartupType SupportsShouldProcess is enabled because Invoke-CimMethod calls ShouldProcess. Here are the paths through which Set-ServiceProperty calls Invoke-CimMethod: - Set-ServiceProperty --> Set-ServiceDependencies --> Invoke-CimMethod + Set-ServiceProperty --> Set-ServiceDependency --> Invoke-CimMethod --> Set-ServieceAccountProperty --> Invoke-CimMethod --> Set-ServiceStartupType --> Invoke-CimMethod #> @@ -1509,35 +1509,35 @@ function Set-ServiceProperty ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter()] [ValidateSet('Automatic', 'Manual', 'Disabled')] - [String] + [System.String] $StartupType, [Parameter()] [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')] - [String] + [System.String] $BuiltInAccount, [Parameter()] - [Boolean] + [System.Boolean] $DesktopInteract, [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $DisplayName, [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] [AllowEmptyCollection()] $Dependencies, @@ -1550,7 +1550,7 @@ function Set-ServiceProperty # Update display name and/or description if needed $serviceCimInstance = Get-ServiceCimInstance -ServiceName $ServiceName - + $setServiceParameters = @{} if ($PSBoundParameters.ContainsKey('DisplayName') -and $serviceCimInstance.DisplayName -ine $DisplayName) @@ -1571,7 +1571,7 @@ function Set-ServiceProperty # Update service dependencies if needed if ($PSBoundParameters.ContainsKey('Dependencies')) { - Set-ServiceDependencies -ServiceName $ServiceName -Dependencies $Dependencies + Set-ServiceDependency -ServiceName $ServiceName -Dependencies $Dependencies } # Update service account properties if needed @@ -1619,7 +1619,7 @@ function Remove-Service ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name ) @@ -1643,20 +1643,20 @@ function Remove-ServiceWithTimeout ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] - [UInt32] + [System.UInt32] $TerminateTimeout ) Remove-Service -Name $Name $serviceDeleted = $false - $start = [DateTime]::Now + $start = [System.DateTime]::Now - while (-not $serviceDeleted -and ([DateTime]::Now - $start).TotalMilliseconds -lt $TerminateTimeout) + while (-not $serviceDeleted -and ([System.DateTime]::Now - $start).TotalMilliseconds -lt $TerminateTimeout) { $service = Get-Service -Name $Name -ErrorAction 'SilentlyContinue' @@ -1685,7 +1685,7 @@ function Remove-ServiceWithTimeout .SYNOPSIS Waits for the service with the given name to reach the given state within the given time span. - + This is a wrapper function for unit testing. .PARAMETER ServiceName @@ -1704,7 +1704,7 @@ function Wait-ServiceStateWithTimeout ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter(Mandatory = $true)] @@ -1712,7 +1712,7 @@ function Wait-ServiceStateWithTimeout $State, [Parameter(Mandatory = $true)] - [TimeSpan] + [System.TimeSpan] $WaitTimeSpan ) @@ -1738,11 +1738,11 @@ function Start-ServiceWithTimeout ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter(Mandatory = $true)] - [UInt32] + [System.UInt32] $StartupTimeout ) @@ -1769,11 +1769,11 @@ function Stop-ServiceWithTimeout ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter(Mandatory = $true)] - [UInt32] + [System.UInt32] $TerminateTimeout ) diff --git a/DscResources/MSFT_UserResource/MSFT_UserResource.psm1 b/DscResources/MSFT_UserResource/MSFT_UserResource.psm1 index 968f1d8..7b7571f 100644 --- a/DscResources/MSFT_UserResource/MSFT_UserResource.psm1 +++ b/DscResources/MSFT_UserResource/MSFT_UserResource.psm1 @@ -34,13 +34,13 @@ else #> function Get-TargetResource { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName ) @@ -57,7 +57,7 @@ function Get-TargetResource <# .SYNOPSIS Creates, modifies, or deletes a user. - + .PARAMETER UserName The name of the user to create, modify, or delete. @@ -91,30 +91,32 @@ function Get-TargetResource Specifies whether the user is allowed to change their password or not. By default this is set to $false - .NOTES + .NOTES If Ensure is set to 'Present' then the password parameter is required. #> function Set-TargetResource { - [CmdletBinding()] + # Should process is called in a helper functions but not directly in Set-TargetResource + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')] + [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $FullName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] @@ -124,19 +126,19 @@ function Set-TargetResource $Password, [Parameter()] - [Boolean] + [System.Boolean] $Disabled, [Parameter()] - [Boolean] + [System.Boolean] $PasswordNeverExpires, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeRequired, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeNotAllowed ) @@ -186,26 +188,26 @@ function Set-TargetResource #> function Test-TargetResource { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $FullName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] @@ -215,19 +217,19 @@ function Test-TargetResource $Password, [Parameter()] - [Boolean] + [System.Boolean] $Disabled, [Parameter()] - [Boolean] + [System.Boolean] $PasswordNeverExpires, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeRequired, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeNotAllowed ) @@ -251,13 +253,13 @@ function Test-TargetResource #> function Get-TargetResourceOnFullSKU { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName ) @@ -312,7 +314,7 @@ function Get-TargetResourceOnFullSKU <# .SYNOPSIS Creates, modifies, or deletes a user when on a full server. - + .PARAMETER UserName The name of the user to create, modify, or delete. @@ -346,30 +348,30 @@ function Get-TargetResourceOnFullSKU Specifies whether the user is allowed to change their password or not. By default this is set to $false - .NOTES + .NOTES If Ensure is set to 'Present' then the Password parameter is required. #> function Set-TargetResourceOnFullSKU { - [CmdletBinding()] + [CmdletBinding(SupportsShouldProcess = $true)] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $FullName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] @@ -379,19 +381,19 @@ function Set-TargetResourceOnFullSKU $Password, [Parameter()] - [Boolean] + [System.Boolean] $Disabled, [Parameter()] - [Boolean] + [System.Boolean] $PasswordNeverExpires, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeRequired, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeNotAllowed ) @@ -410,7 +412,7 @@ function Set-TargetResourceOnFullSKU try { $user = Find-UserByNameOnFullSku -UserName $UserName - + } catch { @@ -456,7 +458,7 @@ function Set-TargetResourceOnFullSKU } elseif (-not $userExists) { - <# + <# For a newly created user, set the DisplayName property to an empty string since by default DisplayName is set to user's name. #> @@ -574,26 +576,26 @@ function Set-TargetResourceOnFullSKU #> function Test-TargetResourceOnFullSKU { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $FullName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] @@ -603,19 +605,19 @@ function Test-TargetResourceOnFullSKU $Password, [Parameter()] - [Boolean] + [System.Boolean] $Disabled, [Parameter()] - [Boolean] + [System.Boolean] $PasswordNeverExpires, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeRequired, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeNotAllowed ) @@ -731,13 +733,13 @@ function Test-TargetResourceOnFullSKU #> function Get-TargetResourceOnNanoServer { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName ) @@ -793,7 +795,7 @@ function Get-TargetResourceOnNanoServer <# .SYNOPSIS Creates, modifies, or deletes a user when on Nano Server. - + .PARAMETER UserName The name of the user to create, modify, or delete. @@ -827,7 +829,7 @@ function Get-TargetResourceOnNanoServer Specifies whether the user is allowed to change their password or not. By default this is set to $false - .NOTES + .NOTES If Ensure is set to 'Present' then the Password parameter is required. #> function Set-TargetResourceOnNanoServer @@ -836,20 +838,20 @@ function Set-TargetResourceOnNanoServer ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $FullName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] @@ -859,19 +861,19 @@ function Set-TargetResourceOnNanoServer $Password, [Parameter()] - [Boolean] + [System.Boolean] $Disabled, [Parameter()] - [Boolean] + [System.Boolean] $PasswordNeverExpires, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeRequired, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeNotAllowed ) @@ -883,7 +885,7 @@ function Set-TargetResourceOnNanoServer # Try to find a user by a name. $userExists = $false - + try { $user = Find-UserByNameOnNanoServer -UserName $UserName @@ -965,12 +967,12 @@ function Set-TargetResourceOnNanoServer # NOTE: The parameter name and the property name have opposite meaning. $expected = (-not $PasswordChangeNotAllowed) $actual = $expected - + if ($userExists) { $actual = $user.UserMayChangePassword } - + if ($PSBoundParameters.ContainsKey('PasswordChangeNotAllowed') -and ((-not $userExists) -or ($expected -ne $actual))) { Set-LocalUser -Name $UserName -UserMayChangePassword $expected @@ -1031,26 +1033,26 @@ function Set-TargetResourceOnNanoServer #> function Test-TargetResourceOnNanoServer { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $FullName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] @@ -1060,19 +1062,19 @@ function Test-TargetResourceOnNanoServer $Password, [Parameter()] - [Boolean] + [System.Boolean] $Disabled, [Parameter()] - [Boolean] + [System.Boolean] $PasswordNeverExpires, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeRequired, [Parameter()] - [Boolean] + [System.Boolean] $PasswordChangeNotAllowed ) @@ -1172,35 +1174,35 @@ function Assert-UserNameValid ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName ) # Check if the name consists of only periods and/or white spaces $wrongName = $true - + for ($i = 0; $i -lt $UserName.Length; $i++) { - if (-not [Char]::IsWhiteSpace($UserName, $i) -and $UserName[$i] -ne '.') + if (-not [System.Char]::IsWhiteSpace($UserName, $i) -and $UserName[$i] -ne '.') { $wrongName = $false break } } - $invalidChars = @('\','/','"','[',']',':','|','<','>','+','=',';',',','?','*','@') + $invalidChars = @('\', '/', '"', '[', ']', ':', '|', '<', '>', '+', '=', ';', ',', '?', '*', '@') if ($wrongName) { New-InvalidArgumentException ` - -Message ($script:localizedData.InvalidUserName -f $UserName, [String]::Join(' ', $invalidChars)) ` + -Message ($script:localizedData.InvalidUserName -f $UserName, [System.String]::Join(' ', $invalidChars)) ` -ArgumentName 'UserName' } if ($UserName.IndexOfAny($invalidChars) -ne -1) { New-InvalidArgumentException ` - -Message ($script:localizedData.InvalidUserName -f $UserName, [String]::Join(' ', $invalidChars)) ` + -Message ($script:localizedData.InvalidUserName -f $UserName, [System.String]::Join(' ', $invalidChars)) ` -ArgumentName 'UserName' } } @@ -1208,7 +1210,7 @@ function Assert-UserNameValid <# .SYNOPSIS Tests the local user's credentials on the local machine. - + .PARAMETER UserName The username to validate the credentials of. @@ -1217,18 +1219,18 @@ function Assert-UserNameValid #> function Test-CredentialsValidOnNanoServer { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $UserName, [Parameter()] [ValidateNotNullOrEmpty()] - [SecureString] + [System.Security.SecureString] $Password ) @@ -1314,7 +1316,7 @@ function Test-CredentialsValidOnNanoServer .SYNOPSIS Queries a user by the given username. If found the function returns a UserPrincipal object. Otherwise, the function returns $null. - + .PARAMETER UserName The username to search for. #> @@ -1342,7 +1344,7 @@ function Find-UserByNameOnFullSku <# .SYNOPSIS Adds a user with the given username and returns the new user object - + .PARAMETER UserName The username for the new user #> @@ -1383,7 +1385,7 @@ function Add-UserOnFullSku <# .SYNOPSIS Sets the password for the given user - + .PARAMETER User The user to set the password for @@ -1415,7 +1417,7 @@ function Set-UserPasswordOnFullSku .SYNOPSIS Validates the password is correct for the given user. Returns $true if the Password is correct for the given username, false otherwise. - + .PARAMETER UserName The UserName to check @@ -1459,7 +1461,7 @@ function Test-UserPasswordOnFullSku .SYNOPSIS Queries a user by the given username. If found the function returns a UserPrincipal object. Otherwise, the function returns $null. - + .PARAMETER UserName The username to search for. #> @@ -1498,7 +1500,7 @@ function Remove-UserOnFullSku <# .SYNOPSIS Saves changes for the given user on a machine. - + .PARAMETER User The user to save the changes of #> @@ -1519,7 +1521,7 @@ function Save-UserOnFullSku <# .SYNOPSIS Expires the password of the given user. - + .PARAMETER User The user to expire the password of. #> @@ -1541,7 +1543,7 @@ function Revoke-UserPassword .SYNOPSIS Queries a user by the given username. If found the function returns a LocalUser object. Otherwise, the function throws an error that the user was not found. - + .PARAMETER UserName The username to search for. #> diff --git a/DscResources/MSFT_UserResource/en-US/MSFT_UserResource.strings.psd1 b/DscResources/MSFT_UserResource/en-US/MSFT_UserResource.strings.psd1 index 8381ba4..89860ac 100644 --- a/DscResources/MSFT_UserResource/en-US/MSFT_UserResource.strings.psd1 +++ b/DscResources/MSFT_UserResource/en-US/MSFT_UserResource.strings.psd1 @@ -1,4 +1,4 @@ -# Localized resources for User +# Localized resources for User ConvertFrom-StringData @' UserWithName = User: {0} diff --git a/DscResources/MSFT_WindowsFeature/MSFT_WindowsFeature.psm1 b/DscResources/MSFT_WindowsFeature/MSFT_WindowsFeature.psm1 index 27feb18..fa75844 100644 --- a/DscResources/MSFT_WindowsFeature/MSFT_WindowsFeature.psm1 +++ b/DscResources/MSFT_WindowsFeature/MSFT_WindowsFeature.psm1 @@ -26,32 +26,32 @@ $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_WindowsFeature' If the specified role or feature does not contain any subfeatures then IncludeAllSubFeature will be set to $false. If the specified feature contains one or more subfeatures then IncludeAllSubFeature will be set to $true only if all the - subfeatures are installed. Otherwise, IncludeAllSubFeature will be set to $false. + subfeatures are installed. Otherwise, IncludeAllSubFeature will be set to $false. #> function Get-TargetResource { [CmdletBinding()] - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, - + [Parameter()] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential ) - + Write-Verbose -Message ($script:localizedData.GetTargetResourceStartMessage -f $Name) - - Import-ServerManager - + + Import-ServerManager + Write-Verbose -Message ($script:localizedData.QueryFeature -f $Name) - + $isWinServer2008R2SP1 = Test-IsWinServer2008R2SP1 if ($isWinServer2008R2SP1 -and $PSBoundParameters.ContainsKey('Credential')) { @@ -63,11 +63,11 @@ function Get-TargetResource { $feature = Get-WindowsFeature @PSBoundParameters } - - Assert-SingleFeatureExists -Feature $feature -Name $Name - + + Assert-SingleInstanceOfFeature -Feature $feature -Name $Name + $includeAllSubFeature = $true - + if ($feature.SubFeatures.Count -eq 0) { $includeAllSubFeature = $false @@ -82,7 +82,7 @@ function Get-TargetResource if ($PSBoundParameters.ContainsKey('Credential')) { - $getWindowsFeatureParameters['Credential'] = $Credential + $getWindowsFeatureParameters['Credential'] = $Credential } if ($isWinServer2008R2SP1 -and $PSBoundParameters.ContainsKey('Credential')) @@ -100,9 +100,9 @@ function Get-TargetResource { $subFeature = Get-WindowsFeature @getWindowsFeatureParameters } - - Assert-SingleFeatureExists -Feature $subFeature -Name $currentSubFeatureName - + + Assert-SingleInstanceOfFeature -Feature $subFeature -Name $currentSubFeatureName + if (-not $subFeature.Installed) { $includeAllSubFeature = $false @@ -121,7 +121,7 @@ function Get-TargetResource } Write-Verbose -Message ($script:localizedData.GetTargetResourceEndMessage -f $Name) - + # Add all feature properties to the hash table return @{ Name = $Name @@ -134,7 +134,7 @@ function Get-TargetResource <# .SYNOPSIS Installs or uninstalls the role or feature with the given name on the target machine - with the option of installing or uninstalling all subfeatures as well. + with the option of installing or uninstalling all subfeatures as well. .PARAMETER Name The name of the role or feature to install or uninstall. @@ -166,16 +166,16 @@ function Set-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [Boolean] + [System.Boolean] $IncludeAllSubFeature = $false, [Parameter()] @@ -186,7 +186,7 @@ function Set-TargetResource [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath ) @@ -205,7 +205,7 @@ function Set-TargetResource if ($PSBoundParameters.ContainsKey('LogPath')) { - $addWindowsFeatureParameters['LogPath'] = $LogPath + $addWindowsFeatureParameters['LogPath'] = $LogPath } Write-Verbose -Message ($script:localizedData.InstallFeature -f $Name) @@ -225,7 +225,7 @@ function Set-TargetResource { if ($PSBoundParameters.ContainsKey('Credential')) { - $addWindowsFeatureParameters['Credential'] = $Credential + $addWindowsFeatureParameters['Credential'] = $Credential } $feature = Add-WindowsFeature @addWindowsFeatureParameters @@ -256,7 +256,7 @@ function Set-TargetResource if ($PSBoundParameters.ContainsKey('LogPath')) { - $removeWindowsFeatureParameters['LogPath'] = $LogPath + $removeWindowsFeatureParameters['LogPath'] = $LogPath } Write-Verbose -Message ($script:localizedData.UninstallFeature -f $Name) @@ -276,7 +276,7 @@ function Set-TargetResource { if ($PSBoundParameters.ContainsKey('Credential')) { - $addWindowsFeatureParameters['Credential'] = $Credential + $addWindowsFeatureParameters['Credential'] = $Credential } $feature = Remove-WindowsFeature @removeWindowsFeatureParameters @@ -304,7 +304,7 @@ function Set-TargetResource <# .SYNOPSIS - Tests if the role or feature with the given name is in the desired state. + Tests if the role or feature with the given name is in the desired state. .PARAMETER Name The name of the role or feature to test the state of. @@ -315,11 +315,11 @@ function Set-TargetResource By default this is set to Present. .PARAMETER IncludeAllSubFeature - Specifies whether or not the installation state of all subfeatures should be tested with + Specifies whether or not the installation state of all subfeatures should be tested with the specified role or feature. Default is false. - -If this property is set to true and Ensure is set to Present, + -If this property is set to true and Ensure is set to Present, each subfeature will be tested to ensure it is installed. - -If this property is set to true and Ensure is set to Absent, + -If this property is set to true and Ensure is set to Absent, each subfeature will be tested to ensure it is uninstalled. -If this property is false, subfeatures will not be tested. @@ -340,16 +340,16 @@ function Test-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [Boolean] + [System.Boolean] $IncludeAllSubFeature = $false, [Parameter()] @@ -360,15 +360,15 @@ function Test-TargetResource [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath ) Write-Verbose -Message ($script:localizedData.TestTargetResourceStartMessage -f $Name) - + Import-ServerManager - + $testTargetResourceResult = $false $getWindowsFeatureParameters = @{ @@ -377,11 +377,11 @@ function Test-TargetResource if ($PSBoundParameters.ContainsKey('Credential')) { - $getWindowsFeatureParameters['Credential'] = $Credential + $getWindowsFeatureParameters['Credential'] = $Credential } - + Write-Verbose -Message ($script:localizedData.QueryFeature -f $Name) - + $isWinServer2008R2SP1 = Test-IsWinServer2008R2SP1 if ($isWinServer2008R2SP1 -and $PSBoundParameters.ContainsKey('Credential')) { @@ -398,22 +398,22 @@ function Test-TargetResource { $feature = Get-WindowsFeature @getWindowsFeatureParameters } - - Assert-SingleFeatureExists -Feature $feature -Name $Name - + + Assert-SingleInstanceOfFeature -Feature $feature -Name $Name + # Check if the feature is in the requested Ensure state. if (($Ensure -eq 'Present' -and $feature.Installed -eq $true) -or ` ($Ensure -eq 'Absent' -and $feature.Installed -eq $false)) { $testTargetResourceResult = $true - + if ($IncludeAllSubFeature) { # Check if each subfeature is in the requested state. foreach ($currentSubFeatureName in $feature.SubFeatures) { $getWindowsFeatureParameters['Name'] = $currentSubFeatureName - + if ($isWinServer2008R2SP1 -and $PSBoundParameters.ContainsKey('Credential')) { <# @@ -429,15 +429,15 @@ function Test-TargetResource { $subFeature = Get-WindowsFeature @getWindowsFeatureParameters } - - Assert-SingleFeatureExists -Feature $subFeature -Name $currentSubFeatureName - + + Assert-SingleInstanceOfFeature -Feature $subFeature -Name $currentSubFeatureName + if (-not $subFeature.Installed -and $Ensure -eq 'Present') { $testTargetResourceResult = $false break } - + if ($subFeature.Installed -and $Ensure -eq 'Absent') { $testTargetResourceResult = $false @@ -451,9 +451,9 @@ function Test-TargetResource # Ensure is not in the correct state $testTargetResourceResult = $false } - + Write-Verbose -Message ($script:localizedData.TestTargetResourceEndMessage -f $Name) - + return $testTargetResourceResult } @@ -467,19 +467,19 @@ function Test-TargetResource .PARAMETER Name The name of the role or feature to include in any error messages that are thrown. - (Not used to assert validity of the feature). + (Not used to assert validity of the feature). #> -function Assert-SingleFeatureExists +function Assert-SingleInstanceOfFeature { [CmdletBinding()] param ( [Parameter()] - [PSObject] + [System.Management.Automation.PSObject] $Feature, [Parameter()] - [String] + [System.String] $Name ) @@ -501,7 +501,7 @@ function Assert-SingleFeatureExists #> function Import-ServerManager { - param + param () <# @@ -552,7 +552,7 @@ function Import-ServerManager <# .SYNOPSIS Tests if the machine is a Windows Server 2008 R2 SP1 machine. - + .NOTES Since Assert-PrequisitesValid ensures that ServerManager is available on the machine, this function only checks the OS version. diff --git a/DscResources/MSFT_WindowsFeature/en-US/MSFT_WindowsFeature.strings.psd1 b/DscResources/MSFT_WindowsFeature/en-US/MSFT_WindowsFeature.strings.psd1 index f36ee5a..3a78e88 100644 --- a/DscResources/MSFT_WindowsFeature/en-US/MSFT_WindowsFeature.strings.psd1 +++ b/DscResources/MSFT_WindowsFeature/en-US/MSFT_WindowsFeature.strings.psd1 @@ -1,4 +1,4 @@ -# Localized strings for MSFT_WindowsFeature.psd1 +# Localized strings for MSFT_WindowsFeature.psd1 ConvertFrom-StringData @' FeatureNotFoundError = The requested feature {0} could not be found on the target machine. diff --git a/DscResources/MSFT_WindowsOptionalFeature/MSFT_WindowsOptionalFeature.psm1 b/DscResources/MSFT_WindowsOptionalFeature/MSFT_WindowsOptionalFeature.psm1 index 816c31d..d9d7d70 100644 --- a/DscResources/MSFT_WindowsOptionalFeature/MSFT_WindowsOptionalFeature.psm1 +++ b/DscResources/MSFT_WindowsOptionalFeature/MSFT_WindowsOptionalFeature.psm1 @@ -19,11 +19,11 @@ $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_WindowsOptionalFea function Get-TargetResource { [CmdletBinding()] - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Name ) @@ -32,11 +32,11 @@ function Get-TargetResource Assert-ResourcePrerequisitesValid $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -FeatureName $Name -Online - + <# $windowsOptionalFeatureProperties and this section of code are needed because an error will be thrown if a property is not found in WMF 4 instead of returning null. - #> + #> $windowsOptionalFeatureProperties = @{} $propertiesNeeded = @( 'LogPath', 'State', 'CustomProperties', 'FeatureName', 'LogLevel', 'Description', 'DisplayName' ) @@ -55,8 +55,8 @@ function Get-TargetResource $windowsOptionalFeatureResource = @{ LogPath = $windowsOptionalFeatureProperties.LogPath Ensure = Convert-FeatureStateToEnsure -State $windowsOptionalFeatureProperties.State - CustomProperties = - Convert-CustomPropertyArrayToStringArray -CustomProperties $windowsOptionalFeatureProperties.CustomProperties + CustomProperties = Convert-CustomPropertyArrayToStringArray ` + -CustomProperties $windowsOptionalFeatureProperties.CustomProperties Name = $windowsOptionalFeatureProperties.FeatureName LogLevel = $windowsOptionalFeatureProperties.LogLevel Description = $windowsOptionalFeatureProperties.Description @@ -85,7 +85,7 @@ function Get-TargetResource being disabled. .PARAMETER NoWindowsUpdateCheck - Specifies whether or not DISM contacts Windows Update (WU) when searching for the source + Specifies whether or not DISM contacts Windows Update (WU) when searching for the source files to enable the feature. If $true, DISM will not contact WU. @@ -106,29 +106,29 @@ function Set-TargetResource param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Name, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [Boolean] + [System.Boolean] $RemoveFilesOnDisable, [Parameter()] - [Boolean] + [System.Boolean] $NoWindowsUpdateCheck, [Parameter()] - [String] + [System.String] $LogPath, [Parameter()] [ValidateSet('ErrorsOnly', 'ErrorsAndWarning', 'ErrorsAndWarningAndInformation')] - [String] + [System.String] $LogLevel = 'ErrorsAndWarningAndInformation' ) @@ -138,9 +138,23 @@ function Set-TargetResource $dismLogLevel = switch ($LogLevel) { - 'ErrorsOnly' { 'Errors'; break } - 'ErrorsAndWarning' { 'Warnings'; break } - 'ErrorsAndWarningAndInformation' { 'WarningsInfo'; break } + 'ErrorsOnly' + { + 'Errors' + break + } + + 'ErrorsAndWarning' + { + 'Warnings' + break + } + + 'ErrorsAndWarningAndInformation' + { + 'WarningsInfo' + break + } } # Construct splatting hashtable for DISM cmdlets @@ -188,7 +202,7 @@ function Set-TargetResource <# $restartNeeded and this section of code are needed because an error will be thrown if the RestartNeeded property is not found in WMF 4. - #> + #> try { $restartNeeded = $windowsOptionalFeature.RestartNeeded @@ -235,33 +249,33 @@ function Set-TargetResource function Test-TargetResource { [CmdletBinding()] - [OutputType([Boolean])] + [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Name, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [Boolean] + [System.Boolean] $RemoveFilesOnDisable, [Parameter()] - [Boolean] + [System.Boolean] $NoWindowsUpdateCheck, [Parameter()] - [String] + [System.String] $LogPath, [Parameter()] [ValidateSet('ErrorsOnly', 'ErrorsAndWarning', 'ErrorsAndWarningAndInformation')] - [String] + [System.String] $LogLevel = 'ErrorsAndWarningAndInformation' ) @@ -270,7 +284,7 @@ function Test-TargetResource Assert-ResourcePrerequisitesValid $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -FeatureName $Name -Online - + $featureIsInDesiredState = $false if ($null -eq $windowsOptionalFeature -or $windowsOptionalFeature.State -eq 'Disabled') @@ -281,9 +295,9 @@ function Test-TargetResource { $featureIsInDesiredState = $Ensure -eq 'Present' } - + Write-Verbose -Message ($script:localizedData.TestTargetResourceEndMessage -f $Name) - + return $featureIsInDesiredState } @@ -298,15 +312,15 @@ function Test-TargetResource function Convert-CustomPropertyArrayToStringArray { [CmdletBinding()] - [OutputType([String[]])] + [OutputType([System.String[]])] param ( [Parameter()] - [PSCustomObject[]] + [System.Management.Automation.PSObject[]] $CustomProperties ) - $propertiesAsStrings = [String[]] @() + $propertiesAsStrings = [System.String[]] @() foreach ($customProperty in $CustomProperties) { @@ -330,11 +344,11 @@ function Convert-CustomPropertyArrayToStringArray function Convert-FeatureStateToEnsure { [CmdletBinding()] - [OutputType([String])] + [OutputType([System.String])] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $State ) @@ -381,15 +395,16 @@ function Assert-ResourcePrerequisitesValid # Check that we are running as an administrator $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent() $windowsPrincipal = New-Object -TypeName 'System.Security.Principal.WindowsPrincipal' -ArgumentList @( $windowsIdentity ) - + $adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator + if (-not $windowsPrincipal.IsInRole($adminRole)) { New-InvalidOperationException -Message $script:localizedData.ElevationRequired } # Check that Dism PowerShell module is available - Import-Module -Name 'Dism' -ErrorVariable 'errorsFromDismImport' -ErrorAction 'SilentlyContinue' -Force + Import-Module -Name 'Dism' -ErrorVariable 'errorsFromDismImport' -ErrorAction 'SilentlyContinue' -Force -Verbose:$false if ($errorsFromDismImport.Count -gt 0) { diff --git a/DscResources/MSFT_WindowsPackageCab/MSFT_WindowsPackageCab.psm1 b/DscResources/MSFT_WindowsPackageCab/MSFT_WindowsPackageCab.psm1 index 111e483..fb57255 100644 --- a/DscResources/MSFT_WindowsPackageCab/MSFT_WindowsPackageCab.psm1 +++ b/DscResources/MSFT_WindowsPackageCab/MSFT_WindowsPackageCab.psm1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' Import-Module -Name (Join-Path -Path (Split-Path -Path $PSScriptRoot -Parent) ` @@ -30,27 +30,27 @@ Import-Module -Name 'Dism' function Get-TargetResource { [CmdletBinding()] - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $SourcePath, [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath ) @@ -72,7 +72,7 @@ function Get-TargetResource } Write-Verbose -Message ($script:localizedData.RetrievingPackage -f $Name) - + try { $windowsPackageInfo = Dism\Get-WindowsPackage @getWindowsPackageParams @@ -118,22 +118,22 @@ function Set-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $SourcePath, [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath ) @@ -143,10 +143,10 @@ function Set-TargetResource { New-InvalidArgumentException -ArgumentName 'SourcePath' -Message ($script:localizedData.SourcePathDoesNotExist -f $SourcePath) } - + if ($Ensure -ieq 'Present') { - Write-Verbose -Message ($script:localizedData.AddingPackage -f $SourcePath) + Write-Verbose -Message ($script:localizedData.AddingPackage -f $SourcePath) Dism\Add-WindowsPackage -PackagePath $SourcePath -LogPath $LogPath -Online } else @@ -180,27 +180,27 @@ function Set-TargetResource function Test-TargetResource { [CmdletBinding()] - [OutputType([Boolean])] + [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $SourcePath, [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath ) @@ -226,7 +226,7 @@ function Test-TargetResource { Write-Verbose -Message ($script:localizedData.EnsureStatesDoNotMatch -f $Name) return $false - } + } } Export-ModuleMember -Function '*-TargetResource' diff --git a/DscResources/MSFT_WindowsPackageCab/en-US/MSFT_WindowsPackageCab.schema.mfl b/DscResources/MSFT_WindowsPackageCab/en-US/MSFT_WindowsPackageCab.schema.mfl index ce59b5a..82f7e35 100644 --- a/DscResources/MSFT_WindowsPackageCab/en-US/MSFT_WindowsPackageCab.schema.mfl +++ b/DscResources/MSFT_WindowsPackageCab/en-US/MSFT_WindowsPackageCab.schema.mfl @@ -1,4 +1,4 @@ -[Description("This resource is used to install or uninstall a package from a windows cabinet (cab) file.") : Amended,AMENDMENT, LOCALE("MS_409")] +[Description("This resource is used to install or uninstall a package from a windows cabinet (cab) file.") : Amended,AMENDMENT, LOCALE("MS_409")] class MSFT_WindowsPackageCab : OMI_BaseResource { [Key, Description("The name of the package to install or uninstall.") : Amended] String Name; diff --git a/DscResources/MSFT_WindowsPackageCab/en-US/MSFT_WindowsPackageCab.strings.psd1 b/DscResources/MSFT_WindowsPackageCab/en-US/MSFT_WindowsPackageCab.strings.psd1 index 2d5fe9b..3085420 100644 --- a/DscResources/MSFT_WindowsPackageCab/en-US/MSFT_WindowsPackageCab.strings.psd1 +++ b/DscResources/MSFT_WindowsPackageCab/en-US/MSFT_WindowsPackageCab.strings.psd1 @@ -1,4 +1,4 @@ -# Localized resources for WindowsPackageCab +# Localized resources for WindowsPackageCab ConvertFrom-StringData @' RetrievingPackage = Retrieving information for the package {0} diff --git a/DscResources/MSFT_WindowsProcess/MSFT_WindowsProcess.psm1 b/DscResources/MSFT_WindowsProcess/MSFT_WindowsProcess.psm1 index 1731199..b962dd0 100644 --- a/DscResources/MSFT_WindowsProcess/MSFT_WindowsProcess.psm1 +++ b/DscResources/MSFT_WindowsProcess/MSFT_WindowsProcess.psm1 @@ -32,18 +32,18 @@ $script:localizedData = Get-LocalizedData -ResourceName 'MSFT_WindowsProcess' #> function Get-TargetResource { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [AllowEmptyString()] - [String] + [System.String] $Arguments, [Parameter()] @@ -98,6 +98,7 @@ function Get-TargetResource } Write-Verbose -Message ($script:localizedData.GetTargetResourceEndMessage -f $Path) + return $processToReturn } @@ -152,12 +153,12 @@ function Set-TargetResource ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [AllowEmptyString()] - [String] + [System.String] $Arguments, [Parameter()] @@ -168,23 +169,23 @@ function Set-TargetResource [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $StandardOutputPath, [Parameter()] - [String] + [System.String] $StandardErrorPath, [Parameter()] - [String] + [System.String] $StandardInputPath, [Parameter()] - [String] + [System.String] $WorkingDirectory ) @@ -218,6 +219,7 @@ function Set-TargetResource Assert-HashtableDoesNotContainKey @assertHashtableParams $whatIfShouldProcess = $PSCmdlet.ShouldProcess($Path, $script:localizedData.StoppingProcessWhatif) + if ($processCimInstance.Count -gt 0 -and $whatIfShouldProcess) { # If there are multiple process Ids, all will be included to be stopped @@ -238,6 +240,7 @@ function Set-TargetResource New-InvalidOperationException -Message $errorMessage } + <# Before returning from Set-TargetResource we have to ensure a subsequent Test-TargetResource is going to work @@ -265,7 +268,7 @@ function Set-TargetResource foreach ($shouldBeRootedPathArgument in $shouldBeRootedPathArguments) { - if (-not [String]::IsNullOrEmpty($PSBoundParameters[$shouldBeRootedPathArgument])) + if (-not [System.String]::IsNullOrEmpty($PSBoundParameters[$shouldBeRootedPathArgument])) { $assertPathArgumentRootedParams = @{ PathArgumentName = $shouldBeRootedPathArgument @@ -279,7 +282,7 @@ function Set-TargetResource foreach ($shouldExistPathArgument in $shouldExistPathArguments) { - if (-not [String]::IsNullOrEmpty($PSBoundParameters[$shouldExistPathArgument])) + if (-not [System.String]::IsNullOrEmpty($PSBoundParameters[$shouldExistPathArgument])) { $assertPathArgumentValidParams = @{ PathArgumentName = $shouldExistPathArgument @@ -334,7 +337,7 @@ function Set-TargetResource if (($PSBoundParameters.ContainsKey('Credential')) -and (Test-IsRunFromLocalSystemUser)) { # Throw an exception if any of the below parameters are included with Credential passed - foreach ($key in @('StandardOutputPath','StandardInputPath','WorkingDirectory')) + foreach ($key in @('StandardOutputPath', 'StandardInputPath', 'WorkingDirectory')) { if ($PSBoundParameters.Keys -contains $key) { @@ -345,6 +348,7 @@ function Set-TargetResource New-InvalidArgumentException @newInvalidArgumentExceptionParams } } + try { Start-ProcessAsLocalSystemUser -Path $Path -Arguments $Arguments -Credential $Credential @@ -365,7 +369,7 @@ function Set-TargetResource catch [System.Exception] { $errorMessage = ($script:localizedData.ErrorStarting -f $Path, $_.Exception.Message) - + New-InvalidOperationException -Message $errorMessage } } @@ -429,45 +433,45 @@ function Set-TargetResource #> function Test-TargetResource { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [AllowEmptyString()] - [String] + [System.String] $Arguments, [Parameter()] [ValidateNotNullOrEmpty()] - [PSCredential] + [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [String] + [System.String] $StandardOutputPath, [Parameter()] - [String] + [System.String] $StandardErrorPath, [Parameter()] - [String] + [System.String] $StandardInputPath, [Parameter()] - [String] + [System.String] $WorkingDirectory ) @@ -511,13 +515,13 @@ function Test-TargetResource #> function Expand-Path { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path ) @@ -536,11 +540,12 @@ function Expand-Path # Check to see if the path to the file exists in the current location. If so, return the full rooted path. $rootedPath = [System.IO.Path]::GetFullPath($Path) + if ([System.IO.File]::Exists($rootedPath)) { return $rootedPath } - + # If the path is not found, throw an exception New-InvalidArgumentException -ArgumentName 'Path' -Message ($script:localizedData.FileNotFound -f $Path) } @@ -566,17 +571,17 @@ function Expand-Path #> function Get-ProcessCimInstance { - [OutputType([CimInstance[]])] + [OutputType([Microsoft.Management.Infrastructure.CimInstance[]])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter()] - [String] + [System.String] $Arguments, [Parameter()] @@ -586,8 +591,8 @@ function Get-ProcessCimInstance $Credential, [Parameter()] - [ValidateRange(0, [Int]::MaxValue)] - [Int] + [ValidateRange(0, [System.Int32]::MaxValue)] + [System.Int32] $UseGetCimInstanceThreshold = 8 ) @@ -640,7 +645,7 @@ function Get-ProcessCimInstance if ($null -eq $Arguments) { - $Arguments = [String]::Empty + $Arguments = [System.String]::Empty } $processesWithMatchingArguments = @() @@ -666,17 +671,17 @@ function Get-ProcessCimInstance #> function ConvertTo-EscapedStringForWqlFilter { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $FilterString ) - return $FilterString.Replace("\","\\").Replace('"','\"').Replace("'","\'") + return $FilterString.Replace("\", "\\").Replace('"', '\"').Replace("'", "\'") } <# @@ -692,13 +697,13 @@ function ConvertTo-EscapedStringForWqlFilter #> function Get-ProcessOwner { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Object] + [System.Object] $Process ) @@ -717,7 +722,7 @@ function Get-ProcessOwner } } - return '' + return [System.String]::Empty } <# @@ -733,13 +738,13 @@ function Get-ProcessOwner #> function Get-ProcessOwnerCimInstance { - [OutputType([CimInstance])] + [OutputType([Microsoft.Management.Infrastructure.CimInstance])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Object] + [System.Object] $Process ) @@ -759,36 +764,36 @@ function Get-ProcessOwnerCimInstance #> function Get-ArgumentsFromCommandLineInput { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter()] - [String] + [System.String] $CommandLineInput ) - if ([String]::IsNullOrWhitespace($CommandLineInput)) + if ([System.String]::IsNullOrWhitespace($CommandLineInput)) { - return [String]::Empty + return [System.String]::Empty } $CommandLineInput = $CommandLineInput.Trim() if ($CommandLineInput.StartsWith('"')) { - $endOfCommandChar = [Char]'"' + $endOfCommandChar = [System.Char] '"' } else { - $endOfCommandChar = [Char]' ' + $endOfCommandChar = [System.Char] ' ' } $endofCommandIndex = $CommandLineInput.IndexOf($endOfCommandChar, 1) if ($endofCommandIndex -eq -1) { - return [String]::Empty + return [System.String]::Empty } return $CommandLineInput.Substring($endofCommandIndex + 1).Trim() @@ -810,11 +815,11 @@ function Assert-HashtableDoesNotContainKey param ( [Parameter(Mandatory = $true)] - [Hashtable] + [System.Collections.Hashtable] $Hashtable, [Parameter(Mandatory = $true)] - [String[]] + [System.String[]] $Key ) @@ -846,31 +851,31 @@ function Assert-HashtableDoesNotContainKey #> function Wait-ProcessCount { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [Hashtable] + [System.Collections.Hashtable] $ProcessSettings, [Parameter(Mandatory = $true)] - [ValidateRange(0, [Int]::MaxValue)] - [Int] + [ValidateRange(0, [System.Int32]::MaxValue)] + [System.Int32] $ProcessCount, [Parameter()] - [Int] + [System.Int32] $WaitTime = 200000 ) - $startTime = [DateTime]::Now + $startTime = [System.DateTime]::Now do { $actualProcessCount = @( Get-ProcessCimInstance @ProcessSettings ).Count - } while ($actualProcessCount -ne $ProcessCount -and ([DateTime]::Now - $startTime).TotalMilliseconds -lt $WaitTime) + } while ($actualProcessCount -ne $ProcessCount -and ([System.DateTime]::Now - $startTime).TotalMilliseconds -lt $WaitTime) return $actualProcessCount -eq $ProcessCount } @@ -892,12 +897,12 @@ function Assert-PathArgumentRooted ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $PathArgumentName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $PathArgument ) @@ -927,19 +932,19 @@ function Assert-PathArgumentValid ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $PathArgumentName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $PathArgument ) if (-not (Test-Path -Path $PathArgument)) { $message = $script:localizedData.PathShouldExist -f $PathArgument, $PathArgumentName - + New-InvalidArgumentException -ArgumentName 'Path' ` -Message $message } @@ -951,7 +956,7 @@ function Assert-PathArgumentValid #> function Test-IsRunFromLocalSystemUser { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param () @@ -977,16 +982,16 @@ function Test-IsRunFromLocalSystemUser function Start-ProcessAsLocalSystemUser { [CmdletBinding()] - param + param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [AllowEmptyString()] - [String] + [System.String] $Arguments, [Parameter(Mandatory = $true)] @@ -1024,7 +1029,7 @@ function Start-ProcessAsLocalSystemUser #> function Split-Credential { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( @@ -1069,7 +1074,7 @@ function Split-Credential } else { - # support for default domain (localhost) + # Support for default domain (localhost) $domain = $env:computerName $userName = $Credential.UserName } @@ -1099,7 +1104,7 @@ function Split-Credential function Assert-PsDscContextNotRunAsUser { [CmdletBinding()] - param + param () Set-StrictMode -Off @@ -1110,6 +1115,7 @@ function Assert-PsDscContextNotRunAsUser ArgumentName = 'PsDscRunAsCredential' Message = ($script:localizedData.ErrorRunAsCredentialParameterNotSupported -f $PsDscContext.RunAsUser) } + New-InvalidArgumentException @newInvalidArgumentExceptionParams } } @@ -1122,387 +1128,387 @@ function Assert-PsDscContextNotRunAsUser #> function Import-DscNativeMethods { -$dscNativeMethodsSource = @" - -using System; -using System.Collections.Generic; -using System.Text; -using System.Security; -using System.Runtime.InteropServices; -using System.Diagnostics; -using System.Security.Principal; -#if !CORECLR -using System.ComponentModel; -#endif -using System.IO; - -namespace PSDesiredStateConfiguration -{ -#if !CORECLR - [SuppressUnmanagedCodeSecurity] -#endif - public static class NativeMethods - { - //The following structs and enums are used by the various Win32 API's that are used in the code below - - [StructLayout(LayoutKind.Sequential)] - public struct STARTUPINFO - { - public Int32 cb; - public string lpReserved; - public string lpDesktop; - public string lpTitle; - public Int32 dwX; - public Int32 dwY; - public Int32 dwXSize; - public Int32 dwXCountChars; - public Int32 dwYCountChars; - public Int32 dwFillAttribute; - public Int32 dwFlags; - public Int16 wShowWindow; - public Int16 cbReserved2; - public IntPtr lpReserved2; - public IntPtr hStdInput; - public IntPtr hStdOutput; - public IntPtr hStdError; - } - - [StructLayout(LayoutKind.Sequential)] - public struct PROCESS_INFORMATION - { - public IntPtr hProcess; - public IntPtr hThread; - public Int32 dwProcessID; - public Int32 dwThreadID; - } - - [Flags] - public enum LogonType - { - LOGON32_LOGON_INTERACTIVE = 2, - LOGON32_LOGON_NETWORK = 3, - LOGON32_LOGON_BATCH = 4, - LOGON32_LOGON_SERVICE = 5, - LOGON32_LOGON_UNLOCK = 7, - LOGON32_LOGON_NETWORK_CLEARTEXT = 8, - LOGON32_LOGON_NEW_CREDENTIALS = 9 - } - - [Flags] - public enum LogonProvider - { - LOGON32_PROVIDER_DEFAULT = 0, - LOGON32_PROVIDER_WINNT35, - LOGON32_PROVIDER_WINNT40, - LOGON32_PROVIDER_WINNT50 - } - [StructLayout(LayoutKind.Sequential)] - public struct SECURITY_ATTRIBUTES - { - public Int32 Length; - public IntPtr lpSecurityDescriptor; - public bool bInheritHandle; - } - - public enum SECURITY_IMPERSONATION_LEVEL - { - SecurityAnonymous, - SecurityIdentification, - SecurityImpersonation, - SecurityDelegation - } - - public enum TOKEN_TYPE - { - TokenPrimary = 1, - TokenImpersonation - } - - [StructLayout(LayoutKind.Sequential, Pack = 1)] - internal struct TokPriv1Luid - { - public int Count; - public long Luid; - public int Attr; - } - - public const int GENERIC_ALL_ACCESS = 0x10000000; - public const int CREATE_NO_WINDOW = 0x08000000; - internal const int SE_PRIVILEGE_ENABLED = 0x00000002; - internal const int TOKEN_QUERY = 0x00000008; - internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; - internal const string SE_INCRASE_QUOTA = "SeIncreaseQuotaPrivilege"; - -#if CORECLR - [DllImport("api-ms-win-core-handle-l1-1-0.dll", -#else - [DllImport("kernel32.dll", -#endif - EntryPoint = "CloseHandle", SetLastError = true, - CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] - public static extern bool CloseHandle(IntPtr handle); - -#if CORECLR - [DllImport("api-ms-win-core-processthreads-l1-1-2.dll", -#else - [DllImport("advapi32.dll", -#endif - EntryPoint = "CreateProcessAsUser", SetLastError = true, - CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] - public static extern bool CreateProcessAsUser( - IntPtr hToken, - string lpApplicationName, - string lpCommandLine, - ref SECURITY_ATTRIBUTES lpProcessAttributes, - ref SECURITY_ATTRIBUTES lpThreadAttributes, - bool bInheritHandle, - Int32 dwCreationFlags, - IntPtr lpEnvrionment, - string lpCurrentDirectory, - ref STARTUPINFO lpStartupInfo, - ref PROCESS_INFORMATION lpProcessInformation - ); - -#if CORECLR - [DllImport("api-ms-win-security-base-l1-1-0.dll", EntryPoint = "DuplicateTokenEx")] -#else - [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")] -#endif - public static extern bool DuplicateTokenEx( - IntPtr hExistingToken, - Int32 dwDesiredAccess, - ref SECURITY_ATTRIBUTES lpThreadAttributes, - Int32 ImpersonationLevel, - Int32 dwTokenType, - ref IntPtr phNewToken - ); - -#if CORECLR - [DllImport("api-ms-win-security-logon-l1-1-1.dll", CharSet = CharSet.Unicode, SetLastError = true)] -#else - [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] -#endif - public static extern Boolean LogonUser( - String lpszUserName, - String lpszDomain, - IntPtr lpszPassword, - LogonType dwLogonType, - LogonProvider dwLogonProvider, - out IntPtr phToken - ); - -#if CORECLR - [DllImport("api-ms-win-security-base-l1-1-0.dll", ExactSpelling = true, SetLastError = true)] -#else - [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] -#endif - internal static extern bool AdjustTokenPrivileges( - IntPtr htok, - bool disall, - ref TokPriv1Luid newst, - int len, - IntPtr prev, - IntPtr relen - ); - -#if CORECLR - [DllImport("api-ms-win-downlevel-kernel32-l1-1-0.dll", ExactSpelling = true)] -#else - [DllImport("kernel32.dll", ExactSpelling = true)] -#endif - internal static extern IntPtr GetCurrentProcess(); - -#if CORECLR - [DllImport("api-ms-win-downlevel-advapi32-l1-1-1.dll", ExactSpelling = true, SetLastError = true)] -#else - [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] -#endif - internal static extern bool OpenProcessToken( - IntPtr h, - int acc, - ref IntPtr phtok - ); - -#if CORECLR - [DllImport("api-ms-win-downlevel-kernel32-l1-1-0.dll", ExactSpelling = true)] -#else - [DllImport("kernel32.dll", ExactSpelling = true)] -#endif - internal static extern int WaitForSingleObject( - IntPtr h, - int milliseconds - ); - -#if CORECLR - [DllImport("api-ms-win-downlevel-kernel32-l1-1-0.dll", ExactSpelling = true)] -#else - [DllImport("kernel32.dll", ExactSpelling = true)] -#endif - internal static extern bool GetExitCodeProcess( - IntPtr h, - out int exitcode - ); - -#if CORECLR - [DllImport("api-ms-win-downlevel-advapi32-l4-1-0.dll", SetLastError = true)] -#else - [DllImport("advapi32.dll", SetLastError = true)] -#endif - internal static extern bool LookupPrivilegeValue( - string host, - string name, - ref long pluid - ); - - internal static void ThrowException( - string message - ) - { -#if CORECLR - throw new Exception(message); -#else - throw new Win32Exception(message); -#endif - } - - public static void CreateProcessAsUser(string strCommand, string strDomain, string strName, SecureString secureStringPassword, bool waitForExit, ref int ExitCode) - { - var hToken = IntPtr.Zero; - var hDupedToken = IntPtr.Zero; - TokPriv1Luid tp; - var pi = new PROCESS_INFORMATION(); - var sa = new SECURITY_ATTRIBUTES(); - sa.Length = Marshal.SizeOf(sa); - Boolean bResult = false; - try - { - IntPtr unmanagedPassword = IntPtr.Zero; - try - { -#if CORECLR - unmanagedPassword = SecureStringMarshal.SecureStringToCoTaskMemUnicode(secureStringPassword); -#else - unmanagedPassword = Marshal.SecureStringToGlobalAllocUnicode(secureStringPassword); -#endif - bResult = LogonUser( - strName, - strDomain, - unmanagedPassword, - LogonType.LOGON32_LOGON_NETWORK_CLEARTEXT, - LogonProvider.LOGON32_PROVIDER_DEFAULT, - out hToken - ); - } - finally - { - Marshal.ZeroFreeGlobalAllocUnicode(unmanagedPassword); - } - if (!bResult) - { - ThrowException("$($script:localizedData.UserCouldNotBeLoggedError)" + Marshal.GetLastWin32Error().ToString()); - } - IntPtr hproc = GetCurrentProcess(); - IntPtr htok = IntPtr.Zero; - bResult = OpenProcessToken( - hproc, - TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, - ref htok - ); - if (!bResult) - { - ThrowException("$($script:localizedData.OpenProcessTokenError)" + Marshal.GetLastWin32Error().ToString()); - } - tp.Count = 1; - tp.Luid = 0; - tp.Attr = SE_PRIVILEGE_ENABLED; - bResult = LookupPrivilegeValue( - null, - SE_INCRASE_QUOTA, - ref tp.Luid - ); - if (!bResult) - { - ThrowException("$($script:localizedData.PrivilegeLookingUpError)" + Marshal.GetLastWin32Error().ToString()); - } - bResult = AdjustTokenPrivileges( - htok, - false, - ref tp, - 0, - IntPtr.Zero, - IntPtr.Zero - ); - if (!bResult) - { - ThrowException("$($script:localizedData.TokenElevationError)" + Marshal.GetLastWin32Error().ToString()); - } - - bResult = DuplicateTokenEx( - hToken, - GENERIC_ALL_ACCESS, - ref sa, - (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, - (int)TOKEN_TYPE.TokenPrimary, - ref hDupedToken - ); - if (!bResult) - { - ThrowException("$($script:localizedData.DuplicateTokenError)" + Marshal.GetLastWin32Error().ToString()); - } - var si = new STARTUPINFO(); - si.cb = Marshal.SizeOf(si); - si.lpDesktop = ""; - bResult = CreateProcessAsUser( - hDupedToken, - null, - strCommand, - ref sa, - ref sa, - false, - 0, - IntPtr.Zero, - null, - ref si, - ref pi - ); - if (!bResult) - { - ThrowException("$($script:localizedData.CouldNotCreateProcessError)" + Marshal.GetLastWin32Error().ToString()); - } - if (waitForExit) { - int status = WaitForSingleObject(pi.hProcess, -1); - if(status == -1) - { - ThrowException("$($script:localizedData.WaitFailedError)" + Marshal.GetLastWin32Error().ToString()); - } - - bResult = GetExitCodeProcess(pi.hProcess, out ExitCode); - if(!bResult) - { - ThrowException("$($script:localizedData.RetriveStatusError)" + Marshal.GetLastWin32Error().ToString()); - } - } - } - finally - { - if (pi.hThread != IntPtr.Zero) - { - CloseHandle(pi.hThread); - } - if (pi.hProcess != IntPtr.Zero) - { - CloseHandle(pi.hProcess); - } - if (hDupedToken != IntPtr.Zero) - { - CloseHandle(hDupedToken); - } - } - } - } -} - + $dscNativeMethodsSource = @" + +using System; +using System.Collections.Generic; +using System.Text; +using System.Security; +using System.Runtime.InteropServices; +using System.Diagnostics; +using System.Security.Principal; +#if !CORECLR +using System.ComponentModel; +#endif +using System.IO; + +namespace PSDesiredStateConfiguration +{ +#if !CORECLR + [SuppressUnmanagedCodeSecurity] +#endif + public static class NativeMethods + { + //The following structs and enums are used by the various Win32 API's that are used in the code below + + [StructLayout(LayoutKind.Sequential)] + public struct STARTUPINFO + { + public Int32 cb; + public string lpReserved; + public string lpDesktop; + public string lpTitle; + public Int32 dwX; + public Int32 dwY; + public Int32 dwXSize; + public Int32 dwXCountChars; + public Int32 dwYCountChars; + public Int32 dwFillAttribute; + public Int32 dwFlags; + public Int16 wShowWindow; + public Int16 cbReserved2; + public IntPtr lpReserved2; + public IntPtr hStdInput; + public IntPtr hStdOutput; + public IntPtr hStdError; + } + + [StructLayout(LayoutKind.Sequential)] + public struct PROCESS_INFORMATION + { + public IntPtr hProcess; + public IntPtr hThread; + public Int32 dwProcessID; + public Int32 dwThreadID; + } + + [Flags] + public enum LogonType + { + LOGON32_LOGON_INTERACTIVE = 2, + LOGON32_LOGON_NETWORK = 3, + LOGON32_LOGON_BATCH = 4, + LOGON32_LOGON_SERVICE = 5, + LOGON32_LOGON_UNLOCK = 7, + LOGON32_LOGON_NETWORK_CLEARTEXT = 8, + LOGON32_LOGON_NEW_CREDENTIALS = 9 + } + + [Flags] + public enum LogonProvider + { + LOGON32_PROVIDER_DEFAULT = 0, + LOGON32_PROVIDER_WINNT35, + LOGON32_PROVIDER_WINNT40, + LOGON32_PROVIDER_WINNT50 + } + [StructLayout(LayoutKind.Sequential)] + public struct SECURITY_ATTRIBUTES + { + public Int32 Length; + public IntPtr lpSecurityDescriptor; + public bool bInheritHandle; + } + + public enum SECURITY_IMPERSONATION_LEVEL + { + SecurityAnonymous, + SecurityIdentification, + SecurityImpersonation, + SecurityDelegation + } + + public enum TOKEN_TYPE + { + TokenPrimary = 1, + TokenImpersonation + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct TokPriv1Luid + { + public int Count; + public long Luid; + public int Attr; + } + + public const int GENERIC_ALL_ACCESS = 0x10000000; + public const int CREATE_NO_WINDOW = 0x08000000; + internal const int SE_PRIVILEGE_ENABLED = 0x00000002; + internal const int TOKEN_QUERY = 0x00000008; + internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; + internal const string SE_INCRASE_QUOTA = "SeIncreaseQuotaPrivilege"; + +#if CORECLR + [DllImport("api-ms-win-core-handle-l1-1-0.dll", +#else + [DllImport("kernel32.dll", +#endif + EntryPoint = "CloseHandle", SetLastError = true, + CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] + public static extern bool CloseHandle(IntPtr handle); + +#if CORECLR + [DllImport("api-ms-win-core-processthreads-l1-1-2.dll", +#else + [DllImport("advapi32.dll", +#endif + EntryPoint = "CreateProcessAsUser", SetLastError = true, + CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] + public static extern bool CreateProcessAsUser( + IntPtr hToken, + string lpApplicationName, + string lpCommandLine, + ref SECURITY_ATTRIBUTES lpProcessAttributes, + ref SECURITY_ATTRIBUTES lpThreadAttributes, + bool bInheritHandle, + Int32 dwCreationFlags, + IntPtr lpEnvrionment, + string lpCurrentDirectory, + ref STARTUPINFO lpStartupInfo, + ref PROCESS_INFORMATION lpProcessInformation + ); + +#if CORECLR + [DllImport("api-ms-win-security-base-l1-1-0.dll", EntryPoint = "DuplicateTokenEx")] +#else + [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")] +#endif + public static extern bool DuplicateTokenEx( + IntPtr hExistingToken, + Int32 dwDesiredAccess, + ref SECURITY_ATTRIBUTES lpThreadAttributes, + Int32 ImpersonationLevel, + Int32 dwTokenType, + ref IntPtr phNewToken + ); + +#if CORECLR + [DllImport("api-ms-win-security-logon-l1-1-1.dll", CharSet = CharSet.Unicode, SetLastError = true)] +#else + [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] +#endif + public static extern Boolean LogonUser( + String lpszUserName, + String lpszDomain, + IntPtr lpszPassword, + LogonType dwLogonType, + LogonProvider dwLogonProvider, + out IntPtr phToken + ); + +#if CORECLR + [DllImport("api-ms-win-security-base-l1-1-0.dll", ExactSpelling = true, SetLastError = true)] +#else + [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] +#endif + internal static extern bool AdjustTokenPrivileges( + IntPtr htok, + bool disall, + ref TokPriv1Luid newst, + int len, + IntPtr prev, + IntPtr relen + ); + +#if CORECLR + [DllImport("api-ms-win-downlevel-kernel32-l1-1-0.dll", ExactSpelling = true)] +#else + [DllImport("kernel32.dll", ExactSpelling = true)] +#endif + internal static extern IntPtr GetCurrentProcess(); + +#if CORECLR + [DllImport("api-ms-win-downlevel-advapi32-l1-1-1.dll", ExactSpelling = true, SetLastError = true)] +#else + [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] +#endif + internal static extern bool OpenProcessToken( + IntPtr h, + int acc, + ref IntPtr phtok + ); + +#if CORECLR + [DllImport("api-ms-win-downlevel-kernel32-l1-1-0.dll", ExactSpelling = true)] +#else + [DllImport("kernel32.dll", ExactSpelling = true)] +#endif + internal static extern int WaitForSingleObject( + IntPtr h, + int milliseconds + ); + +#if CORECLR + [DllImport("api-ms-win-downlevel-kernel32-l1-1-0.dll", ExactSpelling = true)] +#else + [DllImport("kernel32.dll", ExactSpelling = true)] +#endif + internal static extern bool GetExitCodeProcess( + IntPtr h, + out int exitcode + ); + +#if CORECLR + [DllImport("api-ms-win-downlevel-advapi32-l4-1-0.dll", SetLastError = true)] +#else + [DllImport("advapi32.dll", SetLastError = true)] +#endif + internal static extern bool LookupPrivilegeValue( + string host, + string name, + ref long pluid + ); + + internal static void ThrowException( + string message + ) + { +#if CORECLR + throw new Exception(message); +#else + throw new Win32Exception(message); +#endif + } + + public static void CreateProcessAsUser(string strCommand, string strDomain, string strName, SecureString secureStringPassword, bool waitForExit, ref int ExitCode) + { + var hToken = IntPtr.Zero; + var hDupedToken = IntPtr.Zero; + TokPriv1Luid tp; + var pi = new PROCESS_INFORMATION(); + var sa = new SECURITY_ATTRIBUTES(); + sa.Length = Marshal.SizeOf(sa); + Boolean bResult = false; + try + { + IntPtr unmanagedPassword = IntPtr.Zero; + try + { +#if CORECLR + unmanagedPassword = SecureStringMarshal.SecureStringToCoTaskMemUnicode(secureStringPassword); +#else + unmanagedPassword = Marshal.SecureStringToGlobalAllocUnicode(secureStringPassword); +#endif + bResult = LogonUser( + strName, + strDomain, + unmanagedPassword, + LogonType.LOGON32_LOGON_NETWORK_CLEARTEXT, + LogonProvider.LOGON32_PROVIDER_DEFAULT, + out hToken + ); + } + finally + { + Marshal.ZeroFreeGlobalAllocUnicode(unmanagedPassword); + } + if (!bResult) + { + ThrowException("$($script:localizedData.UserCouldNotBeLoggedError)" + Marshal.GetLastWin32Error().ToString()); + } + IntPtr hproc = GetCurrentProcess(); + IntPtr htok = IntPtr.Zero; + bResult = OpenProcessToken( + hproc, + TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, + ref htok + ); + if (!bResult) + { + ThrowException("$($script:localizedData.OpenProcessTokenError)" + Marshal.GetLastWin32Error().ToString()); + } + tp.Count = 1; + tp.Luid = 0; + tp.Attr = SE_PRIVILEGE_ENABLED; + bResult = LookupPrivilegeValue( + null, + SE_INCRASE_QUOTA, + ref tp.Luid + ); + if (!bResult) + { + ThrowException("$($script:localizedData.PrivilegeLookingUpError)" + Marshal.GetLastWin32Error().ToString()); + } + bResult = AdjustTokenPrivileges( + htok, + false, + ref tp, + 0, + IntPtr.Zero, + IntPtr.Zero + ); + if (!bResult) + { + ThrowException("$($script:localizedData.TokenElevationError)" + Marshal.GetLastWin32Error().ToString()); + } + + bResult = DuplicateTokenEx( + hToken, + GENERIC_ALL_ACCESS, + ref sa, + (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, + (int)TOKEN_TYPE.TokenPrimary, + ref hDupedToken + ); + if (!bResult) + { + ThrowException("$($script:localizedData.DuplicateTokenError)" + Marshal.GetLastWin32Error().ToString()); + } + var si = new STARTUPINFO(); + si.cb = Marshal.SizeOf(si); + si.lpDesktop = ""; + bResult = CreateProcessAsUser( + hDupedToken, + null, + strCommand, + ref sa, + ref sa, + false, + 0, + IntPtr.Zero, + null, + ref si, + ref pi + ); + if (!bResult) + { + ThrowException("$($script:localizedData.CouldNotCreateProcessError)" + Marshal.GetLastWin32Error().ToString()); + } + if (waitForExit) { + int status = WaitForSingleObject(pi.hProcess, -1); + if(status == -1) + { + ThrowException("$($script:localizedData.WaitFailedError)" + Marshal.GetLastWin32Error().ToString()); + } + + bResult = GetExitCodeProcess(pi.hProcess, out ExitCode); + if(!bResult) + { + ThrowException("$($script:localizedData.RetriveStatusError)" + Marshal.GetLastWin32Error().ToString()); + } + } + } + finally + { + if (pi.hThread != IntPtr.Zero) + { + CloseHandle(pi.hThread); + } + if (pi.hProcess != IntPtr.Zero) + { + CloseHandle(pi.hProcess); + } + if (hDupedToken != IntPtr.Zero) + { + CloseHandle(hDupedToken); + } + } + } + } +} + "@ # if not on Nano: Add-Type -TypeDefinition $dscNativeMethodsSource -ReferencedAssemblies 'System.ServiceProcess' -} +} diff --git a/DscResources/ProcessSet/ProcessSet.psd1 b/DscResources/ProcessSet/ProcessSet.psd1 index 4075e4c..518464d 100644 --- a/DscResources/ProcessSet/ProcessSet.psd1 +++ b/DscResources/ProcessSet/ProcessSet.psd1 @@ -1,4 +1,4 @@ -@{ +@{ # Script module or binary module file associated with this manifest. RootModule = 'ProcessSet.schema.psm1' diff --git a/DscResources/ProcessSet/ProcessSet.schema.psm1 b/DscResources/ProcessSet/ProcessSet.schema.psm1 index 4f25592..c518b5a 100644 --- a/DscResources/ProcessSet/ProcessSet.schema.psm1 +++ b/DscResources/ProcessSet/ProcessSet.schema.psm1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' # Import ResourceSetHelper for New-ResourceSetConfigurationScriptBlock @@ -51,43 +51,43 @@ Configuration ProcessSet [CmdletBinding()] param ( - [Parameter(Mandatory = $true, HelpMessage="The file paths to the executables of the processes to start or stop. Only the names of the files may be specified if they are all accessible through the environment path. Relative paths are not supported.")] + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Path, - [Parameter(HelpMessage="Specifies whether or not the processes should exist. To start processes, set this property to Present. To stop processes, set this property to Absent.")] + [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, - [Parameter(HelpMessage="The credential of the user account to start the processes under.")] + [Parameter()] [ValidateNotNullOrEmpty()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, - [Parameter(HelpMessage="The file path to write the standard output to. Any existing file at this path will be overwritten.This property cannot be specified at the same time as Credential when running the processes as a local user.")] + [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $StandardOutputPath, - [Parameter(HelpMessage="The file path to write the standard error output to. Any existing file at this path will be overwritten.")] + [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $StandardErrorPath, - [Parameter(HelpMessage="The file path to get standard input from. This property cannot be specified at the same time as Credential when running the processes as a local user.")] + [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $StandardInputPath, - [Parameter(HelpMessage="The file path to use as the working directory for the processes. Any existing file at this path will be overwritten. This property cannot be specified at the same time as Credential when running the processes as a local user.")] + [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $WorkingDirectory ) - + $newResourceSetConfigurationParams = @{ ResourceName = 'WindowsProcess' ModuleName = 'PSDscResources' @@ -97,7 +97,7 @@ Configuration ProcessSet # Arguments is a key parameter in WindowsProcess resource. Adding it as a common parameter with an empty value string $newResourceSetConfigurationParams['Parameters']['Arguments'] = '' - + $configurationScriptBlock = New-ResourceSetConfigurationScriptBlock @newResourceSetConfigurationParams # This script block must be run directly in this configuration in order to resolve variables diff --git a/DscResources/ResourceSetHelper.psm1 b/DscResources/ResourceSetHelper.psm1 index ee80714..c436951 100644 --- a/DscResources/ResourceSetHelper.psm1 +++ b/DscResources/ResourceSetHelper.psm1 @@ -1,4 +1,4 @@ -# This module should not write any verbose or error messages unless a localization file for it is added +# This module should not write any verbose or error messages unless a localization file for it is added $errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' @@ -27,24 +27,24 @@ Set-StrictMode -Version 'Latest' #> function New-ResourceSetCommonParameterString { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyParameterName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [Hashtable] + [System.Collections.Hashtable] $Parameters ) $stringBuilder = New-Object -TypeName 'System.Text.StringBuilder' - foreach ($parameterName in $Parameters.Keys) + foreach ($parameterName in $Parameters.Keys) { # All composite resources have an extra parameter 'InstanceName' if ($parameterName -ine $KeyParameterName -and $parameterName -ine 'InstanceName') @@ -53,7 +53,7 @@ function New-ResourceSetCommonParameterString if ($null -ne $parameterValue) { - if ($parameterValue -is [String]) + if ($parameterValue -is [System.String]) { $null = $stringBuilder.AppendFormat('{0} = "{1}"', $parameterName, $parameterValue) } @@ -106,7 +106,7 @@ function New-ResourceSetCommonParameterString Name = "Telnet-Client" Ensure = "Present" IncludeAllSubFeature = $true - } + } WindowsFeature Resource1 { @@ -117,33 +117,33 @@ function New-ResourceSetCommonParameterString #> function New-ResourceSetConfigurationString { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ResourceName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ModuleName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyParameterName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] - $KeyParameterValues, - + [System.String[]] + $KeyParameterValues, + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $CommonParameterString ) @@ -162,7 +162,7 @@ function New-ResourceSetConfigurationString $null = $stringBuilder.AppendLine() $null = $stringBuilder.Append($CommonParameterString) $null = $stringBuilder.AppendLine('}') - + $resourceCount++ } @@ -195,7 +195,7 @@ function New-ResourceSetConfigurationString CommonParameterNames = @( 'Ensure', 'MembersToInclude', 'MembersToExclude', 'Credential' ) Parameters = $PSBoundParameters } - + $configurationScriptBlock = New-ResourceSetConfigurationScriptBlock @newResourceSetConfigurationParams .NOTES @@ -205,28 +205,28 @@ function New-ResourceSetConfigurationString #> function New-ResourceSetConfigurationScriptBlock { - [OutputType([ScriptBlock])] + [OutputType([System.Management.Automation.ScriptBlock])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ResourceName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ModuleName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyParameterName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [Hashtable] + [System.Collections.Hashtable] $Parameters ) @@ -242,7 +242,7 @@ function New-ResourceSetConfigurationScriptBlock $resourceString = New-ResourceSetConfigurationString @newResourceSetConfigurationStringParams - return [ScriptBlock]::Create($resourceString) + return [System.Management.Automation.ScriptBlock]::Create($resourceString) } Export-ModuleMember -Function @( 'New-ResourceSetConfigurationScriptBlock' ) diff --git a/DscResources/ServiceSet/ServiceSet.psd1 b/DscResources/ServiceSet/ServiceSet.psd1 index 68f4796..3578a65 100644 --- a/DscResources/ServiceSet/ServiceSet.psd1 +++ b/DscResources/ServiceSet/ServiceSet.psd1 @@ -1,4 +1,4 @@ -@{ +@{ # Script module or binary module file associated with this manifest. RootModule = 'ServiceSet.schema.psm1' diff --git a/DscResources/ServiceSet/ServiceSet.schema.psm1 b/DscResources/ServiceSet/ServiceSet.schema.psm1 index b501f4c..2fac68a 100644 --- a/DscResources/ServiceSet/ServiceSet.schema.psm1 +++ b/DscResources/ServiceSet/ServiceSet.schema.psm1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' # Import ResourceSetHelper for New-ResourceSetConfigurationScriptBlock @@ -18,7 +18,7 @@ Import-Module -Name $script:resourceSetHelperFilePath .PARAMETER Ensure Specifies whether or not the set of services should exist. - + Set this property to Present to modify a set of services. Set this property to Absent to remove a set of services. @@ -51,32 +51,32 @@ Configuration ServiceSet [CmdletBinding()] param ( - [Parameter(Mandatory = $true, HelpMessage="An array of the names of the services to configure.")] + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Name, - [Parameter(HelpMessage="Specifies whether or not the set of services should exist. Set this property to Present to modify a set of services. Set this property to Absent to remove a set of services.")] + [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, - [Parameter(HelpMessage="The startup type each service in the set should have.")] + [Parameter()] [ValidateSet('Automatic', 'Manual', 'Disabled')] - [String] + [System.String] $StartupType, - [Parameter(HelpMessage="The built-in account each service in the set should start under. Cannot be specified at the same time as Credential. The user account specified by this property must have access to the service executable paths in order to start the services.")] + [Parameter()] [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')] - [String] + [System.String] $BuiltInAccount, - [Parameter(HelpMessage="The state each service in the set should be in. From the default value defined in Service, the default will be Running.")] + [Parameter()] [ValidateSet('Running', 'Stopped', 'Ignore')] - [String] + [System.String] $State, - [Parameter(HelpMessage="he credential of the user account each service in the set should start under. Cannot be specified at the same time as BuiltInAccount. The user specified by this credential will automatically be granted the Log on as a Service right. The user account specified by this property must have access to the service executable paths in order to start the services.")] + [Parameter()] [ValidateNotNull()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] @@ -89,7 +89,7 @@ Configuration ServiceSet KeyParameterName = 'Name' Parameters = $PSBoundParameters } - + $configurationScriptBlock = New-ResourceSetConfigurationScriptBlock @newResourceSetConfigurationParams # This script block must be run directly in this configuration in order to resolve variables diff --git a/DscResources/WindowsFeatureSet/WindowsFeatureSet.psd1 b/DscResources/WindowsFeatureSet/WindowsFeatureSet.psd1 index a0a3694..53b27e2 100644 --- a/DscResources/WindowsFeatureSet/WindowsFeatureSet.psd1 +++ b/DscResources/WindowsFeatureSet/WindowsFeatureSet.psd1 @@ -1,4 +1,4 @@ -@{ +@{ # Script module or binary module file associated with this manifest. RootModule = 'WindowsFeatureSet.schema.psm1' diff --git a/DscResources/WindowsFeatureSet/WindowsFeatureSet.schema.psm1 b/DscResources/WindowsFeatureSet/WindowsFeatureSet.schema.psm1 index 3e8f20c..dfe2942 100644 --- a/DscResources/WindowsFeatureSet/WindowsFeatureSet.schema.psm1 +++ b/DscResources/WindowsFeatureSet/WindowsFeatureSet.schema.psm1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' # Import ResourceSetHelper for New-ResourceSetConfigurationScriptBlock @@ -41,42 +41,34 @@ Configuration WindowsFeatureSet [CmdletBinding()] param ( - [Parameter(Mandatory = $true, HelpMessage="The name of the roles or features to install or uninstall.")] + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Name, - [Parameter(HelpMessage="Specifies whether the roles or features should be installed or uninstalled. - - To install the features, set this property to Present. - To uninstall the features, set this property to Absent.")] + [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, - [Parameter(HelpMessage="Specify the source")] + [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Source, - [Parameter(HelpMessage="Specifies whether or not all subfeatures should be installed or uninstalled alongside the specified roles or features. - - If this property is true and Ensure is set to Present, all subfeatures will be installed. - If this property is false and Ensure is set to Present, subfeatures will not be installed or uninstalled. - If Ensure is set to Absent, all subfeatures will be uninstalled.")] - [Boolean] + [Parameter()] + [System.Boolean] $IncludeAllSubFeature, - [Parameter(HelpMessage="The credential of the user account under which to install or uninstall the roles or features.")] + [Parameter()] [ValidateNotNull()] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] $Credential, - [Parameter(HelpMessage="The custom file path to which to log this operation. - If not passed in, the default log path will be used (%windir%\logs\ServerManager.log).")] + [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath ) @@ -86,7 +78,7 @@ Configuration WindowsFeatureSet KeyParameterName = 'Name' Parameters = $PSBoundParameters } - + $configurationScriptBlock = New-ResourceSetConfigurationScriptBlock @newResourceSetConfigurationParams # This script block must be run directly in this configuration in order to resolve variables diff --git a/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.psd1 b/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.psd1 index f9d27d2..2e95b92 100644 --- a/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.psd1 +++ b/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.psd1 @@ -1,4 +1,4 @@ -@{ +@{ # Script module or binary module file associated with this manifest. RootModule = 'WindowsOptionalFeatureSet.schema.psm1' diff --git a/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.schema.psm1 b/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.schema.psm1 index df15612..585fb94 100644 --- a/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.schema.psm1 +++ b/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.schema.psm1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' # Import ResourceSetHelper for New-ResourceSetConfigurationScriptBlock @@ -41,35 +41,32 @@ Configuration WindowsOptionalFeatureSet [CmdletBinding()] param ( - [Parameter(Mandatory = $true, HelpMessage="The names of the Windows optional features to enable or disable.")] + [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Name, - [Parameter(Mandatory = $true, HelpMessage="Specifies whether the features should be enabled or disabled. - - To enable a set of features, set this property to Present. - To disable a set of features, set this property to Absent.")] + [Parameter(Mandatory = $true)] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, - [Parameter(HelpMessage="Specifies whether or not to remove all files associated with the features when they are disabled.")] - [Boolean] + [Parameter()] + [System.Boolean] $RemoveFilesOnDisable, - [Parameter(HelpMessage="Specifies whether or not DISM should contact Windows Update (WU) when searching for the source files to restore Windows optional features on an online image.")] - [Boolean] + [Parameter()] + [System.Boolean] $NoWindowsUpdateCheck, - [Parameter(HelpMessage="The file path to which to log the opertation.")] + [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath, - [Parameter(HelpMessage="The level of detail to include in the log.")] + [Parameter()] [ValidateSet('ErrorsOnly', 'ErrorsAndWarning', 'ErrorsAndWarningAndInformation')] - [String] + [System.String] $LogLevel ) @@ -79,7 +76,7 @@ Configuration WindowsOptionalFeatureSet KeyParameterName = 'Name' Parameters = $PSBoundParameters } - + $configurationScriptBlock = New-ResourceSetConfigurationScriptBlock @newResourceSetConfigurationParams # This script block must be run directly in this configuration in order to resolve variables diff --git a/Examples/Sample_Archive_ExpandArchiveNoValidationCredential.ps1 b/Examples/Sample_Archive_ExpandArchiveNoValidationCredential.ps1 index c1572df..060e53c 100644 --- a/Examples/Sample_Archive_ExpandArchiveNoValidationCredential.ps1 +++ b/Examples/Sample_Archive_ExpandArchiveNoValidationCredential.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Expands the archive located at 'C:\ExampleArchivePath\Archive.zip' to the destination path 'C:\ExampleDestinationPath\Destination'. diff --git a/Examples/Sample_Archive_RemoveArchiveChecksum.ps1 b/Examples/Sample_Archive_RemoveArchiveChecksum.ps1 index c05d805..c530b53 100644 --- a/Examples/Sample_Archive_RemoveArchiveChecksum.ps1 +++ b/Examples/Sample_Archive_RemoveArchiveChecksum.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Remove the expansion of the archive located at 'C:\ExampleArchivePath\Archive.zip' from the destination path 'C:\ExampleDestinationPath\Destination'. diff --git a/Examples/Sample_Archive_RemoveArchiveNoValidation.ps1 b/Examples/Sample_Archive_RemoveArchiveNoValidation.ps1 index 5578da9..2ccc726 100644 --- a/Examples/Sample_Archive_RemoveArchiveNoValidation.ps1 +++ b/Examples/Sample_Archive_RemoveArchiveNoValidation.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Removes the expansion of the archive located at 'C:\ExampleArchivePath\Archive.zip' from the destination path 'C:\ExampleDestinationPath\Destination'. diff --git a/Examples/Sample_Environment_CreateNonPathVariable.ps1 b/Examples/Sample_Environment_CreateNonPathVariable.ps1 index 9129fee..7598e0b 100644 --- a/Examples/Sample_Environment_CreateNonPathVariable.ps1 +++ b/Examples/Sample_Environment_CreateNonPathVariable.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Creates the environment variable 'TestEnvironmentVariable' and sets the value to 'TestValue' both on the machine and within the process. diff --git a/Examples/Sample_Environment_CreatePathVariable.ps1 b/Examples/Sample_Environment_CreatePathVariable.ps1 index 6b8270e..009a673 100644 --- a/Examples/Sample_Environment_CreatePathVariable.ps1 +++ b/Examples/Sample_Environment_CreatePathVariable.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Creates the environment variable 'TestPathEnvironmentVariable' and sets the value to 'TestValue' if it doesn't already exist or appends the value 'TestValue' to the existing path if it does diff --git a/Examples/Sample_Environment_Remove.ps1 b/Examples/Sample_Environment_Remove.ps1 index cabd3dd..4d88e33 100644 --- a/Examples/Sample_Environment_Remove.ps1 +++ b/Examples/Sample_Environment_Remove.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Removes the environment variable 'TestEnvironmentVariable' from both the machine and the process. diff --git a/Examples/Sample_GroupSet_AddMembers.ps1 b/Examples/Sample_GroupSet_AddMembers.ps1 index 702aa51..122e851 100644 --- a/Examples/Sample_GroupSet_AddMembers.ps1 +++ b/Examples/Sample_GroupSet_AddMembers.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS If the groups named GroupName1 and Administrators do not exist, creates the groups named GroupName1 and Administrators and adds the users with the usernames Username1 and Username2 diff --git a/Examples/Sample_Group_RemoveMembers.ps1 b/Examples/Sample_Group_RemoveMembers.ps1 index f75beee..58b1a34 100644 --- a/Examples/Sample_Group_RemoveMembers.ps1 +++ b/Examples/Sample_Group_RemoveMembers.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS If the group named GroupName1 does not exist, creates a group named GroupName1. diff --git a/Examples/Sample_Group_SetMembers.ps1 b/Examples/Sample_Group_SetMembers.ps1 index a050a3b..62be584 100644 --- a/Examples/Sample_Group_SetMembers.ps1 +++ b/Examples/Sample_Group_SetMembers.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS If the group named GroupName1 does not exist, creates a group named GroupName1 and adds the users with the usernames Username1 and Username2 to the group. diff --git a/Examples/Sample_ProcessSet_Start.ps1 b/Examples/Sample_ProcessSet_Start.ps1 index 7e32668..320fe15 100644 --- a/Examples/Sample_ProcessSet_Start.ps1 +++ b/Examples/Sample_ProcessSet_Start.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Starts the processes with the executables at the file paths C:\Windows\cmd.exe and C:\TestPath\TestProcess.exe with no arguments. diff --git a/Examples/Sample_ProcessSet_Stop.ps1 b/Examples/Sample_ProcessSet_Stop.ps1 index 4c47f6f..f1a9b06 100644 --- a/Examples/Sample_ProcessSet_Stop.ps1 +++ b/Examples/Sample_ProcessSet_Stop.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Stops the processes with the executables at the file paths C:\Windows\cmd.exe and C:\TestPath\TestProcess.exe with no arguments and logs any output to the path diff --git a/Examples/Sample_RegistryResource_AddKey.ps1 b/Examples/Sample_RegistryResource_AddKey.ps1 index 138d78f..c49cc96 100644 --- a/Examples/Sample_RegistryResource_AddKey.ps1 +++ b/Examples/Sample_RegistryResource_AddKey.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Create a new registry key called MyNewKey as a subkey under the key 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'. diff --git a/Examples/Sample_RegistryResource_AddOrModifyValue.ps1 b/Examples/Sample_RegistryResource_AddOrModifyValue.ps1 index df89a0a..ea98dc3 100644 --- a/Examples/Sample_RegistryResource_AddOrModifyValue.ps1 +++ b/Examples/Sample_RegistryResource_AddOrModifyValue.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS If the registry key value MyValue under the key 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' does not exist, diff --git a/Examples/Sample_RegistryResource_RemoveKey.ps1 b/Examples/Sample_RegistryResource_RemoveKey.ps1 index 79a2d17..f2cf276 100644 --- a/Examples/Sample_RegistryResource_RemoveKey.ps1 +++ b/Examples/Sample_RegistryResource_RemoveKey.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Removes the registry key called MyNewKey under the parent key 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'. diff --git a/Examples/Sample_RegistryResource_RemoveValue.ps1 b/Examples/Sample_RegistryResource_RemoveValue.ps1 index 2dec121..37be0ec 100644 --- a/Examples/Sample_RegistryResource_RemoveValue.ps1 +++ b/Examples/Sample_RegistryResource_RemoveValue.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Removes the registry key value MyValue from the key 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'. diff --git a/Examples/Sample_Script.ps1 b/Examples/Sample_Script.ps1 index caea309..e086cf7 100644 --- a/Examples/Sample_Script.ps1 +++ b/Examples/Sample_Script.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Creates a file at the given file path with the specified content through the Script resource. diff --git a/Examples/Sample_ServiceSet_BuiltInAccount.ps1 b/Examples/Sample_ServiceSet_BuiltInAccount.ps1 index d66b093..79c7820 100644 --- a/Examples/Sample_ServiceSet_BuiltInAccount.ps1 +++ b/Examples/Sample_ServiceSet_BuiltInAccount.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Sets the Secure Socket Tunneling Protocol and DHCP Client services to run under the built-in account LocalService. diff --git a/Examples/Sample_ServiceSet_StartServices.ps1 b/Examples/Sample_ServiceSet_StartServices.ps1 index fb8dfee..1ac00dd 100644 --- a/Examples/Sample_ServiceSet_StartServices.ps1 +++ b/Examples/Sample_ServiceSet_StartServices.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Ensures that the DHCP Client and Windows Firewall services are running. #> diff --git a/Examples/Sample_User_CreateUser.ps1 b/Examples/Sample_User_CreateUser.ps1 index b2aae55..fc75587 100644 --- a/Examples/Sample_User_CreateUser.ps1 +++ b/Examples/Sample_User_CreateUser.ps1 @@ -1,4 +1,4 @@ -Configuration UserExample +Configuration UserExample { param ( [System.Management.Automation.PSCredential] diff --git a/Examples/Sample_User_Generic.ps1 b/Examples/Sample_User_Generic.ps1 index 17cd506..bd44a8d 100644 --- a/Examples/Sample_User_Generic.ps1 +++ b/Examples/Sample_User_Generic.ps1 @@ -1,4 +1,4 @@ -param +param ( [Parameter(Mandatory)] [System.String] diff --git a/Examples/Sample_WindowsFeature.ps1 b/Examples/Sample_WindowsFeature.ps1 index 77d0352..db23f46 100644 --- a/Examples/Sample_WindowsFeature.ps1 +++ b/Examples/Sample_WindowsFeature.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Creates a custom configuration for installing or uninstalling a Windows role or feature. diff --git a/Examples/Sample_WindowsFeatureSet_Install.ps1 b/Examples/Sample_WindowsFeatureSet_Install.ps1 index 9c82264..48aeb95 100644 --- a/Examples/Sample_WindowsFeatureSet_Install.ps1 +++ b/Examples/Sample_WindowsFeatureSet_Install.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Installs the TelnetClient and RSAT-File-Services Windows features, including all their subfeatures. Logs the operation to the file at 'C:\LogPath\Log.log'. diff --git a/Examples/Sample_WindowsFeatureSet_Uninstall.ps1 b/Examples/Sample_WindowsFeatureSet_Uninstall.ps1 index 7e25124..eb8ecdf 100644 --- a/Examples/Sample_WindowsFeatureSet_Uninstall.ps1 +++ b/Examples/Sample_WindowsFeatureSet_Uninstall.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Uninstalls the TelnetClient and RSAT-File-Services Windows features, including all their subfeatures. Logs the operation to the file at 'C:\LogPath\Log.log'. diff --git a/Examples/Sample_WindowsOptionalFeature.ps1 b/Examples/Sample_WindowsOptionalFeature.ps1 index f2895d4..151ba55 100644 --- a/Examples/Sample_WindowsOptionalFeature.ps1 +++ b/Examples/Sample_WindowsOptionalFeature.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Enables the Windows optional feature with the specified name and outputs a log to the specified path. diff --git a/Examples/Sample_WindowsOptionalFeatureSet_Disable.ps1 b/Examples/Sample_WindowsOptionalFeatureSet_Disable.ps1 index 25f6f7b..ea8eb61 100644 --- a/Examples/Sample_WindowsOptionalFeatureSet_Disable.ps1 +++ b/Examples/Sample_WindowsOptionalFeatureSet_Disable.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Disables the Windows optional features TelnetClient and LegacyComponents and removes all files associated with these features. diff --git a/Examples/Sample_WindowsOptionalFeatureSet_Enable.ps1 b/Examples/Sample_WindowsOptionalFeatureSet_Enable.ps1 index 13a84c6..16fb179 100644 --- a/Examples/Sample_WindowsOptionalFeatureSet_Enable.ps1 +++ b/Examples/Sample_WindowsOptionalFeatureSet_Enable.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Enables the Windows optional features MicrosoftWindowsPowerShellV2 and Internet-Explorer-Optional-amd64 and outputs a log of the operations to a file at the path diff --git a/Examples/Sample_WindowsPackageCab.ps1 b/Examples/Sample_WindowsPackageCab.ps1 index 49af41f..656a4bf 100644 --- a/Examples/Sample_WindowsPackageCab.ps1 +++ b/Examples/Sample_WindowsPackageCab.ps1 @@ -1,4 +1,4 @@ -<# +<# .SYNOPSIS Installs a package from the cab file with the specified name from the specified source path and outputs a log to the specified log path. diff --git a/PSDscResources.psd1 b/PSDscResources.psd1 index 5159c5f..8a662ab 100644 --- a/PSDscResources.psd1 +++ b/PSDscResources.psd1 @@ -4,7 +4,7 @@ # RootModule = '' # Version number of this module. -moduleVersion = '2.11.0.0' +moduleVersion = '2.12.0.0' # Supported PSEditions # CompatiblePSEditions = @() @@ -101,7 +101,33 @@ PrivateData = @{ # IconUri = '' # ReleaseNotes of this module - ReleaseNotes = '* Fix Custom DSC Resource Kit PSSA Rule Failures + ReleaseNotes = '* Ports style fixes that were recently made in xPSDesiredStateConfiguration + on test related files. +* Ports most of the style upgrades from xPSDesiredStateConfiguration that have + been made in files in the DscResources folder. +* Ports fixes for the following issues: + [Issue 505](https://github.com/PowerShell/xPSDesiredStateConfiguration/issues/505) + [Issue 590](https://github.com/PowerShell/xPSDesiredStateConfiguration/issues/590) + Changes to test helper Enter-DscResourceTestEnvironment so that it only + updates DSCResource.Tests when it is longer than 120 minutes since + it was last pulled. This is to improve performance of test execution + and reduce the likelihood of connectivity issues caused by inability to + pull DSCResource.Tests. +* Fixes issue where MsiPackage Integration tests fail if the test HttpListener + fails to start. Moves the test HttpListener objects to dynamically assigned, + higher numbered ports to avoid conflicts with other services, and also checks + to ensure that the ports are available before using them. Adds checks to + ensure that no outstanding HTTP server jobs are running before attempting to + setup a new one. Also adds additional instrumentation to make it easier to + troubleshoot issues with the test HttpListener objects in the future. + Specifically fixes + [Issue 142](https://github.com/PowerShell/PSDscResources/issues/142) +* Improved speed of Test-IsNanoServer function +* Remove the Byte Order Mark (BOM) from all affected files +* Opt-in to "Validate Module Files" and "Validate Script Files" common meta-tests +* Opt-in to "Common Tests - Relative Path Length" common meta-test +* Fix README markdownlint validation failures +* Move change log from README.md to CHANGELOG.md ' @@ -127,3 +153,4 @@ PrivateData = @{ + diff --git a/README.md b/README.md index 3be6947..d6360a3 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,3 @@ -master: [![Build status](https://ci.appveyor.com/api/projects/status/9uf3wyys7ky7776d/branch/master?svg=true)](https://ci.appveyor.com/project/PowerShell/psdscresources/branch/master) -[![codecov](https://codecov.io/gh/PowerShell/PSDscResources/branch/master/graph/badge.svg)](https://codecov.io/gh/PowerShell/PSDscResources) - -dev: [![Build status](https://ci.appveyor.com/api/projects/status/9uf3wyys7ky7776d/branch/dev?svg=true)](https://ci.appveyor.com/project/PowerShell/psdscresources/branch/dev) -[![codecov](https://codecov.io/gh/PowerShell/PSDscResources/branch/dev/graph/badge.svg)](https://codecov.io/gh/PowerShell/PSDscResources) - # PSDscResources PSDscResources is the new home of the in-box resources from PSDesiredStateConfiguration. @@ -17,11 +11,13 @@ Because PSDscResources overwrites in-box resources, it is only available for WMF Many of the resource updates provided here are also included in the [xPSDesiredStateConfiguration](https://github.com/PowerShell/xPSDesiredStateConfiguration) module which is still compatible with WMF 4 and WMF 5 (though this module is not supported and may be removed in the future). To update your in-box resources to the newest versions provided by PSDscResources, first install PSDscResources from the PowerShell Gallery: + ```powershell Install-Module PSDscResources ``` Then, simply add this line to your DSC configuration: + ```powershell Import-DscResource -ModuleName PSDscResources ``` @@ -29,12 +25,36 @@ Import-DscResource -ModuleName PSDscResources This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. +## Branches + +### master + +[![Build status](https://ci.appveyor.com/api/projects/status/9uf3wyys7ky7776d/branch/master?svg=true)](https://ci.appveyor.com/project/PowerShell/psdscresources/branch/master) +[![codecov](https://codecov.io/gh/PowerShell/PSDscResources/branch/master/graph/badge.svg)](https://codecov.io/gh/PowerShell/PSDscResources) + +This is the branch containing the latest release - +no contributions should be made directly to this branch. + +### dev + +[![Build status](https://ci.appveyor.com/api/projects/status/9nsi30ladk1jaax5/branch/master?svg=true)](https://ci.appveyor.com/project/PowerShell/AuditPolicyDsc/branch/dev) +[![codecov](https://codecov.io/gh/PowerShell/AuditPolicyDsc/branch/dev/graph/badge.svg)](https://codecov.io/gh/PowerShell/AuditPolicyDsc/branch/dev) + +This is the development branch +to which contributions should be proposed by contributors as pull requests. +This development branch will periodically be merged to the master branch, +and be released to [PowerShell Gallery](https://www.powershellgallery.com/). + ## Contributing This module does not accept breaking changes. Please check out the common DSC Resources [contributing guidelines](https://github.com/PowerShell/DscResource.Kit/blob/master/CONTRIBUTING.md). +## Change log + +A full list of changes in each version can be found in the [change log](CHANGELOG.md). + ## Resources * [Archive](#archive): Provides a mechanism to expand an archive (.zip) file to a specific path or remove an expanded archive (.zip) file from a specific path on a target node. @@ -572,137 +592,3 @@ The following parameters will be the same for each process in the set: * [Start multiple processes](https://github.com/PowerShell/PSDesResources/blob/master/Examples/Sample_ProcessSet_Start.ps1) * [Stop multiple processes](https://github.com/PowerShell/PSDesResources/blob/master/Examples/Sample_ProcessSet_Stop.ps1) - -## Versions - -### Unreleased - -### 2.11.0.0 - -* Fix Custom DSC Resource Kit PSSA Rule Failures - -### 2.10.0.0 - -* Fixed CompanyName typo - Fixes [Issue #100](https://github.com/PowerShell/PSDscResources/issues/100) -* Update LICENSE file to match the Microsoft Open Source Team - standard - Fixes [Issue #120](https://github.com/PowerShell/PSDscResources/issues/120). -* Update `CommonResourceHelper` unit tests to meet Pester 4.0.0 - standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). -* Update `ResourceHelper` unit tests to meet Pester 4.0.0 - standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). -* Ported fixes from [xPSDesiredStateConfiguration](https://github.com/PowerShell/xPSDesiredStateConfiguration): - * xArchive - * Fix end-to-end tests. - * Update integration tests to meet Pester 4.0.0 standards. - * Update end-to-end tests to meet Pester 4.0.0 standards. - * Update unit and integration tests to meet Pester 4.0.0 standards. - * Wrapped all path and identifier strings in verbose messages with - quotes to make it easier to identify the limit of the string when - debugging. - * Refactored date/time checksum code to improve testability and ensure - tests can run on machines with localized datetime formats that are not - US. - * Fix 'Get-ArchiveEntryLastWriteTime' to return `[datetime]`. - * Improved verbose logging to make debugging path issues easier. -* Added .gitattributes file to ensure CRLF settings are configured correctly - for the repository. -* Updated '.vscode\settings.json' to refer to AnalyzerSettings.psd1 so that - custom syntax problems are highlighted in Visual Studio Code. -* Fixed style guideline violations in `CommonResourceHelper.psm1`. -* Updated 'appveyor.yml' to meet more recent standards. -* Removed OS image version from 'appveyor.yml' to use default image - ([Issue #127](https://github.com/PowerShell/PSDscResources/issues/127)). -* Removed code to install WMF5.1 from 'appveyor.yml' because it is already - installed in AppVeyor images ([Issue #128](https://github.com/PowerShell/PSDscResources/issues/128)). -* Removed .vscode from .gitignore so that Visual Studio code environment - settings can be committed. -* Environment - * Update tests to meet Pester 4.0.0 standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). -* Group - * Update tests to meet Pester 4.0.0 standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). - * Fix unit tests to run on Nano Server. - * Refactored unit tests to enclude Context fixtures and change functions - to Describe fixtures. -* GroupSet - * Update tests to meet Pester 4.0.0 standards ([issue #129](https://github.com/PowerShell/PSDscResources/issues/129)). - -### 2.9.0.0 - -* Added Description and Parameter description for composite resources - -### 2.8.0.0 - -* Archive - * Added handling of directory archive entries that end with a foward slash - * Removed formatting of LastWriteTime timestamp and updated comparison of timestamps to handle dates in different formats -* WindowsProcess - * Fix unreliable tests -* Updated Test-IsNanoServer to return false if Get-ComputerInfo fails -* Registry - * Fixed bug when using the full registry drive name (e.g. HKEY\_LOCAL\_MACHINE) and using a key name that includes a drive with forward slashes (e.g. C:/) - -### 2.7.0.0 - -* MsiPackage - * Parse installation date from registry using invariant culture. - * Fix a bug in unit test failing, when regional setting differs from English-US. - -### 2.6.0.0 - -* Archive - * Fixed a minor bug in the unit tests where sometimes the incorrect DateTime format was used. -* Added MsiPackage - -### 2.5.0.0 - -* Enable codecov.io code coverage reporting -* Group - * Added support for domain based group members on Nano server. -* Added the Archive resource -* Update Test-IsNanoServer cmdlet to properly test for a Nano server rather than the core version of PowerShell -* Registry - * Fixed bug where an error was thrown when running Get-DscConfiguration if the registry already existed - -### 2.4.0.0 - -* Cleaned User -* Updated User to have non-dependent unit tests. -* Ported fixes from [xPSDesiredStateConfiguration](https://github.com/PowerShell/xPSDesiredStateConfiguration): - * WindowsProcess: Minor updates to integration tests - * Registry: Fixed support for forward slashes in registry key names -* Group: - * Group members in the "NT Authority", "BuiltIn" and "NT Service" scopes should now be resolved without an error. If you were seeing the errors "Exception calling ".ctor" with "4" argument(s): "Server names cannot contain a space character."" or "Exception calling ".ctor" with "2" argument(s): "Server names cannot contain a space character."", this fix should resolve those errors. If you are still seeing one of the errors, there is probably another local scope we need to add. Please let us know. - * The resource will no longer attempt to resolve group members if Members, MembersToInclude, and MembersToExclude are not specified. -* Added Environment - -### 2.3.0.0 - -* Updated manifest to include both WindowsOptionalFeature and WindowsOptionalFeatureSet instead of just WindowsOptionalFeature twice - -### 2.2.0.0 - -* WindowsFeature: - * Added Catch to ignore RuntimeException when importing ServerManager module. This solves the issue described [here](https://social.technet.microsoft.com/Forums/en-US/9fc314e1-27bf-4f03-ab78-5e0f7a662b8f/importmodule-servermanager-some-or-all-identity-references-could-not-be-translated?forum=winserverpowershell). - * Updated unit tests. -* Added WindowsProcess -* CommonTestHelper: - * Added Get-AppVeyorAdministratorCredential. - * Added Set-StrictMode -'Latest' and $errorActionPreference -'Stop'. -* Service: - * Updated resource module, unit tests, integration tests, and examples to reflect the changes made in xPSDesiredStateConfiguration. -* Group: - * Updated resource module, examples, and integration tests to reflect the changes made in xPSDesiredStateConfiguration. -* Added Script. -* Added GroupSet, ServiceSet, WindowsFeatureSet, WindowsOptionalFeatureSet, and ProcessSet. -* Added Set-StrictMode -'Latest' and $errorActionPreference -'Stop' to Group, Service, User, WindowsFeature, WindowsOptionalFeature, WindowsPackageCab. -* Fixed bug in WindowsFeature in which is was checking the 'Count' property of an object that was not always an array. -* Cleaned Group and Service resources and tests. -* Added Registry. - -### 2.1.0.0 - -* Added WindowsFeature. - -### 2.0.0.0 - -* Initial release of PSDscResources. diff --git a/Tests/Integration/GroupSet.Integration.Tests.ps1 b/Tests/Integration/GroupSet.Integration.Tests.ps1 index 4315647..7929bad 100644 --- a/Tests/Integration/GroupSet.Integration.Tests.ps1 +++ b/Tests/Integration/GroupSet.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] param () if ($PSVersionTable.PSVersion -lt [Version] '5.1') @@ -65,8 +65,8 @@ try Ensure = 'Present' } - Test-GroupExists -GroupName $testGroupName1 | Should -Be $false - Test-GroupExists -GroupName $testGroupName2 | Should -Be $false + Test-GroupExists -GroupName $testGroupName1 | Should -BeFalse + Test-GroupExists -GroupName $testGroupName2 | Should -BeFalse try { @@ -76,8 +76,8 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName1 -Members @() | Should -Be $true - Test-GroupExists -GroupName $testGroupName2 -Members @() | Should -Be $true + Test-GroupExists -GroupName $testGroupName1 -Members @() | Should -BeTrue + Test-GroupExists -GroupName $testGroupName2 -Members @() | Should -BeTrue } finally { @@ -105,7 +105,7 @@ try MembersToInclude = $groupMembers } - Test-GroupExists -GroupName $testGroupName1 | Should -Be $false + Test-GroupExists -GroupName $testGroupName1 | Should -BeFalse try { @@ -115,7 +115,7 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName1 -MembersToInclude $groupMembers | Should -Be $true + Test-GroupExists -GroupName $testGroupName1 -MembersToInclude $groupMembers | Should -BeTrue } finally { @@ -140,8 +140,8 @@ try MembersToInclude = $groupMembers } - Test-GroupExists -GroupName $testGroupName | Should -Be $false - Test-GroupExists -GroupName $administratorsGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeFalse + Test-GroupExists -GroupName $administratorsGroupName | Should -BeTrue try { @@ -151,8 +151,8 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName -MembersToInclude $groupMembers | Should -Be $true - Test-GroupExists -GroupName $administratorsGroupName -MembersToInclude $groupMembers | Should -Be $true + Test-GroupExists -GroupName $testGroupName -MembersToInclude $groupMembers | Should -BeTrue + Test-GroupExists -GroupName $administratorsGroupName -MembersToInclude $groupMembers | Should -BeTrue } finally { @@ -178,11 +178,11 @@ try foreach ($testGroupName in $testGroupNames) { - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse New-Group -GroupName $testGroupName -Members $testUsernames - Test-GroupExists -GroupName $testGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeTrue } try @@ -195,7 +195,7 @@ try foreach ($testGroupName in $testGroupNames) { - Test-GroupExists -GroupName $testGroupName -MembersToExclude $groupMembersToExclude | Should -Be $true + Test-GroupExists -GroupName $testGroupName -MembersToExclude $groupMembersToExclude | Should -BeTrue } } finally @@ -222,11 +222,11 @@ try foreach ($testGroupName in $testGroupNames) { - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse New-Group -GroupName $testGroupName - Test-GroupExists -GroupName $testGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeTrue } try @@ -239,7 +239,7 @@ try foreach ($testGroupName in $testGroupNames) { - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse } } finally diff --git a/Tests/Integration/GroupSet.config.ps1 b/Tests/Integration/GroupSet.config.ps1 index 965f469..4b8f6ce 100644 --- a/Tests/Integration/GroupSet.config.ps1 +++ b/Tests/Integration/GroupSet.config.ps1 @@ -1,4 +1,4 @@ -param +param ( [Parameter(Mandatory = $true)] [System.String] diff --git a/Tests/Integration/MSFT_Archive.EndToEnd.Tests.ps1 b/Tests/Integration/MSFT_Archive.EndToEnd.Tests.ps1 index 674c8e4..c413b65 100644 --- a/Tests/Integration/MSFT_Archive.EndToEnd.Tests.ps1 +++ b/Tests/Integration/MSFT_Archive.EndToEnd.Tests.ps1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' if ($PSVersionTable.PSVersion -lt [Version] '5.1') @@ -140,7 +140,7 @@ Describe 'Archive End to End Tests' { $destination = Join-Path -Path $TestDrive -ChildPath 'NonExistentDestinationForExpand' It 'Destination should not exist before configuration' { - Test-Path -Path $destination | Should -Be $false + Test-Path -Path $destination | Should -BeFalse } $archiveParameters = @{ @@ -151,7 +151,7 @@ Describe 'Archive End to End Tests' { } It 'Should return false from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $false + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeFalse } It 'Should compile and apply the MOF without throwing an exception' { @@ -163,15 +163,15 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -199,25 +199,25 @@ Describe 'Archive End to End Tests' { $otherItems[$otherFilePath] = $otherFileContent It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } foreach ($otherItemPath in $otherItems.Keys) { $otherItemName = Split-Path -Path $otherItemPath -Leaf $otherItemExpectedContent = $otherItems[$otherItemPath] - $otherItemIsDirectory = [String]::IsNullOrEmpty($otherItemExpectedContent) + $otherItemIsDirectory = [System.String]::IsNullOrEmpty($otherItemExpectedContent) if ($otherItemIsDirectory) { It "Other item under destination $otherItemName should exist as a directory before configuration" { - Test-Path -Path $otherItemPath -PathType 'Container' | Should -Be $true + Test-Path -Path $otherItemPath -PathType 'Container' | Should -BeTrue } } else { It "Other item under destination $otherItemName should exist as a file before configuration" { - Test-Path -Path $otherItemPath -PathType 'Leaf' | Should -Be $true + Test-Path -Path $otherItemPath -PathType 'Leaf' | Should -BeTrue } It "Other file under destination $otherItemName should have the expected content before configuration" { @@ -234,7 +234,7 @@ Describe 'Archive End to End Tests' { } It 'Should return false from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $false + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeFalse } It 'Should compile and apply the MOF without throwing an exception' { @@ -246,29 +246,29 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } foreach ($otherItemPath in $otherItems.Keys) { $otherItemName = Split-Path -Path $otherItemPath -Leaf $otherItemExpectedContent = $otherItems[$otherItemPath] - $otherItemIsDirectory = [String]::IsNullOrEmpty($otherItemExpectedContent) + $otherItemIsDirectory = [System.String]::IsNullOrEmpty($otherItemExpectedContent) if ($otherItemIsDirectory) { It "Other item under destination $otherItemName should exist as a directory after configuration" { - Test-Path -Path $otherItemPath -PathType 'Container' | Should -Be $true + Test-Path -Path $otherItemPath -PathType 'Container' | Should -BeTrue } } else { It "Other item under destination $otherItemName should exist as a file after configuration" { - Test-Path -Path $otherItemPath -PathType 'Leaf' | Should -Be $true + Test-Path -Path $otherItemPath -PathType 'Leaf' | Should -BeTrue } It "Other file under destination $otherItemName should have the expected after before configuration" { @@ -278,7 +278,7 @@ Describe 'Archive End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -291,11 +291,11 @@ Describe 'Archive End to End Tests' { $null = Expand-Archive -Path $script:testArchiveFilePath -DestinationPath $destination -Force It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } $archiveParameters = @{ @@ -306,7 +306,7 @@ Describe 'Archive End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } It 'Should compile and apply the MOF without throwing an exception' { @@ -318,15 +318,15 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -339,15 +339,15 @@ Describe 'Archive End to End Tests' { $null = Expand-Archive -Path $script:testArchiveFileWithDifferentFileContentPath -DestinationPath $destination -Force It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'File contents of destination should not match the file contents of the archive' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeFalse } $archiveParameters = @{ @@ -361,7 +361,7 @@ Describe 'Archive End to End Tests' { } It 'Should return false from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $false + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeFalse } It 'Should compile and run configuration and throw an error for attempting to overwrite files without Force specified' { @@ -374,19 +374,19 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'File contents of destination should not match the file contents of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeFalse } It 'Should return false from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $false + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeFalse } } @@ -399,15 +399,15 @@ Describe 'Archive End to End Tests' { $null = Expand-Archive -Path $script:testArchiveFileWithDifferentFileContentPath -DestinationPath $destination -Force It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'File contents of destination should not match the file contents of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeFalse } $archiveParameters = @{ @@ -421,7 +421,7 @@ Describe 'Archive End to End Tests' { } It 'Should return false from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $false + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeFalse } It 'Should compile and apply the MOF without throwing an exception' { @@ -433,19 +433,19 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'File contents of destination should match the file contents of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeTrue } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -458,15 +458,15 @@ Describe 'Archive End to End Tests' { $null = Expand-Archive -Path $script:testArchiveFilePath -DestinationPath $destination -Force It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'File contents of destination should match the file contents of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeTrue } $archiveParameters = @{ @@ -480,7 +480,7 @@ Describe 'Archive End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } It 'Should compile and apply the MOF without throwing an exception' { @@ -492,19 +492,19 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'File contents of destination should match the file contents of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeTrue } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -517,11 +517,11 @@ Describe 'Archive End to End Tests' { $null = Expand-Archive -Path $script:testArchiveFilePath -DestinationPath $destination -Force It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } $archiveParameters = @{ @@ -532,7 +532,7 @@ Describe 'Archive End to End Tests' { } It 'Should return false from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $false + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeFalse } It 'Should compile and apply the MOF without throwing an exception' { @@ -544,15 +544,15 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should not match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeFalse } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -582,25 +582,25 @@ Describe 'Archive End to End Tests' { $otherItems[$otherFilePath] = $otherFileContent It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } foreach ($otherItemPath in $otherItems.Keys) { $otherItemName = Split-Path -Path $otherItemPath -Leaf $otherItemExpectedContent = $otherItems[$otherItemPath] - $otherItemIsDirectory = [String]::IsNullOrEmpty($otherItemExpectedContent) + $otherItemIsDirectory = [System.String]::IsNullOrEmpty($otherItemExpectedContent) if ($otherItemIsDirectory) { It "Other item under destination $otherItemName should exist as a directory before configuration" { - Test-Path -Path $otherItemPath -PathType 'Container' | Should -Be $true + Test-Path -Path $otherItemPath -PathType 'Container' | Should -BeTrue } } else { It "Other item under destination $otherItemName should exist as a file before configuration" { - Test-Path -Path $otherItemPath -PathType 'Leaf' | Should -Be $true + Test-Path -Path $otherItemPath -PathType 'Leaf' | Should -BeTrue } It "Other file under destination $otherItemName should have the expected content before configuration" { @@ -610,7 +610,7 @@ Describe 'Archive End to End Tests' { } It 'File structure of destination should match the file structure of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } $archiveParameters = @{ @@ -621,7 +621,7 @@ Describe 'Archive End to End Tests' { } It 'Should return false from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $false + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeFalse } It 'Should compile and apply the MOF without throwing an exception' { @@ -633,25 +633,25 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } foreach ($otherItemPath in $otherItems.Keys) { $otherItemName = Split-Path -Path $otherItemPath -Leaf $otherItemExpectedContent = $otherItems[$otherItemPath] - $otherItemIsDirectory = [String]::IsNullOrEmpty($otherItemExpectedContent) + $otherItemIsDirectory = [System.String]::IsNullOrEmpty($otherItemExpectedContent) if ($otherItemIsDirectory) { It "Other item under destination $otherItemName should exist as a directory before configuration" { - Test-Path -Path $otherItemPath -PathType 'Container' | Should -Be $true + Test-Path -Path $otherItemPath -PathType 'Container' | Should -BeTrue } } else { It "Other item under destination $otherItemName should exist as a file before configuration" { - Test-Path -Path $otherItemPath -PathType 'Leaf' | Should -Be $true + Test-Path -Path $otherItemPath -PathType 'Leaf' | Should -BeTrue } It "Other file under destination $otherItemName should have the expected content before configuration" { @@ -661,11 +661,11 @@ Describe 'Archive End to End Tests' { } It 'File structure of destination should not match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeFalse } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -676,11 +676,11 @@ Describe 'Archive End to End Tests' { $null = New-Item -Path $destination -ItemType 'Directory' It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should not match the file structure of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeFalse } $archiveParameters = @{ @@ -691,7 +691,7 @@ Describe 'Archive End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } It 'Should compile and apply the MOF without throwing an exception' { @@ -703,15 +703,15 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should not match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeFalse } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -721,7 +721,7 @@ Describe 'Archive End to End Tests' { $destination = Join-Path -Path $TestDrive -ChildPath 'NonexistentDestinationForRemove' It 'Destination should not exist before configuration' { - Test-Path -Path $destination | Should -Be $false + Test-Path -Path $destination | Should -BeFalse } $archiveParameters = @{ @@ -732,7 +732,7 @@ Describe 'Archive End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } It 'Should compile and apply the MOF without throwing an exception' { @@ -744,11 +744,11 @@ Describe 'Archive End to End Tests' { } It 'Destination should not exist after configuration' { - Test-Path -Path $destination | Should -Be $false + Test-Path -Path $destination | Should -BeFalse } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -761,15 +761,15 @@ Describe 'Archive End to End Tests' { $null = Expand-Archive -Path $script:testArchiveFileWithDifferentFileContentPath -DestinationPath $destination -Force It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'File contents of destination should not match the file contents of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeFalse } $archiveParameters = @{ @@ -783,7 +783,7 @@ Describe 'Archive End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } It 'Should compile and apply the MOF without throwing an exception' { @@ -795,19 +795,19 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeTrue } It 'File contents of destination should not match the file contents of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeFalse } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } @@ -820,11 +820,11 @@ Describe 'Archive End to End Tests' { $null = Expand-Archive -Path $script:testArchiveFilePath -DestinationPath $destination -Force It 'Destination should exist before configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure and contents of destination should match the file contents of the archive before configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination -CheckContents | Should -BeTrue } $archiveParameters = @{ @@ -838,7 +838,7 @@ Describe 'Archive End to End Tests' { } It 'Should return false from Test-TargetResource with the same parameters before configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $false + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeFalse } It 'Should compile and apply the MOF without throwing an exception' { @@ -850,15 +850,15 @@ Describe 'Archive End to End Tests' { } It 'Destination should exist after configuration' { - Test-Path -Path $destination | Should -Be $true + Test-Path -Path $destination | Should -BeTrue } It 'File structure of destination should not match the file structure of the archive after configuration' { - Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -Be $false + Test-FileStructuresMatch -SourcePath $script:testArchiveFilePathWithoutExtension -DestinationPath $destination | Should -BeFalse } It 'Should return false from Test-TargetResource with the same parameters after configuration' { - MSFT_Archive\Test-TargetResource @archiveParameters | Should -Be $true + MSFT_Archive\Test-TargetResource @archiveParameters | Should -BeTrue } } } diff --git a/Tests/Integration/MSFT_Archive.Integration.Tests.ps1 b/Tests/Integration/MSFT_Archive.Integration.Tests.ps1 index d3562aa..2f64b18 100644 --- a/Tests/Integration/MSFT_Archive.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_Archive.Integration.Tests.ps1 @@ -46,15 +46,15 @@ Describe 'Archive Integration Tests' { $destinationDirectoryPath = Join-Path -Path $TestDrive -ChildPath $destinationDirectoryName It 'File structure and contents of the destination should not match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } It 'Test-TargetResource with Ensure as Present should return false before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } It 'Set-TargetResource should not throw' { @@ -62,15 +62,15 @@ Describe 'Archive Integration Tests' { } It 'File structure and contents of the destination should match the file structure and contents of the archive after Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeTrue } It 'Test-TargetResource with Ensure as Present should return true after Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false after Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } } @@ -93,15 +93,15 @@ Describe 'Archive Integration Tests' { $null = Expand-Archive -Path $zipFilePath -DestinationPath $destinationDirectoryPath -Force It 'File structure and contents of the destination should match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeTrue } It 'Test-TargetResource with Ensure as Present should return true before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } It 'Set-TargetResource should not throw' { @@ -109,15 +109,15 @@ Describe 'Archive Integration Tests' { } It 'File structure and contents of the destination should not match the file structure and contents of the archive after Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } It 'Test-TargetResource with Ensure as Present should return false after Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true after Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } } @@ -164,15 +164,15 @@ Describe 'Archive Integration Tests' { $destinationDirectoryPath = Join-Path -Path $TestDrive -ChildPath $destinationDirectoryName It 'File structure and contents of the destination should not match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } It 'Test-TargetResource with Ensure as Present should return false before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } It 'Set-TargetResource should not throw' { @@ -180,15 +180,15 @@ Describe 'Archive Integration Tests' { } It 'File structure and contents of the destination should match the file structure and contents of the archive after Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeTrue } It 'Test-TargetResource with Ensure as Present should return true after Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false after Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } } @@ -237,15 +237,15 @@ Describe 'Archive Integration Tests' { $null = Expand-Archive -Path $zipFilePath -DestinationPath $destinationDirectoryPath -Force It 'File structure and contents of the destination should match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeTrue } It 'Test-TargetResource with Ensure as Present should return true before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } It 'Set-TargetResource should not throw' { @@ -253,15 +253,15 @@ Describe 'Archive Integration Tests' { } It 'File structure and contents of the destination should not match the file structure and contents of the archive after Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } It 'Test-TargetResource with Ensure as Present should return false after Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true after Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } } @@ -295,23 +295,23 @@ Describe 'Archive Integration Tests' { $destinationDirectoryPath = Join-Path -Path $TestDrive -ChildPath $destinationDirectoryName It 'File structure and contents of the destination should not match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath1 -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath1 -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } It 'Test-TargetResource with Ensure as Present should return false for specified archive before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath1 -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath1 -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true for specified archive before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath1 -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath1 -Destination $destinationDirectoryPath | Should -BeTrue } It 'Test-TargetResource with Ensure as Present should return false for other archive with same timestamp with before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath2 -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath2 -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true for other archive with same timestamp before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath2 -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath2 -Destination $destinationDirectoryPath | Should -BeTrue } It 'Set-TargetResource should not throw' { @@ -319,23 +319,23 @@ Describe 'Archive Integration Tests' { } It 'File structure and contents of the destination should match the file structure and contents of the archive after Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath1 -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $zipFileSourcePath1 -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeTrue } It 'Test-TargetResource with Ensure as Present should return true for specified archive after Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath1 -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath1 -Destination $destinationDirectoryPath | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false for specified archive after Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath1 -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath1 -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Present should return false for other archive with same timestamp with before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath2 -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath2 -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true for other archive with same timestamp before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath2 -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath2 -Destination $destinationDirectoryPath | Should -BeTrue } } @@ -371,19 +371,19 @@ Describe 'Archive Integration Tests' { $null = Set-Content -Path $newFilePath -Value 'Fake text' It 'File structure and contents of the destination should match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeTrue } It 'Test-TargetResource with Ensure as Present should return true before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } It 'Extra file should be present before Set-TargetResource' { - Test-Path -Path $newFilePath | Should -Be $true + Test-Path -Path $newFilePath | Should -BeTrue } It 'Set-TargetResource should not throw' { @@ -391,19 +391,19 @@ Describe 'Archive Integration Tests' { } It 'File structure and contents of the destination should not match the file structure and contents of the archive after Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } It 'Test-TargetResource with Ensure as Present should return false after Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true after Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath | Should -BeTrue } It 'Extra file should be present after Set-TargetResource' { - Test-Path -Path $newFilePath | Should -Be $true + Test-Path -Path $newFilePath | Should -BeTrue } } @@ -454,26 +454,25 @@ Describe 'Archive Integration Tests' { } It 'Test-TargetResource with Ensure as Present should return true before file edit' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false before file edit' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeFalse } $fileToEditPath = Join-Path -Path $destinationDirectoryPath -ChildPath $fileToEditName It 'File to edit should exist at the destination before Set-TargetResource' { - Test-Path -Path $fileToEditPath | Should -Be $true + Test-Path -Path $fileToEditPath | Should -BeTrue } $fileBeforeEdit = Get-Item -Path $fileToEditPath $lastWriteTimeBeforeEdit = $fileBeforeEdit.LastWriteTime - $creationTimeBeforeEdit = $fileBeforeEdit.CreationTime $null = Set-Content -Path $fileToEditPath -Value 'Different false text' -Force - Set-ItemProperty -Path $fileToEditPath -Name 'LastWriteTime' -Value ([DateTime]::MaxValue) - Set-ItemProperty -Path $fileToEditPath -Name 'CreationTime' -Value ([DateTime]::MaxValue) + Set-ItemProperty -Path $fileToEditPath -Name 'LastWriteTime' -Value ([System.DateTime]::MaxValue) + Set-ItemProperty -Path $fileToEditPath -Name 'CreationTime' -Value ([System.DateTime]::MaxValue) $fileAfterEdit = Get-Item -Path $fileToEditPath @@ -490,15 +489,15 @@ Describe 'Archive Integration Tests' { } It 'Test-TargetResource with Ensure as Present should return false before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeTrue } It 'File structure and contents of the destination should not match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } It 'Set-TargetResource should not throw' { @@ -508,7 +507,7 @@ Describe 'Archive Integration Tests' { $fileAfterSetTargetResource = Get-Item -Path $fileToEditPath It 'Edited file should exist at the destination after Set-TargetResource' { - Test-Path -Path $fileToEditPath | Should -Be $true + Test-Path -Path $fileToEditPath | Should -BeTrue } It 'Edited file at the destination should have the same content as the same file in the archive after Set-TargetResource' { @@ -524,15 +523,15 @@ Describe 'Archive Integration Tests' { } It 'Test-TargetResource with Ensure as Present should return true after Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false after Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeFalse } It 'File structure and contents of the destination should match the file structure and contents of the archive after Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $true + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeTrue } } @@ -567,26 +566,25 @@ Describe 'Archive Integration Tests' { } It 'Test-TargetResource with Ensure as Present should return true before file edit' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false before file edit' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeFalse } $fileToEditPath = Join-Path -Path $destinationDirectoryPath -ChildPath $fileToEditName It 'File to edit should exist at the destination before Set-TargetResource' { - Test-Path -Path $fileToEditPath | Should -Be $true + Test-Path -Path $fileToEditPath | Should -BeTrue } $fileBeforeEdit = Get-Item -Path $fileToEditPath $lastWriteTimeBeforeEdit = $fileBeforeEdit.LastWriteTime - $creationTimeBeforeEdit = $fileBeforeEdit.CreationTime $null = Set-Content -Path $fileToEditPath -Value 'Different false text' -Force - Set-ItemProperty -Path $fileToEditPath -Name 'LastWriteTime' -Value ([DateTime]::MaxValue) - Set-ItemProperty -Path $fileToEditPath -Name 'CreationTime' -Value ([DateTime]::MaxValue) + Set-ItemProperty -Path $fileToEditPath -Name 'LastWriteTime' -Value ([System.DateTime]::MaxValue) + Set-ItemProperty -Path $fileToEditPath -Name 'CreationTime' -Value ([System.DateTime]::MaxValue) $fileAfterEdit = Get-Item -Path $fileToEditPath @@ -603,15 +601,15 @@ Describe 'Archive Integration Tests' { } It 'Test-TargetResource with Ensure as Present should return false before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeTrue } It 'File structure and contents of the destination should not match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } { Set-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue } | Should -Throw @@ -648,26 +646,25 @@ Describe 'Archive Integration Tests' { } It 'Test-TargetResource with Ensure as Present should return true before file edit' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $true + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeTrue } It 'Test-TargetResource with Ensure as Absent should return false before file edit' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $false + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeFalse } $fileToEditPath = Join-Path -Path $destinationDirectoryPath -ChildPath $fileToEditName It 'File to edit should exist at the destination before Set-TargetResource' { - Test-Path -Path $fileToEditPath | Should -Be $true + Test-Path -Path $fileToEditPath | Should -BeTrue } $fileBeforeEdit = Get-Item -Path $fileToEditPath $lastWriteTimeBeforeEdit = $fileBeforeEdit.LastWriteTime - $creationTimeBeforeEdit = $fileBeforeEdit.CreationTime $null = Set-Content -Path $fileToEditPath -Value 'Different false text' -Force - Set-ItemProperty -Path $fileToEditPath -Name 'LastWriteTime' -Value ([DateTime]::MaxValue) - Set-ItemProperty -Path $fileToEditPath -Name 'CreationTime' -Value ([DateTime]::MaxValue) + Set-ItemProperty -Path $fileToEditPath -Name 'LastWriteTime' -Value ([System.DateTime]::MaxValue) + Set-ItemProperty -Path $fileToEditPath -Name 'CreationTime' -Value ([System.DateTime]::MaxValue) $fileAfterEdit = Get-Item -Path $fileToEditPath @@ -684,25 +681,23 @@ Describe 'Archive Integration Tests' { } It 'Test-TargetResource with Ensure as Present should return false before Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true before Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeTrue } It 'File structure and contents of the destination should not match the file structure and contents of the archive before Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } It 'Set-TargetResource should not throw' { { Set-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue } | Should -Not -Throw } - $fileAfterSetTargetResource = Get-Item -Path $fileToEditPath - It 'Edited file should exist at the destination after Set-TargetResource' { - Test-Path -Path $fileToEditPath | Should -Be $true + Test-Path -Path $fileToEditPath | Should -BeTrue } It 'Edited file at the destination should have the edited content' { @@ -718,15 +713,15 @@ Describe 'Archive Integration Tests' { } It 'Test-TargetResource with Ensure as Present should return false after Set-TargetResource' { - Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $false + Test-TargetResource -Ensure 'Present' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeFalse } It 'Test-TargetResource with Ensure as Absent should return true after Set-TargetResource' { - Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -Be $true + Test-TargetResource -Ensure 'Absent' -Path $zipFilePath -Destination $destinationDirectoryPath -Validate $true -Checksum $possibleChecksumValue | Should -BeTrue } It 'File structure and contents of the destination should not match the file structure and contents of the archive after Set-TargetResource' { - Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -Be $false + Test-FileStructuresMatch -SourcePath $zipFileSourcePath -DestinationPath $destinationDirectoryPath -CheckContents | Should -BeFalse } } } diff --git a/Tests/Integration/MSFT_Archive_CredentialOnly.config.ps1 b/Tests/Integration/MSFT_Archive_CredentialOnly.config.ps1 index 8453105..51f4da1 100644 --- a/Tests/Integration/MSFT_Archive_CredentialOnly.config.ps1 +++ b/Tests/Integration/MSFT_Archive_CredentialOnly.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,17 +11,17 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] diff --git a/Tests/Integration/MSFT_Archive_ValidateAndChecksum.config.ps1 b/Tests/Integration/MSFT_Archive_ValidateAndChecksum.config.ps1 index d912417..e26074d 100644 --- a/Tests/Integration/MSFT_Archive_ValidateAndChecksum.config.ps1 +++ b/Tests/Integration/MSFT_Archive_ValidateAndChecksum.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,29 +11,29 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [Boolean] + [System.Boolean] $Validate = $false, [Parameter()] - [String] + [System.String] $Checksum = 'SHA-256', [Parameter()] - [Boolean] + [System.Boolean] $Force = $false ) diff --git a/Tests/Integration/MSFT_Archive_ValidateOnly.config.ps1 b/Tests/Integration/MSFT_Archive_ValidateOnly.config.ps1 index 6fb9566..7455c0e 100644 --- a/Tests/Integration/MSFT_Archive_ValidateOnly.config.ps1 +++ b/Tests/Integration/MSFT_Archive_ValidateOnly.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,21 +11,21 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Destination, [Parameter()] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter()] - [Boolean] + [System.Boolean] $Validate = $false ) diff --git a/Tests/Integration/MSFT_EnvironmentResource.EndToEnd.Tests.ps1 b/Tests/Integration/MSFT_EnvironmentResource.EndToEnd.Tests.ps1 index 3ef7aee..ca42500 100644 --- a/Tests/Integration/MSFT_EnvironmentResource.EndToEnd.Tests.ps1 +++ b/Tests/Integration/MSFT_EnvironmentResource.EndToEnd.Tests.ps1 @@ -1,4 +1,4 @@ -<# +<# Please note that some of these tests depend on each other. They must be run in the order given - if one test fails, subsequent tests may also fail. @@ -27,53 +27,53 @@ try { Describe 'EnvironmentResouce Integration Tests - with both Targets specified (default)' { BeforeAll { - $testEnvironmentVarName = 'TestEnvironmentVariableName' - $testPathEnvironmentVarName = 'TestPathEnvironmentVariableName' - $machineEnvironmentRegistryPath = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Environment' + $script:testEnvironmentVarName = 'TestEnvironmentVariableName' + $script:testPathEnvironmentVarName = 'TestPathEnvironmentVariableName' + $script:machineEnvironmentRegistryPath = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Environment' - $testValue = 'InitialTestValue' - $newTestValue = 'NewTestValue' + $script:testValue = 'InitialTestValue' + $script:newTestValue = 'NewTestValue' - $configFile = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_EnvironmentResource.config.ps1' + $script:configFile = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_EnvironmentResource.config.ps1' } AfterAll { # Remove variables from the process: - [System.Environment]::SetEnvironmentVariable($testEnvironmentVarName, $null) - [System.Environment]::SetEnvironmentVariable($testPathEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testPathEnvironmentVarName, $null) # Remove variables from machine: - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName } - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName } } - Context "Should create the environment variable $testEnvironmentVarName" { + Context "Should create the environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Create' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName # Ensure the environment variable doesn't exist # Remove variable from the process: - [System.Environment]::SetEnvironmentVariable($testEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testEnvironmentVarName, $null) # Remove variable from machine: - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName } It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Present' ` -OutputPath $configurationPath ` -ErrorAction 'Stop' @@ -87,21 +87,21 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $testValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:testValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should update environment variable $testEnvironmentVarName" { + Context "Should update environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Update' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` - -Value $newTestValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` + -Value $script:newTestValue ` -Ensure 'Present' ` -OutputPath $configurationPath ` -ErrorAction 'Stop' @@ -115,8 +115,8 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } @@ -127,8 +127,8 @@ try It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` -Value 'otherValue' ` -Ensure 'Absent' ` -OutputPath $configurationPath ` @@ -143,20 +143,20 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove environment variable $testEnvironmentVarName" { + Context "Should remove environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Remove' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` -Value $null ` -Ensure 'Absent' ` -OutputPath $configurationPath ` @@ -171,32 +171,32 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName + $currentConfig.Name | Should -Be $script:testEnvironmentVarName $currentConfig.Value | Should -Be $null $currentConfig.Ensure | Should -Be 'Absent' } } - Context "Should create the path environment variable $testPathEnvironmentVarName" { + Context "Should create the path environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Create_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName # Ensure the environment variable doesn't exist # Remove variable from the process: - [System.Environment]::SetEnvironmentVariable($testPathEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testPathEnvironmentVarName, $null) # Remove variable from machine: - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName } It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Present' ` -Path $true ` -OutputPath $configurationPath ` @@ -211,23 +211,23 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName - $currentConfig.Value | Should -Be $testValue + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName + $currentConfig.Value | Should -Be $script:testValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should update environment variable $testPathEnvironmentVarName" { + Context "Should update environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Update_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName - $expectedValue = $testValue + ';' + $newTestValue + $expectedValue = $script:testValue + ';' + $script:newTestValue It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $newTestValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:newTestValue ` -Ensure 'Present' ` -Path $true ` -OutputPath $configurationPath ` @@ -242,7 +242,7 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $expectedValue $currentConfig.Ensure | Should -Be 'Present' } @@ -252,12 +252,12 @@ try $configurationName = 'MSFT_EnvironmentResource_NonRemove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName - $expectedValue = $testValue + ';' + $newTestValue + $expectedValue = $script:testValue + ';' + $script:newTestValue It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` -Value 'otherValue' ` -Ensure 'Absent' ` -Path $true ` @@ -273,21 +273,21 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $expectedValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove only one value from environment variable $testPathEnvironmentVarName" { + Context "Should remove only one value from environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_PartialRemove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Absent' ` -Path $true ` -OutputPath $configurationPath ` @@ -302,20 +302,20 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove the environment variable $testPathEnvironmentVarName" { + Context "Should remove the environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Remove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` -Value $null ` -Ensure 'Absent' ` -Path $true ` @@ -331,7 +331,7 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $null $currentConfig.Ensure | Should -Be 'Absent' } @@ -340,45 +340,45 @@ try Describe 'EnvironmentResouce Integration Tests - only Process Target specified' { BeforeAll { - $testEnvironmentVarName = 'TestProcessEnvironmentVariableName' - $testPathEnvironmentVarName = 'TestProcessPathEnvironmentVariableName' + $script:testEnvironmentVarName = 'TestProcessEnvironmentVariableName' + $script:testPathEnvironmentVarName = 'TestProcessPathEnvironmentVariableName' - $testValue = 'InitialProcessTestValue' - $newTestValue = 'NewProcessTestValue' + $script:testValue = 'InitialProcessTestValue' + $script:newTestValue = 'NewProcessTestValue' - $configFile = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_EnvironmentResource.config.ps1' + $script:configFile = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_EnvironmentResource.config.ps1' } AfterAll { # Remove variables from the process: - [System.Environment]::SetEnvironmentVariable($testEnvironmentVarName, $null) - [System.Environment]::SetEnvironmentVariable($testPathEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testPathEnvironmentVarName, $null) # Remove variables from machine (these shouldn't have been set): - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName } - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName } } - Context "Should create the environment variable $testEnvironmentVarName" { + Context "Should create the environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Create' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName # Ensure the environment variable doesn't exist # Remove variable from the process: - [System.Environment]::SetEnvironmentVariable($testEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testEnvironmentVarName, $null) It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Present' ` -Target @('Process') ` -OutputPath $configurationPath ` @@ -393,21 +393,21 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $testValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:testValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should update environment variable $testEnvironmentVarName" { + Context "Should update environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Update' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` - -Value $newTestValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` + -Value $script:newTestValue ` -Ensure 'Present' ` -Target @('Process') ` -OutputPath $configurationPath ` @@ -422,8 +422,8 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } @@ -434,8 +434,8 @@ try It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` -Value 'otherValue' ` -Ensure 'Absent' ` -Target @('Process') ` @@ -451,20 +451,20 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove environment variable $testEnvironmentVarName" { + Context "Should remove environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Remove' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` -Value $null ` -Ensure 'Absent' ` -Target @('Process') ` @@ -480,26 +480,26 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName + $currentConfig.Name | Should -Be $script:testEnvironmentVarName $currentConfig.Value | Should -Be $null $currentConfig.Ensure | Should -Be 'Absent' } } - Context "Should create the path environment variable $testPathEnvironmentVarName" { + Context "Should create the path environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Create_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName # Ensure the environment variable doesn't exist # Remove variable from the process: - [System.Environment]::SetEnvironmentVariable($testPathEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testPathEnvironmentVarName, $null) It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Present' ` -Path $true ` -Target @('Process') ` @@ -515,23 +515,23 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName - $currentConfig.Value | Should -Be $testValue + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName + $currentConfig.Value | Should -Be $script:testValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should update environment variable $testPathEnvironmentVarName" { + Context "Should update environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Update_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName - $expectedValue = $testValue + ';' + $newTestValue + $expectedValue = $script:testValue + ';' + $script:newTestValue It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $newTestValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:newTestValue ` -Ensure 'Present' ` -Path $true ` -Target @('Process') ` @@ -547,7 +547,7 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $expectedValue $currentConfig.Ensure | Should -Be 'Present' } @@ -557,12 +557,12 @@ try $configurationName = 'MSFT_EnvironmentResource_NonRemove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName - $expectedValue = $testValue + ';' + $newTestValue + $expectedValue = $script:testValue + ';' + $script:newTestValue It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` -Value 'otherValue' ` -Ensure 'Absent' ` -Path $true ` @@ -579,21 +579,21 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $expectedValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove only one value from environment variable $testPathEnvironmentVarName" { + Context "Should remove only one value from environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_PartialRemove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Absent' ` -Path $true ` -Target @('Process') ` @@ -609,20 +609,20 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove the environment variable $testPathEnvironmentVarName" { + Context "Should remove the environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Remove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` -Value $null ` -Ensure 'Absent' ` -Path $true ` @@ -639,7 +639,7 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $null $currentConfig.Ensure | Should -Be 'Absent' } @@ -648,48 +648,48 @@ try Describe 'EnvironmentResouce Integration Tests - only Machine Target specified' { BeforeAll { - $testEnvironmentVarName = 'TestMachineEnvironmentVariableName' - $testPathEnvironmentVarName = 'TestMachinePathEnvironmentVariableName' + $script:testEnvironmentVarName = 'TestMachineEnvironmentVariableName' + $script:testPathEnvironmentVarName = 'TestMachinePathEnvironmentVariableName' - $testValue = 'InitialMachineTestValue' - $newTestValue = 'NewMachineTestValue' + $script:testValue = 'InitialMachineTestValue' + $script:newTestValue = 'NewMachineTestValue' - $configFile = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_EnvironmentResource.config.ps1' + $script:configFile = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_EnvironmentResource.config.ps1' } AfterAll { # Remove variables from the process (these shouldn't have been set): - [System.Environment]::SetEnvironmentVariable($testEnvironmentVarName, $null) - [System.Environment]::SetEnvironmentVariable($testPathEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testEnvironmentVarName, $null) + [System.Environment]::SetEnvironmentVariable($script:testPathEnvironmentVarName, $null) # Remove variables from machine: - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName } - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName } } - Context "Should create the environment variable $testEnvironmentVarName" { + Context "Should create the environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Create' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName # Ensure the environment variable doesn't exist: # Remove variable from machine: - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testEnvironmentVarName } It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Present' ` -Target @('Machine') ` -OutputPath $configurationPath ` @@ -704,21 +704,21 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $testValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:testValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should update environment variable $testEnvironmentVarName" { + Context "Should update environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Update' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` - -Value $newTestValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` + -Value $script:newTestValue ` -Ensure 'Present' ` -Target @('Machine') ` -OutputPath $configurationPath ` @@ -733,8 +733,8 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } @@ -745,8 +745,8 @@ try It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` -Value 'otherValue' ` -Ensure 'Absent' ` -Target @('Machine') ` @@ -762,20 +762,20 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove environment variable $testEnvironmentVarName" { + Context "Should remove environment variable $script:testEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Remove' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testEnvironmentVarName ` -Value $null ` -Ensure 'Absent' ` -Target @('Machine') ` @@ -791,29 +791,29 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testEnvironmentVarName + $currentConfig.Name | Should -Be $script:testEnvironmentVarName $currentConfig.Value | Should -Be $null $currentConfig.Ensure | Should -Be 'Absent' } } - Context "Should create the path environment variable $testPathEnvironmentVarName" { + Context "Should create the path environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Create_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName # Ensure the environment variable doesn't exist: # Remove variable from machine: - if (Get-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') + if (Get-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName -ErrorAction 'SilentlyContinue') { - Remove-ItemProperty -Path $machineEnvironmentRegistryPath -Name $testPathEnvironmentVarName + Remove-ItemProperty -Path $script:machineEnvironmentRegistryPath -Name $script:testPathEnvironmentVarName } It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Present' ` -Path $true ` -Target @('Machine') ` @@ -829,23 +829,23 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName - $currentConfig.Value | Should -Be $testValue + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName + $currentConfig.Value | Should -Be $script:testValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should update environment variable $testPathEnvironmentVarName" { + Context "Should update environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Update_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName - $expectedValue = $testValue + ';' + $newTestValue + $expectedValue = $script:testValue + ';' + $script:newTestValue It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $newTestValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:newTestValue ` -Ensure 'Present' ` -Path $true ` -Target @('Machine') ` @@ -861,7 +861,7 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $expectedValue $currentConfig.Ensure | Should -Be 'Present' } @@ -871,12 +871,12 @@ try $configurationName = 'MSFT_EnvironmentResource_NonRemove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName - $expectedValue = $testValue + ';' + $newTestValue + $expectedValue = $script:testValue + ';' + $script:newTestValue It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` -Value 'otherValue' ` -Ensure 'Absent' ` -Path $true ` @@ -893,21 +893,21 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $expectedValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove only one value from environment variable $testPathEnvironmentVarName" { + Context "Should remove only one value from environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_PartialRemove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` - -Value $testValue ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` + -Value $script:testValue ` -Ensure 'Absent' ` -Path $true ` -Target @('Machine') ` @@ -923,20 +923,20 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName - $currentConfig.Value | Should -Be $newTestValue + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName + $currentConfig.Value | Should -Be $script:newTestValue $currentConfig.Ensure | Should -Be 'Present' } } - Context "Should remove the environment variable $testPathEnvironmentVarName" { + Context "Should remove the environment variable $script:testPathEnvironmentVarName" { $configurationName = 'MSFT_EnvironmentResource_Remove_Path' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName It 'Should compile without throwing' { { - . $configFile -ConfigurationName $configurationName - & $configurationName -Name $testPathEnvironmentVarName ` + . $script:configFile -ConfigurationName $configurationName + & $configurationName -Name $script:testPathEnvironmentVarName ` -Value $null ` -Ensure 'Absent' ` -Path $true ` @@ -953,7 +953,7 @@ try It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should -Be $testPathEnvironmentVarName + $currentConfig.Name | Should -Be $script:testPathEnvironmentVarName $currentConfig.Value | Should -Be $null $currentConfig.Ensure | Should -Be 'Absent' } diff --git a/Tests/Integration/MSFT_EnvironmentResource.Integration.Tests.ps1 b/Tests/Integration/MSFT_EnvironmentResource.Integration.Tests.ps1 index bb7d1f6..f59a600 100644 --- a/Tests/Integration/MSFT_EnvironmentResource.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_EnvironmentResource.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -# These tests must be run with elevated access +# These tests must be run with elevated access $errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' @@ -64,7 +64,7 @@ try # Verify the environmnet variable $envVar is successfully created $retrievedVar.Ensure | Should -Be 'Absent' - # Verify the create environmnet variable's value is set to default value [String]::Empty + # Verify the create environmnet variable's value is set to default value [System.String]::Empty $retrievedVar.Value | Should -Be $null # Remove the created test variable @@ -189,10 +189,11 @@ try It 'Should return true when an environment variable is present and should be' { $envVar = 'BlahVar' $val = 'A;B;C' + Set-TargetResource -Name $envVar -Value $val # Test the created environmnet variable - Test-TargetResource -Name $envVar | Should -Be $true + Test-TargetResource -Name $envVar | Should -BeTrue # Remove the created test variable Set-TargetResource -Name $envVar -Ensure Absent @@ -204,7 +205,7 @@ try Set-TargetResource -Name $envVar -Value $val # Verify the environmnet variable exists - Test-TargetResource -Name $envVar -Value $val | Should -Be $true + Test-TargetResource -Name $envVar -Value $val | Should -BeTrue # Remove the created test variable Set-TargetResource -Name $envVar -Ensure Absent @@ -215,7 +216,7 @@ try Set-TargetResource -Name $envVar -Ensure Absent # Verify the environmnet variable exists - Test-TargetResource -Name $envVar -Ensure Absent | Should -Be $true + Test-TargetResource -Name $envVar -Ensure Absent | Should -BeTrue # Remove the created test variable Set-TargetResource -Name $envVar -Ensure Absent @@ -229,7 +230,7 @@ try $subpath = 'B' # Test a sub-path exists in environment variable - Test-TargetResource -Name $envVar -Value $subpath -Path $true | Should -Be $true + Test-TargetResource -Name $envVar -Value $subpath -Path $true | Should -BeTrue # Remove the created test variable Set-TargetResource -Name $envVar -Ensure Absent @@ -242,7 +243,7 @@ try $subpath = 'B;a;c' - Test-TargetResource -Name $envVar -Value $subpath -Path $true | Should -Be $true + Test-TargetResource -Name $envVar -Value $subpath -Path $true | Should -BeTrue # Remove the created test variable Set-TargetResource -Name $envVar -Ensure Absent @@ -255,7 +256,7 @@ try $subpath = 'D;E' - Test-TargetResource -Name $envVar -Value $subpath -Path $true -Ensure Absent | Should -Be $true + Test-TargetResource -Name $envVar -Value $subpath -Path $true -Ensure Absent | Should -BeTrue # Remove the created test variable Set-TargetResource -Name $envVar -Ensure Absent diff --git a/Tests/Integration/MSFT_EnvironmentResource.config.ps1 b/Tests/Integration/MSFT_EnvironmentResource.config.ps1 index 1ee2b4d..0ad329f 100644 --- a/Tests/Integration/MSFT_EnvironmentResource.config.ps1 +++ b/Tests/Integration/MSFT_EnvironmentResource.config.ps1 @@ -1,4 +1,4 @@ -param +param ( [Parameter(Mandatory = $true)] [System.String] diff --git a/Tests/Integration/MSFT_GroupResource.Integration.Tests.ps1 b/Tests/Integration/MSFT_GroupResource.Integration.Tests.ps1 index 0f812a8..4df7c1c 100644 --- a/Tests/Integration/MSFT_GroupResource.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_GroupResource.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] param () $errorActionPreference = 'Stop' @@ -76,7 +76,7 @@ try GroupName = $testGroupName } - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse try { @@ -86,7 +86,7 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName -Members @() | Should -Be $true + Test-GroupExists -GroupName $testGroupName -Members @() | Should -BeTrue } finally { @@ -106,7 +106,7 @@ try GroupName = $testGroupName } - Test-GroupExists -GroupName $testGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeTrue { . $script:confgurationNoMembersFilePath -ConfigurationName $configurationName @@ -114,7 +114,7 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeTrue } It 'Should add a member to the built-in Users group with MembersToInclude' { @@ -127,7 +127,7 @@ try MembersToInclude = $testUsername1 } - Test-GroupExists -GroupName $testGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeTrue { . $script:confgurationWithMembersToIncludeExcludeFilePath -ConfigurationName $configurationName @@ -135,7 +135,7 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName -MembersToInclude $testUsername1 | Should -Be $true + Test-GroupExists -GroupName $testGroupName -MembersToInclude $testUsername1 | Should -BeTrue } It 'Should create a group with two test users using Members' { @@ -150,7 +150,7 @@ try Members = $groupMembers } - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse try { @@ -160,7 +160,7 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName -Members $groupMembers | Should -Be $true + Test-GroupExists -GroupName $testGroupName -Members $groupMembers | Should -BeTrue } finally { @@ -183,11 +183,11 @@ try MembersToInclude = $groupMembers } - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse New-Group -GroupName $testGroupName - Test-GroupExists -GroupName $testGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeTrue try { @@ -197,7 +197,7 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName -MembersToInclude $groupMembers | Should -Be $true + Test-GroupExists -GroupName $testGroupName -MembersToInclude $groupMembers | Should -BeTrue } finally { @@ -220,11 +220,11 @@ try MembersToExclude = $groupMembersToExclude } - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse New-Group -GroupName $testGroupName -Members $groupMembersToExclude - Test-GroupExists -GroupName $testGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeTrue try { @@ -234,7 +234,7 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName -MembersToExclude $groupMembersToExclude | Should -Be $true + Test-GroupExists -GroupName $testGroupName -MembersToExclude $groupMembersToExclude | Should -BeTrue } finally { @@ -254,11 +254,11 @@ try GroupName = $testGroupName } - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse New-Group -GroupName $testGroupName - Test-GroupExists -GroupName $testGroupName | Should -Be $true + Test-GroupExists -GroupName $testGroupName | Should -BeTrue try { @@ -268,7 +268,7 @@ try Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force } | Should -Not -Throw - Test-GroupExists -GroupName $testGroupName | Should -Be $false + Test-GroupExists -GroupName $testGroupName | Should -BeFalse } finally { diff --git a/Tests/Integration/MSFT_GroupResource_Members.config.ps1 b/Tests/Integration/MSFT_GroupResource_Members.config.ps1 index 8ca8298..b51d44c 100644 --- a/Tests/Integration/MSFT_GroupResource_Members.config.ps1 +++ b/Tests/Integration/MSFT_GroupResource_Members.config.ps1 @@ -1,4 +1,4 @@ -param +param ( [Parameter(Mandatory = $true)] [System.String] diff --git a/Tests/Integration/MSFT_GroupResource_MembersToIncludeExclude.config.ps1 b/Tests/Integration/MSFT_GroupResource_MembersToIncludeExclude.config.ps1 index ecd15df..4c6b087 100644 --- a/Tests/Integration/MSFT_GroupResource_MembersToIncludeExclude.config.ps1 +++ b/Tests/Integration/MSFT_GroupResource_MembersToIncludeExclude.config.ps1 @@ -1,4 +1,4 @@ -param +param ( [Parameter(Mandatory = $true)] [System.String] diff --git a/Tests/Integration/MSFT_GroupResource_NoMembers.config.ps1 b/Tests/Integration/MSFT_GroupResource_NoMembers.config.ps1 index 7497040..f0ee5cc 100644 --- a/Tests/Integration/MSFT_GroupResource_NoMembers.config.ps1 +++ b/Tests/Integration/MSFT_GroupResource_NoMembers.config.ps1 @@ -1,4 +1,4 @@ -param +param ( [Parameter(Mandatory = $true)] [System.String] diff --git a/Tests/Integration/MSFT_MsiPackage.EndToEnd.Tests.ps1 b/Tests/Integration/MSFT_MsiPackage.EndToEnd.Tests.ps1 index 5abf0a9..2f10bc9 100644 --- a/Tests/Integration/MSFT_MsiPackage.EndToEnd.Tests.ps1 +++ b/Tests/Integration/MSFT_MsiPackage.EndToEnd.Tests.ps1 @@ -1,4 +1,4 @@ -<# +<# Please note that some of these tests depend on each other. They must be run in the order given - if one test fails, subsequent tests may also fail. @@ -43,7 +43,7 @@ Describe 'MsiPackage End to End Tests' { <# This log file is used to log messages from the mock server which is important for debugging since - most of the work of the mock server is done within a separate process. + most of the work of the mock server is done within a separate process. #> $script:logFile = Join-Path -Path $PSScriptRoot -ChildPath 'PackageTestLogFile.txt' $script:environmentInIncorrectStateErrorMessage = 'The current environment is not in the expected state for this test - either something was setup incorrectly on your machine or a previous test failed - results after this may be invalid.' @@ -55,6 +55,9 @@ Describe 'MsiPackage End to End Tests' { $null = New-TestMsi -DestinationPath $script:msiLocation + $script:testHttpPort = Get-UnusedTcpPort + $script:testHttpsPort = Get-UnusedTcpPort -ExcludePorts @($script:testHttpPort) + # Clear the log file 'Beginning integration tests' > $script:logFile } @@ -85,8 +88,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return True from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $true + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeTrue if ($testTargetResourceInitialResult -ne $true) { @@ -100,23 +103,23 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should not exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoOptionalParameters -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should return True from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Package should not exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } } @@ -130,8 +133,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return False from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $false + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeFalse if ($testTargetResourceInitialResult -ne $false) { @@ -145,23 +148,23 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should not exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoOptionalParameters -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should return True from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Package should exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } } @@ -175,8 +178,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return True from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $true + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeTrue if ($testTargetResourceInitialResult -ne $true) { @@ -190,23 +193,23 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoOptionalParameters -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should return True from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Package should exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } } @@ -220,8 +223,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return False from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $false + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeFalse if ($testTargetResourceInitialResult -ne $false) { @@ -235,23 +238,23 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoOptionalParameters -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should return True from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Package should not exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } } @@ -273,8 +276,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return False from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $false + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeFalse if ($testTargetResourceInitialResult -ne $false) { @@ -288,27 +291,27 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should not exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathLogPath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should return True from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Should have created the log file' { - Test-Path -Path $logPath | Should Be $true + Test-Path -Path $logPath | Should -BeTrue } It 'Package should exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } } @@ -330,8 +333,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return False from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $false + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeFalse if ($testTargetResourceInitialResult -ne $false) { @@ -345,35 +348,36 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathLogPath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should return True from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Should have created the log file' { - Test-Path -Path $logPath | Should Be $true + Test-Path -Path $logPath | Should -BeTrue } It 'Package should not exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false - } + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse + } } Context 'Install package from HTTP Url' { $configurationName = 'UninstallExistingMsiPackageFromHttp' - $baseUrl = 'http://localhost:1242/' - $msiUrl = "$baseUrl" + 'package.msi' + $uriBuilder = [System.UriBuilder]::new('http', 'localhost', $script:testHttpPort) + $uriBuilder.Path = 'package.msi' + $msiUrl = $uriBuilder.Uri.AbsoluteUri $fileServerStarted = $null $job = $null @@ -385,8 +389,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return False from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $false + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeFalse if ($testTargetResourceInitialResult -ne $false) { @@ -400,23 +404,26 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should not exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } try { - $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $false + # Make sure no existing HTTP(S) test servers are running + Stop-EveryTestServerInstance + + $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $false -HttpPort $script:testHttpPort -HttpsPort $script:testHttpsPort $fileServerStarted = $serverResult.FileServerStarted - $job = $serverResult.Job + $job = $serverResult.Job $fileServerStarted.WaitOne(30000) It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoOptionalParameters -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } } finally @@ -429,19 +436,20 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return True from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Package should exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } } Context 'Uninstall Msi package from HTTP Url' { $configurationName = 'InstallMsiPackageFromHttp' - $baseUrl = 'http://localhost:1242/' - $msiUrl = "$baseUrl" + 'package.msi' + $uriBuilder = [System.UriBuilder]::new('http', 'localhost', $script:testHttpPort) + $uriBuilder.Path = 'package.msi' + $msiUrl = $uriBuilder.Uri.AbsoluteUri $fileServerStarted = $null $job = $null @@ -453,8 +461,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return False from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $false + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeFalse if ($testTargetResourceInitialResult -ne $false) { @@ -468,23 +476,26 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } - + try { - $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $false + # Make sure no existing HTTP(S) test servers are running + Stop-EveryTestServerInstance + + $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $false -HttpPort $script:testHttpPort -HttpsPort $script:testHttpsPort $fileServerStarted = $serverResult.FileServerStarted $job = $serverResult.Job $fileServerStarted.WaitOne(30000) It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoOptionalParameters -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } } finally @@ -497,19 +508,20 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Package should not exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } } Context 'Install Msi package from HTTPS Url' { $configurationName = 'InstallMsiPackageFromHttpS' - $baseUrl = 'https://localhost:1243/' - $msiUrl = "$baseUrl" + 'package.msi' + $uriBuilder = [System.UriBuilder]::new('https', 'localhost', $script:testHttpsPort) + $uriBuilder.Path = 'package.msi' + $msiUrl = $uriBuilder.Uri.AbsoluteUri $fileServerStarted = $null $job = $null @@ -521,8 +533,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return False from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $false + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeFalse if ($testTargetResourceInitialResult -ne $false) { @@ -536,23 +548,26 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should not exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } - + try { - $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $true + # Make sure no existing HTTP(S) test servers are running + Stop-EveryTestServerInstance + + $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $true -HttpPort $script:testHttpPort -HttpsPort $script:testHttpsPort $fileServerStarted = $serverResult.FileServerStarted $job = $serverResult.Job $fileServerStarted.WaitOne(30000) It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoOptionalParameters -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } } finally @@ -565,19 +580,20 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Package should exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } } - + Context 'Uninstall Msi package from HTTPS Url' { $configurationName = 'UninstallMsiPackageFromHttps' - $baseUrl = 'https://localhost:1243/' - $msiUrl = "$baseUrl" + 'package.msi' + $uriBuilder = [System.UriBuilder]::new('https', 'localhost', $script:testHttpsPort) + $uriBuilder.Path = 'package.msi' + $msiUrl = $uriBuilder.Uri.AbsoluteUri $fileServerStarted = $null $job = $null @@ -589,8 +605,8 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return False from Test-TargetResource with the same parameters before configuration' { - $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters - $testTargetResourceInitialResult | Should Be $false + $testTargetResourceInitialResult = MSFT_MsiPackage\Test-TargetResource @msiPackageParameters + $testTargetResourceInitialResult | Should -BeFalse if ($testTargetResourceInitialResult -ne $false) { @@ -604,23 +620,26 @@ Describe 'MsiPackage End to End Tests' { } It 'Package should exist on the machine before configuration is run' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue } try { - $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $true + # Make sure no existing HTTP(S) test servers are running + Stop-EveryTestServerInstance + + $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $true -HttpPort $script:testHttpPort -HttpsPort $script:testHttpsPort $fileServerStarted = $serverResult.FileServerStarted $job = $serverResult.Job $fileServerStarted.WaitOne(30000) It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoOptionalParameters -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @msiPackageParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } } finally @@ -633,11 +652,11 @@ Describe 'MsiPackage End to End Tests' { } It 'Should return true from Test-TargetResource with the same parameters after configuration' { - MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should Be $true + MSFT_MsiPackage\Test-TargetResource @msiPackageParameters | Should -BeTrue } It 'Package should not exist on the machine' { - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } } } diff --git a/Tests/Integration/MSFT_MsiPackage.Integration.Tests.ps1 b/Tests/Integration/MSFT_MsiPackage.Integration.Tests.ps1 index 740f9bf..b177acc 100644 --- a/Tests/Integration/MSFT_MsiPackage.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_MsiPackage.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' if ($PSVersionTable.PSVersion -lt [Version] '5.1') @@ -37,7 +37,7 @@ try <# This log file is used to log messages from the mock server which is important for debugging since - most of the work of the mock server is done within a separate process. + most of the work of the mock server is done within a separate process. #> $script:logFile = Join-Path -Path $PSScriptRoot -ChildPath 'PackageTestLogFile.txt' @@ -49,6 +49,9 @@ try $null = New-TestMsi -DestinationPath $script:msiLocation + $script:testHttpPort = Get-UnusedTcpPort + $script:testHttpsPort = Get-UnusedTcpPort -ExcludePorts @($script:testHttpPort) + # Clear the log file 'Beginning integration tests' > $script:logFile } @@ -114,34 +117,34 @@ try -Path $script:msiLocation ` -ProductId $script:packageId - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse $testTargetResourceResult = Test-TargetResource ` -Ensure 'Absent' ` -Path $script:msiLocation ` -ProductId $script:packageId - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return correct value when package is present' { Set-TargetResource -Ensure 'Present' -Path $script:msiLocation -ProductId $script:packageId - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue $testTargetResourceResult = Test-TargetResource ` -Ensure 'Present' ` -Path $script:msiLocation ` -ProductId $script:packageId ` - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue $testTargetResourceResult = Test-TargetResource ` -Ensure 'Absent' ` -Path $script:msiLocation ` -ProductId $script:packageId ` - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } @@ -149,30 +152,33 @@ try It 'Should correctly install and remove a .msi package' { Set-TargetResource -Ensure 'Present' -Path $script:msiLocation -ProductId $script:packageId - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue $getTargetResourceResult = Get-TargetResource -Path $script:msiLocation -ProductId $script:packageId - $getTargetResourceResult.Version | Should Be '1.2.3.4' - $getTargetResourceResult.InstalledOn | Should Be ('{0:d}' -f [DateTime]::Now.Date) - $getTargetResourceResult.ProductId | Should Be $script:packageId + $getTargetResourceResult.Version | Should -Be '1.2.3.4' + $getTargetResourceResult.InstalledOn | Should -Be ('{0:d}' -f [System.DateTime]::Now.Date) + $getTargetResourceResult.ProductId | Should -Be $script:packageId - [Math]::Round($getTargetResourceResult.Size, 2) | Should Be 0.03 + [Math]::Round($getTargetResourceResult.Size, 2) | Should -Be 0.03 Set-TargetResource -Ensure 'Absent' -Path $script:msiLocation -ProductId $script:packageId - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse } It 'Should throw with incorrect product id' { $wrongPackageId = '{deadbeef-80c6-41e6-a1b9-8bdb8a050272}' - { Set-TargetResource -Ensure 'Present' -Path $script:msiLocation -ProductId $wrongPackageId } | Should Throw + { Set-TargetResource -Ensure 'Present' -Path $script:msiLocation -ProductId $wrongPackageId } | Should -Throw } It 'Should correctly install and remove a package from a HTTP URL' { - $baseUrl = 'http://localhost:1242/' - $msiUrl = "$baseUrl" + 'package.msi' + $uriBuilder = [System.UriBuilder]::new('http', 'localhost', $script:testHttpPort) + $baseUrl = $uriBuilder.Uri.AbsoluteUri + + $uriBuilder.Path = 'package.msi' + $msiUrl = $uriBuilder.Uri.AbsoluteUri $fileServerStarted = $null $job = $null @@ -181,20 +187,29 @@ try { 'Http tests:' >> $script:logFile - $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $false + # Make sure no existing HTTP(S) test servers are running + Stop-EveryTestServerInstance + + $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $false -HttpPort $script:testHttpPort -HttpsPort $script:testHttpsPort $fileServerStarted = $serverResult.FileServerStarted $job = $serverResult.Job # Wait for the file server to be ready to receive requests $fileServerStarted.WaitOne(30000) - { Set-TargetResource -Ensure 'Present' -Path $baseUrl -ProductId $script:packageId } | Should Throw + { Set-TargetResource -Ensure 'Present' -Path $baseUrl -ProductId $script:packageId } | Should -Throw Set-TargetResource -Ensure 'Present' -Path $msiUrl -ProductId $script:packageId - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue Set-TargetResource -Ensure 'Absent' -Path $msiUrl -ProductId $script:packageId - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse + } + catch + { + Write-Warning -Message 'Caught exception performing HTTP server tests. Outputting HTTP server log.' -Verbose + Get-Content -Path $script:logFile | Write-Verbose -Verbose + throw $_ } finally { @@ -207,9 +222,11 @@ try } It 'Should correctly install and remove a package from a HTTPS URL' -Skip:$script:skipHttpsTest { + $uriBuilder = [System.UriBuilder]::new('https', 'localhost', $script:testHttpsPort) + $baseUrl = $uriBuilder.Uri.AbsoluteUri - $baseUrl = 'https://localhost:1243/' - $msiUrl = "$baseUrl" + 'package.msi' + $uriBuilder.Path = 'package.msi' + $msiUrl = $uriBuilder.Uri.AbsoluteUri $fileServerStarted = $null $job = $null @@ -218,20 +235,29 @@ try { 'Https tests:' >> $script:logFile - $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $true + # Make sure no existing HTTP(S) test servers are running + Stop-EveryTestServerInstance + + $serverResult = Start-Server -FilePath $script:msiLocation -LogPath $script:logFile -Https $true -HttpPort $script:testHttpPort -HttpsPort $script:testHttpsPort $fileServerStarted = $serverResult.FileServerStarted - $job = $serverResult.Job + $job = $serverResult.Job # Wait for the file server to be ready to receive requests $fileServerStarted.WaitOne(30000) - { Set-TargetResource -Ensure 'Present' -Path $baseUrl -ProductId $script:packageId } | Should Throw + { Set-TargetResource -Ensure 'Present' -Path $baseUrl -ProductId $script:packageId } | Should -Throw Set-TargetResource -Ensure 'Present' -Path $msiUrl -ProductId $script:packageId - Test-PackageInstalledById -ProductId $script:packageId | Should Be $true + Test-PackageInstalledById -ProductId $script:packageId | Should -BeTrue Set-TargetResource -Ensure 'Absent' -Path $msiUrl -ProductId $script:packageId - Test-PackageInstalledById -ProductId $script:packageId | Should Be $false + Test-PackageInstalledById -ProductId $script:packageId | Should -BeFalse + } + catch + { + Write-Warning -Message 'Caught exception performing HTTPS server tests. Outputting HTTPS server log.' -Verbose + Get-Content -Path $script:logFile | Write-Verbose -Verbose + throw $_ } finally { @@ -253,8 +279,8 @@ try Set-TargetResource -Ensure 'Present' -Path $script:msiLocation -LogPath $logPath -ProductId $script:packageId - Test-Path -Path $logPath | Should Be $true - Get-Content -Path $logPath | Should Not Be $null + Test-Path -Path $logPath | Should -BeTrue + Get-Content -Path $logPath | Should -Not -Be $null } It 'Should add space after .MSI installation arguments' { @@ -281,7 +307,7 @@ try ProductId = $script:packageId } - { Set-TargetResource -Ensure 'Present' @packageParameters } | Should Not Throw + { Set-TargetResource -Ensure 'Present' @packageParameters } | Should -Not -Throw } It 'Should install package using user credentials when specified' { diff --git a/Tests/Integration/MSFT_MsiPackage_LogPath.ps1 b/Tests/Integration/MSFT_MsiPackage_LogPath.ps1 index ee5dafe..7efdc95 100644 --- a/Tests/Integration/MSFT_MsiPackage_LogPath.ps1 +++ b/Tests/Integration/MSFT_MsiPackage_LogPath.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,20 +11,20 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ProductId, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter(Mandatory = $true)] - [String] + [System.String] $LogPath ) diff --git a/Tests/Integration/MSFT_MsiPackage_NoOptionalParameters.ps1 b/Tests/Integration/MSFT_MsiPackage_NoOptionalParameters.ps1 index 209cd28..3e2bcb7 100644 --- a/Tests/Integration/MSFT_MsiPackage_NoOptionalParameters.ps1 +++ b/Tests/Integration/MSFT_MsiPackage_NoOptionalParameters.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,16 +11,16 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ProductId, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present' ) diff --git a/Tests/Integration/MSFT_RegistryResource.EndToEnd.Tests.ps1 b/Tests/Integration/MSFT_RegistryResource.EndToEnd.Tests.ps1 index b7d3c1f..2ba9712 100644 --- a/Tests/Integration/MSFT_RegistryResource.EndToEnd.Tests.ps1 +++ b/Tests/Integration/MSFT_RegistryResource.EndToEnd.Tests.ps1 @@ -1,4 +1,4 @@ -<# +<# WARNING: DO NOT RUN THESE TESTS ON A VALUABLE MACHINE! Running on a disposable VM or AppVeyor is strongly recommended. If these tests go awry, your machine's registry could be corrupted which will brick your machine! @@ -54,25 +54,25 @@ try } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathKeyAndNameOnly -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $registryKey = Get-Item -Path $registryParameters.Key -ErrorAction 'SilentlyContinue' It 'Should have created the registry key' { - $registryKey | Should Not Be $null + $registryKey | Should -Not -Be $null } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } @@ -86,29 +86,29 @@ try } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathKeyAndNameOnly -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $registryKeyValue = Get-ItemProperty -Path $registryParameters.Key -Name $registryParameters.ValueName -ErrorAction 'SilentlyContinue' It 'Should have created the registry key value' { - $registryKeyValue | Should Not Be $null + $registryKeyValue | Should -Not -Be $null } It 'Should not have set the registry key value' { - $registryKeyValue.($registryParameters.ValueName) | Should Be '' + $registryKeyValue.($registryParameters.ValueName) | Should -Be '' } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } @@ -124,29 +124,29 @@ try } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathWithDataAndType -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $registryKeyValue = Get-ItemProperty -Path $registryParameters.Key -Name $registryParameters.ValueName -ErrorAction 'SilentlyContinue' It 'Should have created the registry key value' { - $registryKeyValue | Should Not Be $null + $registryKeyValue | Should -Not -Be $null } It 'Should have set the registry key value to the specified String value' { - $registryKeyValue.($registryParameters.ValueName) | Should Be $registryParameters.ValueData + $registryKeyValue.($registryParameters.ValueName) | Should -Be $registryParameters.ValueData } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } @@ -156,8 +156,8 @@ try { 'String' { 'TestString2'; break } 'Binary' { '0xCAC1111'; break } - 'DWord' { [Int32]::MaxValue.ToString(); break } - 'QWord' { [Int64]::MaxValue.ToString(); break } + 'DWord' { [System.Int32]::MaxValue.ToString(); break } + 'QWord' { [System.Int64]::MaxValue.ToString(); break } 'MultiString' { @('MultiString1', 'MultiString2'); break } 'ExpandString' { '%WINDIR%'; break } } @@ -165,10 +165,10 @@ try $expectedRegistryKeyValue = switch ($registryKeyValueType) { 'String' { 'TestString2'; break } - 'Binary' { [Byte[]]@( 12, 172, 17, 17 ); break } - 'DWord' { [Int32]::MaxValue; break } - 'QWord' { [Int64]::MaxValue; break } - 'MultiString' { [String[]]@('MultiString1', 'MultiString2'); break } + 'Binary' { [System.Byte[]] @( 12, 172, 17, 17 ); break } + 'DWord' { [System.Int32]::MaxValue; break } + 'QWord' { [System.Int64]::MaxValue; break } + 'MultiString' { [System.String[]] @('MultiString1', 'MultiString2'); break } 'ExpandString' { 'C:\windows'; break } } @@ -184,29 +184,29 @@ try } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathWithDataAndType -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $registryKeyValue = Get-ItemProperty -Path $registryParameters.Key -Name $registryParameters.ValueName -ErrorAction 'SilentlyContinue' It 'Should be able to retrieve the registry key value' { - $registryKeyValue | Should Not Be $null + $registryKeyValue | Should -Not -Be $null } It 'Should have set the registry key value to the specified value' { - Compare-Object -ReferenceObject $expectedRegistryKeyValue -DifferenceObject $registryKeyValue.($registryParameters.ValueName) | Should Be $null + Compare-Object -ReferenceObject $expectedRegistryKeyValue -DifferenceObject $registryKeyValue.($registryParameters.ValueName) | Should -Be $null } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } } @@ -222,32 +222,32 @@ try ValueData = '0x00' } - $expectedRegistryKeyValue = [Byte[]]@(0) + $expectedRegistryKeyValue = [System.Byte[]] @(0) It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathWithDataAndType -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $registryKeyValue = Get-ItemProperty -Path $registryParameters.Key -Name $registryParameters.ValueName -ErrorAction 'SilentlyContinue' It 'Should be able to retrieve the registry key value' { - $registryKeyValue | Should Not Be $null + $registryKeyValue | Should -Not -Be $null } It 'Should have set the registry key value to the specified Binary value' { - Compare-Object -ReferenceObject $expectedRegistryKeyValue -DifferenceObject $registryKeyValue.'(default)' | Should Be $null + Compare-Object -ReferenceObject $expectedRegistryKeyValue -DifferenceObject $registryKeyValue.'(default)' | Should -Be $null } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } @@ -263,15 +263,15 @@ try } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathWithDataAndType -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $parentRegistryKey = Get-Item -Path 'HKLM:' @@ -286,7 +286,7 @@ try } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } @@ -300,25 +300,25 @@ try } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathKeyAndNameOnly -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $registryKeyValue = Get-ItemProperty -Path $registryParameters.Key -Name $registryParameters.ValueName -ErrorAction 'SilentlyContinue' It 'Should have removed the registry key value' { - $registryKeyValue | Should Be $null + $registryKeyValue | Should -Be $null } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } @@ -334,25 +334,25 @@ try } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathWithDataAndType -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $registryKeyValue = Get-ItemProperty -Path $registryParameters.Key -Name $registryParameters.ValueName -ErrorAction 'SilentlyContinue' It 'Should have removed the registry key value' { - $registryKeyValue | Should Be $null + $registryKeyValue | Should -Be $null } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } @@ -366,25 +366,25 @@ try } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePathKeyAndNameOnly -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @registryParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } $registryKey = Get-Item -Path $registryParameters.Key -ErrorAction 'SilentlyContinue' It 'Should have removed the registry key value' { - $registryKey | Should Be $null + $registryKey | Should -Be $null } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_RegistryResource\Test-TargetResource @registryParameters | Should Be $true + MSFT_RegistryResource\Test-TargetResource @registryParameters | Should -BeTrue } } } @@ -393,4 +393,4 @@ finally { Exit-DscResourceTestEnvironment -TestEnvironment $script:testEnvironment } - + diff --git a/Tests/Integration/MSFT_RegistryResource.Integration.Tests.ps1 b/Tests/Integration/MSFT_RegistryResource.Integration.Tests.ps1 index 3426ff5..c2a6ff2 100644 --- a/Tests/Integration/MSFT_RegistryResource.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_RegistryResource.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -<# +<# WARNING: DO NOT RUN THESE TESTS ON A VALUABLE MACHINE! Running on a disposable VM or AppVeyor is strongly recommended. If these tests go awry, your machine's registry could be corrupted which will brick your machine! @@ -78,27 +78,27 @@ try It 'Should return Present when retrieving a blank value from an existing registry key' { $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' $getTargetResourceResult = Get-TargetResource -Key $registryKeyPath -ValueName '' - $getTargetResourceResult.Ensure | Should Be 'Present' + $getTargetResourceResult.Ensure | Should -Be 'Present' } It 'Should return Absent when retrieving a blank value from a registry key that does not exist' { $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environmental' $getTargetResourceResult = Get-TargetResource -Key $registryKeyPath -ValueName '' - $getTargetResourceResult.Ensure | Should Be 'Absent' + $getTargetResourceResult.Ensure | Should -Be 'Absent' } It 'Should return Present when retrieving an existing value from an existing registry key' { - $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' + $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' $registryValueName = 'Path' $getTargetResourceResult = Get-TargetResource -Key $registryKeyPath -ValueName $registryValueName - $getTargetResourceResult.Ensure | Should Be 'Present' + $getTargetResourceResult.Ensure | Should -Be 'Present' } It 'Should return Absent when retrieving a nonexistant value from an existing registry key' { - $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' + $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' $registryValueName = 'PsychoPath' $getTargetResourceResult = Get-TargetResource -Key $registryKeyPath -ValueName $registryValueName - $getTargetResourceResult.Ensure | Should Be 'Absent' + $getTargetResourceResult.Ensure | Should -Be 'Absent' } $commonRegistryKeys = @( 'HKEY_CURRENT_USER', 'HKEY_CLASSES_ROOT', 'HKEY_USERS', 'HKEY_CURRENT_CONFIG' ) @@ -106,7 +106,7 @@ try { It "Should return Present when retrieving a blank value from $commonRegistryKey" { $getTargetResourceResult = Get-TargetResource -Key $commonRegistryKey -ValueName '' - $getTargetResourceResult.Ensure | Should Be 'Present' + $getTargetResourceResult.Ensure | Should -Be 'Present' } } @@ -116,7 +116,7 @@ try # Verify that the registry key has been created $registryKeyExists = Test-RegistryKeyExists -KeyPath $script:registryKeyPath - $registryKeyExists | Should Be $true + $registryKeyExists | Should -BeTrue } It 'Should create a new registry key tree' { @@ -126,7 +126,7 @@ try # Verify that the registry key has been created $registryKeyExists = Test-RegistryKeyExists -KeyPath $registryKeyTreePath - $registryKeyExists | Should Be $true + $registryKeyExists | Should -BeTrue } It 'Should remove a registry key' { @@ -135,14 +135,14 @@ try # Verify that the registry key exists before removal $registryKeyExists = Test-RegistryKeyExists -KeyPath $script:registryKeyPath - $registryKeyExists | Should Be $true + $registryKeyExists | Should -BeTrue - # Now remove the TestKey + # Now remove the TestKey Set-TargetResource -Key $script:registryKeyPath -ValueName '' -Ensure 'Absent' # Verify that the registry key has been removed $registryKeyExists = Test-RegistryKeyExists -KeyPath $script:registryKeyPath - $registryKeyExists | Should Be $false + $registryKeyExists | Should -BeFalse } It 'Should remove a registry key tree' { @@ -153,27 +153,27 @@ try # Verify that the registry key tree exists before removal $registryKeyExists = Test-RegistryKeyExists -KeyPath $registryKeyTreePath - $registryKeyExists | Should Be $true + $registryKeyExists | Should -BeTrue - # Remove the test registry key tree + # Remove the test registry key tree Set-TargetResource -Key $registryKeyTreePath -ValueName '' -Ensure 'Absent' # Verify that the registry key tree has been removed $registryKeyExists = Test-RegistryKeyExists -KeyPath $registryKeyTreePath - $registryKeyExists | Should Be $false + $registryKeyExists | Should -BeFalse } It 'Should create a new string registry key value' { $valueName = 'TestValue' $valueData = 'TestData' $valueType = 'String' - - # Create the new registry key value + + # Create the new registry key value Set-TargetResource -Key $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType # Verify that the registry key value has been created with the correct data and type $registryValueExists = Test-RegistryValueExists -KeyPath $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType - $registryValueExists | Should Be $true + $registryValueExists | Should -BeTrue } It 'Should create a new binary registry key value' { @@ -181,24 +181,24 @@ try $valueData = 'aabbcc' $valueType = 'Binary' - # Create the new registry key value + # Create the new registry key value Set-TargetResource -Key $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType -Hex $true # Verify that the registry key value has been created with the correct data and type $registryValueExists = Test-RegistryValueExists -KeyPath $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType - $registryValueExists | Should Be $true + $registryValueExists | Should -BeTrue } It 'Should set the default value of a registry key' { $valueName = '' $valueData = 'DefaultValue' - # Create the new registry key value + # Create the new registry key value Set-TargetResource -Key $script:registryKeyPath -ValueName $valueName -ValueData $valueData # Verify that the registry key value has been created with the correct data and type $registryValueExists = Test-RegistryValueExists -KeyPath $script:registryKeyPath -ValueName '(default)' -ValueData $valueData -ValueType 'String' - $registryValueExists | Should Be $true + $registryValueExists | Should -BeTrue } It 'Should remove a registry key value' { @@ -208,17 +208,17 @@ try # Create the test registry value New-RegistryValue -KeyPath $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType - + # Verify that the registry key value exists before removal $registryValueExists = Test-RegistryValueExists -KeyPath $script:registryKeyPath -ValueName $valueName - $registryValueExists | Should Be $true + $registryValueExists | Should -BeTrue # Remove the registry value Set-TargetResource -Key $script:registryKeyPath -ValueName $valueName -Ensure 'Absent' # Verify that the registry key value has been removed $registryValueExists = Test-RegistryValueExists -KeyPath $script:registryKeyPath -ValueName $valueName - $registryValueExists | Should Be $false + $registryValueExists | Should -BeFalse } It 'Should remove the default value for a registry key' { @@ -228,17 +228,17 @@ try # Create the test registry value New-RegistryValue -KeyPath $script:registryKeyPath -ValueName '(default)' -ValueData $valueData -ValueType $valueType - + # Verify that the registry key value exists before removal $registryValueExists = Test-RegistryValueExists -KeyPath $script:registryKeyPath -ValueName '(default)' - $registryValueExists | Should Be $true + $registryValueExists | Should -BeTrue # Remove the registry value Set-TargetResource -Key $script:registryKeyPath -ValueName $valueName -Ensure 'Absent' # Verify that the registry key value has been removed $registryValueExists = Test-RegistryValueExists -KeyPath $script:registryKeyPath -ValueName '(default)' - $registryValueExists | Should Be $false + $registryValueExists | Should -BeFalse } It 'Should create a new key and value with path containing forward slashes' { @@ -246,51 +246,51 @@ try $valueName = 'Testing' $valueData = 'TestValue' - # Create the new registry key value + # Create the new registry key value Set-TargetResource -Key $registryKeyPathWithForwardSlashes -ValueName $valueName -ValueData $valueData # Verify that the registry key value has been created with the correct data and type $registryValueExists = Test-RegistryValueExists -KeyPath $registryKeyPathWithForwardSlashes -ValueName $valueName -ValueData $valueData - $registryValueExists | Should Be $true + $registryValueExists | Should -BeTrue } # Test-TargetResource It 'Should return true for an existing registry key' { $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' $testTargetResourceResult = Test-TargetResource -Key $registryKeyPath -ValueName '' - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return false for a registry key that does not exist' { $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environmentally' $testTargetResourceResult = Test-TargetResource -Key $registryKeyPath -ValueName '' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should return true for an existing registry value' { $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' $valueName = 'path' $testTargetResourceResult = Test-TargetResource -Key $registryKeyPath -ValueName $valueName - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return false for a registry value that does not exist' { - $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' + $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' $valueName = 'NonExisting' $testTargetResourceResult = Test-TargetResource -Key $registryKeyPath -ValueName $valueName - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should return true when Ensure is Absent and registry key does not exist' { $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environmentally' $testTargetResourceResult = Test-TargetResource -Key $registryKeyPath -ValueName '' -Ensure 'Absent' - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return false when Ensure is Absent and registry key exists' { $registryKeyPath = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' $testTargetResourceResult = Test-TargetResource -Key $registryKeyPath -ValueName '' -Ensure 'Absent' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should return false when Ensure is Absent and registry value exists with invalid data' { @@ -299,7 +299,7 @@ try $valueData = 'FakePath' $testTargetResourceResult = Test-TargetResource -Key $registryKeyPath -ValueName $valueName -ValueData $valueData -Ensure 'Absent' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should return true for a multi-string registry value' { @@ -311,7 +311,7 @@ try New-RegistryValue -KeyPath $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType $testTargetResourceResult = Test-TargetResource -Key $registryKeyPath -ValueName $valueName -ValueData $valueData - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return true for a binary registry value' { @@ -323,7 +323,7 @@ try New-RegistryValue -KeyPath $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType $testTargetResourceResult = Test-TargetResource -Key $script:registryKeyPath -ValueName $valueName -ValueData $valueData - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return true for an empty binary registry value' { @@ -336,10 +336,10 @@ try # Verify that the registry key value has been created with the correct data and type $registryValueExists = Test-RegistryValueExists -KeyPath $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType - $registryValueExists | Should Be $true + $registryValueExists | Should -BeTrue $testTargetResourceResult = Test-TargetResource -Key $script:registryKeyPath -ValueName $valueName -ValueData $valueData - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return true for binary registry value with zeroes' { @@ -351,7 +351,7 @@ try New-RegistryValue -KeyPath $script:registryKeyPath -ValueName $valueName -ValueData $valueData -ValueType $valueType $testTargetResourceResult = Test-TargetResource -Key $script:registryKeyPath -ValueName $valueName -ValueData $valueData - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } } } diff --git a/Tests/Integration/MSFT_RegistryResource_KeyAndNameOnly.config.ps1 b/Tests/Integration/MSFT_RegistryResource_KeyAndNameOnly.config.ps1 index 30622fa..0bdd388 100644 --- a/Tests/Integration/MSFT_RegistryResource_KeyAndNameOnly.config.ps1 +++ b/Tests/Integration/MSFT_RegistryResource_KeyAndNameOnly.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,15 +11,15 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Key, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter(Mandatory = $true)] - [String] + [System.String] [AllowEmptyString()] $ValueName ) diff --git a/Tests/Integration/MSFT_RegistryResource_WithDataAndType.config.ps1 b/Tests/Integration/MSFT_RegistryResource_WithDataAndType.config.ps1 index 16615a4..55edf5f 100644 --- a/Tests/Integration/MSFT_RegistryResource_WithDataAndType.config.ps1 +++ b/Tests/Integration/MSFT_RegistryResource_WithDataAndType.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,25 +11,25 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Key, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter(Mandatory = $true)] - [String] + [System.String] [AllowEmptyString()] $ValueName, [Parameter(Mandatory = $true)] [ValidateSet('String', 'Binary', 'DWord', 'QWord', 'MultiString', 'ExpandString')] - [String] + [System.String] $ValueType, [Parameter(Mandatory = $true)] - [String[]] + [System.String[]] [AllowEmptyCollection()] $ValueData ) diff --git a/Tests/Integration/MSFT_ScriptResource.Integration.Tests.ps1 b/Tests/Integration/MSFT_ScriptResource.Integration.Tests.ps1 index 52a7b95..baad82b 100644 --- a/Tests/Integration/MSFT_ScriptResource.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_ScriptResource.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' if ($PSVersionTable.PSVersion -lt [Version] '5.1') @@ -58,15 +58,15 @@ Describe 'Script Integration Tests' { # Cannot use $TestDrive here because script is run outside of Pester $resourceParameters = @{ FilePath = $script:testFilePath - FileContent = 'Test file content' + FileContent = 'Test file content' } It 'Should have removed test file before the configuration' { - Test-Path -Path $resourceParameters.FilePath | Should Be $false + Test-Path -Path $resourceParameters.FilePath | Should -BeFalse } It 'Should compile and apply the MOF without throwing' { - { + { . $script:configurationNoCredentialFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -74,7 +74,7 @@ Describe 'Script Integration Tests' { } It 'Should have created the test file' { - Test-Path -Path $resourceParameters.FilePath | Should Be $true + Test-Path -Path $resourceParameters.FilePath | Should -BeTrue } It 'Should have set file content correctly' { @@ -91,7 +91,7 @@ Describe 'Script Integration Tests' { } $configurationName = 'TestScriptWithCredential' - + # Cannot use $TestDrive here because script is run outside of Pester $resourceParameters = @{ FilePath = $script:testFilePath @@ -100,7 +100,7 @@ Describe 'Script Integration Tests' { } It 'Should have removed test file before config runs' { - Test-Path -Path $resourceParameters.FilePath | Should Be $false + Test-Path -Path $resourceParameters.FilePath | Should -BeFalse } $configData = @{ @@ -114,19 +114,19 @@ Describe 'Script Integration Tests' { } It 'Should compile and apply the MOF without throwing' { - { + { . $script:configurationWithCredentialFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $configData @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should have created the test file' { - Test-Path -Path $resourceParameters.FilePath | Should Be $true + Test-Path -Path $resourceParameters.FilePath | Should -BeTrue } It 'Should have set file content correctly' { - Get-Content -Path $resourceParameters.FilePath -Raw | Should Be "$($resourceParameters.FileContent)`r`n" + Get-Content -Path $resourceParameters.FilePath -Raw | Should -Be "$($resourceParameters.FileContent)`r`n" } } } diff --git a/Tests/Integration/MSFT_ScriptResource_NoCredential.config.ps1 b/Tests/Integration/MSFT_ScriptResource_NoCredential.config.ps1 index 7c33181..1a4846c 100644 --- a/Tests/Integration/MSFT_ScriptResource_NoCredential.config.ps1 +++ b/Tests/Integration/MSFT_ScriptResource_NoCredential.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -12,12 +12,12 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $FilePath, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $FileContent ) diff --git a/Tests/Integration/MSFT_ScriptResource_WithCredential.config.ps1 b/Tests/Integration/MSFT_ScriptResource_WithCredential.config.ps1 index 0f9f066..9f5fb58 100644 --- a/Tests/Integration/MSFT_ScriptResource_WithCredential.config.ps1 +++ b/Tests/Integration/MSFT_ScriptResource_WithCredential.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -12,12 +12,12 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $FilePath, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $FileContent, [Parameter(Mandatory = $true)] diff --git a/Tests/Integration/MSFT_ServiceResource.Integration.Tests.ps1 b/Tests/Integration/MSFT_ServiceResource.Integration.Tests.ps1 index be5bd90..474d3bc 100644 --- a/Tests/Integration/MSFT_ServiceResource.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_ServiceResource.Integration.Tests.ps1 @@ -122,59 +122,59 @@ try $resourceParameters = $script:existingServiceProperties It 'Should compile and apply the MOF without throwing' { - { + { . $script:configurationAllExceptCredentialFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $service = Get-Service -Name $resourceParameters.Name -ErrorAction 'SilentlyContinue' $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$($resourceParameters.Name)'" -ErrorAction 'SilentlyContinue' It 'Should have created a new service with the specified name' { - $service | Should Not Be $null - $serviceCimInstance | Should Not Be $null + $service | Should -Not -Be $null + $serviceCimInstance | Should -Not -Be $null - $service.Name | Should Be $resourceParameters.Name - $serviceCimInstance.Name | Should Be $resourceParameters.Name + $service.Name | Should -Be $resourceParameters.Name + $serviceCimInstance.Name | Should -Be $resourceParameters.Name } It 'Should have created a new service with the specified path' { - $serviceCimInstance.PathName | Should Be $resourceParameters.Path + $serviceCimInstance.PathName | Should -Be $resourceParameters.Path } It 'Should have created a new service with the specified display name' { - $service.DisplayName | Should Be $resourceParameters.DisplayName + $service.DisplayName | Should -Be $resourceParameters.DisplayName } It 'Should have created a new service with the specified description' { - $serviceCimInstance.Description | Should Be $resourceParameters.Description + $serviceCimInstance.Description | Should -Be $resourceParameters.Description } It 'Should have created a new service with the specified dependencies' { $differentDependencies = Compare-Object -ReferenceObject $resourceParameters.Dependencies -DifferenceObject $service.ServicesDependedOn.Name - $differentDependencies | Should Be $null + $differentDependencies | Should -Be $null } It 'Should have created a new service with the default state as Running' { - $service.Status | Should Be 'Running' + $service.Status | Should -Be 'Running' } It 'Should have created a new service with the default startup type as Auto' { - $serviceCimInstance.StartMode | Should Be 'Auto' + $serviceCimInstance.StartMode | Should -Be 'Auto' } It 'Should have created a new service with the default startup account name as LocalSystem' { - $serviceCimInstance.StartName | Should Be 'LocalSystem' + $serviceCimInstance.StartName | Should -Be 'LocalSystem' } It 'Should have created a new service with the default desktop interaction setting as False' { - $serviceCimInstance.DesktopInteract | Should Be $false + $serviceCimInstance.DesktopInteract | Should -BeFalse } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should Be $true + MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should -BeTrue } } @@ -185,59 +185,59 @@ try $resourceParameters = $script:newServiceProperties It 'Should compile and apply the MOF without throwing' { - { + { . $script:configurationAllExceptCredentialFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $service = Get-Service -Name $resourceParameters.Name -ErrorAction 'SilentlyContinue' $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$($resourceParameters.Name)'" -ErrorAction 'SilentlyContinue' It 'Should not have removed service with specified name' { - $service | Should Not Be $null - $serviceCimInstance | Should Not Be $null + $service | Should -Not -Be $null + $serviceCimInstance | Should -Not -Be $null - $service.Name | Should Be $resourceParameters.Name - $serviceCimInstance.Name | Should Be $resourceParameters.Name + $service.Name | Should -Be $resourceParameters.Name + $serviceCimInstance.Name | Should -Be $resourceParameters.Name } It 'Should have edited service to have the specified path' { - $serviceCimInstance.PathName | Should Be $resourceParameters.Path + $serviceCimInstance.PathName | Should -Be $resourceParameters.Path } It 'Should have edited service to have the specified display name' { - $service.DisplayName | Should Be $resourceParameters.DisplayName + $service.DisplayName | Should -Be $resourceParameters.DisplayName } It 'Should have edited service to have the specified description' { - $serviceCimInstance.Description | Should Be $resourceParameters.Description + $serviceCimInstance.Description | Should -Be $resourceParameters.Description } It 'Should have edited service to have the specified dependencies' { $differentDependencies = Compare-Object -ReferenceObject $resourceParameters.Dependencies -DifferenceObject $service.ServicesDependedOn.Name - $differentDependencies | Should Be $null + $differentDependencies | Should -Be $null } It 'Should not have changed the service state from Running' { - $service.Status | Should Be 'Running' + $service.Status | Should -Be 'Running' } It 'Should not have changed the service startup type from Auto' { - $serviceCimInstance.StartMode | Should Be 'Auto' + $serviceCimInstance.StartMode | Should -Be 'Auto' } It 'Should not have changed the service startup account name from LocalSystem' { - $serviceCimInstance.StartName | Should Be 'LocalSystem' + $serviceCimInstance.StartName | Should -Be 'LocalSystem' } It 'Should not have changed the service desktop interaction setting from False' { - $serviceCimInstance.DesktopInteract | Should Be $false + $serviceCimInstance.DesktopInteract | Should -BeFalse } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should Be $true + MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should -BeTrue } } @@ -253,34 +253,34 @@ try } It 'Should compile and apply the MOF without throwing' { - { + { . $script:configurationAllExceptCredentialFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $service = Get-Service -Name $resourceParameters.Name -ErrorAction 'SilentlyContinue' $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$($resourceParameters.Name)'" -ErrorAction 'SilentlyContinue' It 'Should not have removed service with specified name' { - $service | Should Not Be $null - $serviceCimInstance | Should Not Be $null + $service | Should -Not -Be $null + $serviceCimInstance | Should -Not -Be $null - $service.Name | Should Be $resourceParameters.Name - $serviceCimInstance.Name | Should Be $resourceParameters.Name + $service.Name | Should -Be $resourceParameters.Name + $serviceCimInstance.Name | Should -Be $resourceParameters.Name } It 'Should have edited the service to have the specified state' { - $service.Status | Should Be $resourceParameters.State + $service.Status | Should -Be $resourceParameters.State } It 'Should have edited the service to have the specified startup type' { - $serviceCimInstance.StartMode | Should Be $resourceParameters.StartupType + $serviceCimInstance.StartMode | Should -Be $resourceParameters.StartupType } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should Be $true + MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should -BeTrue } } @@ -303,22 +303,22 @@ try } It 'Should compile and apply the MOF without throwing' { - { + { . $script:configurationCredentialOnlyFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $configData @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $service = Get-Service -Name $resourceParameters.Name -ErrorAction 'SilentlyContinue' $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$($resourceParameters.Name)'" -ErrorAction 'SilentlyContinue' It 'Should not have removed service with specified name' { - $service | Should Not Be $null - $serviceCimInstance | Should Not Be $null + $service | Should -Not -Be $null + $serviceCimInstance | Should -Not -Be $null - $service.Name | Should Be $resourceParameters.Name - $serviceCimInstance.Name | Should Be $resourceParameters.Name + $service.Name | Should -Be $resourceParameters.Name + $serviceCimInstance.Name | Should -Be $resourceParameters.Name } It 'Should have edited the service to have the specified startup account name' { @@ -329,11 +329,11 @@ try $expectedStartName = $expectedStartName.TrimStart("$env:COMPUTERNAME\") } - $serviceCimInstance.StartName | Should Be ".\$expectedStartName" + $serviceCimInstance.StartName | Should -Be ".\$expectedStartName" } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should Be $true + MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should -BeTrue } } @@ -348,30 +348,30 @@ try } It 'Should compile and apply the MOF without throwing' { - { + { . $script:configurationAllExceptCredentialFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $service = Get-Service -Name $resourceParameters.Name -ErrorAction 'SilentlyContinue' $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$($resourceParameters.Name)'" -ErrorAction 'SilentlyContinue' It 'Should not have removed service with specified name' { - $service | Should Not Be $null - $serviceCimInstance | Should Not Be $null + $service | Should -Not -Be $null + $serviceCimInstance | Should -Not -Be $null - $service.Name | Should Be $resourceParameters.Name - $serviceCimInstance.Name | Should Be $resourceParameters.Name + $service.Name | Should -Be $resourceParameters.Name + $serviceCimInstance.Name | Should -Be $resourceParameters.Name } It 'Should have edited the service to have the specified startup account name' { - $serviceCimInstance.StartName | Should Be 'NT Authority\LocalService' + $serviceCimInstance.StartName | Should -Be 'NT Authority\LocalService' } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should Be $true + MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should -BeTrue } } @@ -386,23 +386,23 @@ try } It 'Should compile and apply the MOF without throwing' { - { + { . $script:configurationAllExceptCredentialFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $service = Get-Service -Name $resourceParameters.Name -ErrorAction 'SilentlyContinue' $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$($resourceParameters.Name)'" -ErrorAction 'SilentlyContinue' It 'Should have removed the service with specified name' { - $service | Should Be $null - $serviceCimInstance | Should Be $null + $service | Should -Be $null + $serviceCimInstance | Should -Be $null } It 'Should return true from Test-TargetResource with the same parameters' { - MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should Be $true + MSFT_ServiceResource\Test-TargetResource @resourceParameters | Should -BeTrue } } } diff --git a/Tests/Integration/MSFT_ServiceResource_AllExceptCredential.config.ps1 b/Tests/Integration/MSFT_ServiceResource_AllExceptCredential.config.ps1 index 8311b7e..0eb1141 100644 --- a/Tests/Integration/MSFT_ServiceResource_AllExceptCredential.config.ps1 +++ b/Tests/Integration/MSFT_ServiceResource_AllExceptCredential.config.ps1 @@ -1,7 +1,7 @@ param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,58 +11,58 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [ValidateSet('Present', 'Absent')] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Ensure = 'Present', [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $DisplayName = "$Name DisplayName", [Parameter()] - [String] + [System.String] $Description = 'TestDescription', [Parameter()] - [String[]] + [System.String[]] [AllowEmptyCollection()] $Dependencies = @(), [Parameter()] [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')] - [String] + [System.String] $BuiltInAccount = 'LocalSystem', [Parameter()] - [Boolean] + [System.Boolean] $DesktopInteract = $false, [Parameter()] [ValidateSet('Automatic', 'Manual', 'Disabled')] - [String] + [System.String] $StartupType = 'Automatic', [Parameter()] [ValidateSet('Running', 'Stopped', 'Ignore')] - [String] + [System.String] $State = 'Running', [Parameter()] - [UInt32] + [System.UInt32] $StartupTimeout = 30000, [Parameter()] - [UInt32] + [System.UInt32] $TerminateTimeout = 30000 ) diff --git a/Tests/Integration/MSFT_ServiceResource_CredentialOnly.config.ps1 b/Tests/Integration/MSFT_ServiceResource_CredentialOnly.config.ps1 index 4a49e23..dc1dcf4 100644 --- a/Tests/Integration/MSFT_ServiceResource_CredentialOnly.config.ps1 +++ b/Tests/Integration/MSFT_ServiceResource_CredentialOnly.config.ps1 @@ -1,7 +1,7 @@ param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,12 +11,12 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [ValidateSet('Present', 'Absent')] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Ensure = 'Present', [Parameter(Mandatory = $true)] diff --git a/Tests/Integration/MSFT_UserResource.Integration.Tests.ps1 b/Tests/Integration/MSFT_UserResource.Integration.Tests.ps1 index af67b9e..c6dd376 100644 --- a/Tests/Integration/MSFT_UserResource.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_UserResource.Integration.Tests.ps1 @@ -1,8 +1,8 @@ <# To run these tests, the currently logged on user must have rights to create a user. - These integration tests cover creating a brand new user, updating values + These integration tests cover creating a brand new user, updating values of a user that already exists, and deleting a user that exists. -#> +#> # Suppressing this rule since we need to create a plaintext password to test this resource [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] @@ -45,13 +45,13 @@ try } $script:logPath = Join-Path -Path $TestDrive -ChildPath 'NewUser.log' - + $script:testUserName = 'TestUserName12345' $script:testPassword = 'StrongOne7.' $script:testDescription = 'Test Description' $script:newTestDescription = 'New Test Description' $script:secureTestPassword = ConvertTo-SecureString $script:testPassword -AsPlainText -Force - $script:testCredential = New-Object PSCredential ($script:testUserName, $script:secureTestPassword) + $script:testCredential = New-Object PSCredential ($script:testUserName, $script:secureTestPassword) Context 'Should create a new user' { $configurationName = 'MSFT_User_NewUser' @@ -67,23 +67,23 @@ try -Description $script:testDescription ` -OutputPath $configurationPath ` -ConfigurationData $script:configData ` - -ErrorAction 'Stop' + -ErrorAction Stop Start-DscConfiguration -Path $configurationPath -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } - + It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction Stop } | Should -Not -Throw } - + It 'Should return the correct configuration' { - $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' + $currentConfig = Get-DscConfiguration -ErrorAction Stop $currentConfig.UserName | Should Be $script:testUserName - $currentConfig.Ensure | Should Be 'Present' + $currentConfig.Ensure | Should -Be 'Present' $currentConfig.Description | Should Be $script:testDescription - $currentConfig.PasswordNeverExpires | Should Be $false - $currentConfig.Disabled | Should Be $false - $currentConfig.PasswordChangeRequired | Should Be $null + $currentConfig.PasswordNeverExpires | Should -BeFalse + $currentConfig.Disabled | Should -BeFalse + $currentConfig.PasswordChangeRequired | Should -Be $null } } finally @@ -98,7 +98,7 @@ try } } } - + Context 'Should update Description of an existing user' { $configurationName = 'MSFT_User_UpdateUserDescription' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName @@ -122,14 +122,14 @@ try It 'Should be able to call Get-DscConfiguration without throwing' { { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw } - + It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' $currentConfig.UserName | Should Be $script:testUserName $currentConfig.Ensure | Should Be 'Present' $currentConfig.Description | Should Be $newTestDescription - $currentConfig.PasswordNeverExpires | Should Be $false - $currentConfig.Disabled | Should Be $false + $currentConfig.PasswordNeverExpires | Should -BeFalse + $currentConfig.Disabled | Should -BeFalse $currentConfig.PasswordChangeRequired | Should Be $null } } @@ -163,24 +163,24 @@ try -PasswordNeverExpires $true ` -OutputPath $configurationPath ` -ConfigurationData $script:configData ` - -ErrorAction 'Stop' + -ErrorAction Stop Start-DscConfiguration -Path $configurationPath -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction Stop } | Should -Not -Throw } - + It 'Should return the correct configuration' { - $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' + $currentConfig = Get-DscConfiguration -ErrorAction Stop $currentConfig.UserName | Should Be $script:testUserName - $currentConfig.Ensure | Should Be 'Present' + $currentConfig.Ensure | Should -Be 'Present' $currentConfig.Description | Should Be $script:testDescription $currentConfig.FullName | Should Be $newFullName - $currentConfig.PasswordNeverExpires | Should Be $true - $currentConfig.Disabled | Should Be $false - $currentConfig.PasswordChangeRequired | Should Be $null + $currentConfig.PasswordNeverExpires | Should -BeTrue + $currentConfig.Disabled | Should -BeFalse + $currentConfig.PasswordChangeRequired | Should -Be $null } } finally @@ -195,7 +195,7 @@ try } } } - + Context 'Should delete an existing user' { $configurationName = 'MSFT_User_DeleteUser' $configurationPath = Join-Path -Path $TestDrive -ChildPath $configurationName @@ -210,19 +210,19 @@ try -OutputPath $configurationPath ` -ConfigurationData $script:configData ` -Ensure 'Absent' ` - -ErrorAction 'Stop' + -ErrorAction Stop Start-DscConfiguration -Path $configurationPath -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction Stop } | Should -Not -Throw } - + It 'Should return the correct configuration' { - $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' + $currentConfig = Get-DscConfiguration -ErrorAction Stop $currentConfig.UserName | Should Be $script:testUserName - $currentConfig.Ensure | Should Be 'Absent' + $currentConfig.Ensure | Should -Be 'Absent' } } finally diff --git a/Tests/Integration/MSFT_UserResource.config.ps1 b/Tests/Integration/MSFT_UserResource.config.ps1 index cd33399..8dbdea1 100644 --- a/Tests/Integration/MSFT_UserResource.config.ps1 +++ b/Tests/Integration/MSFT_UserResource.config.ps1 @@ -1,30 +1,30 @@ - + # Integration Test Config Template Version 1.0.0 -param +param ( [Parameter(Mandatory = $true)] [System.String] $ConfigurationName ) - + Configuration $ConfigurationName { - param - ( + param + ( [System.String] $UserName = 'Test UserName', - + [System.String] $Description = 'Test Description', - + [System.String] $FullName = 'Test Full Name', - + [ValidateSet('Present', 'Absent')] [System.String] $Ensure = 'Present', - + [Parameter(Mandatory = $true)] [System.Management.Automation.PSCredential] [System.Management.Automation.Credential()] @@ -33,9 +33,9 @@ Configuration $ConfigurationName [Boolean] $PasswordNeverExpires = $false ) - + Import-DscResource -ModuleName 'PSDscResources' - + Node localhost { User UserResource1 diff --git a/Tests/Integration/MSFT_WindowsFeature.Integration.Tests.ps1 b/Tests/Integration/MSFT_WindowsFeature.Integration.Tests.ps1 index cbf4ce4..edc0ba2 100644 --- a/Tests/Integration/MSFT_WindowsFeature.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_WindowsFeature.Integration.Tests.ps1 @@ -1,10 +1,10 @@ -<# +<# Integration tests for installing/uninstalling a Windows Feature. Currently Telnet-Client is set as the feature to test since it's fairly small and doesn't require a restart. ADRMS is set as the feature to test installing/uninstalling a feature with subfeatures, but this takes a good chunk of time, so by default these tests are set to be skipped. If there's any major changes to the resource, then set the skipLongTests variable to $false - and run those tests at least once to test the new functionality more completely. + and run those tests at least once to test the new functionality more completely. #> # Suppressing this rule since we need to create a plaintext password to test this resource @@ -45,7 +45,7 @@ try $script:testFeatureName = 'Telnet-Client' $script:testFeatureWithSubFeaturesName = 'RSAT-File-Services' - #Saving the state so we can clean up afterwards + # Saving the state so we can clean up afterwards $testFeature = Get-WindowsFeature -Name $script:testFeatureName $script:installStateOfTestFeature = $testFeature.Installed @@ -103,23 +103,23 @@ try -OutputPath $configurationPath ` -ErrorAction 'Stop' Start-DscConfiguration -Path $configurationPath -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } - + It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should Be $script:testFeatureName - $currentConfig.IncludeAllSubFeature | Should Be $false - $currentConfig.Ensure | Should Be 'Present' + $currentConfig.Name | Should -Be $script:testFeatureName + $currentConfig.IncludeAllSubFeature | Should -BeFalse + $currentConfig.Ensure | Should -Be 'Present' } It 'Should be Installed' { $feature = Get-WindowsFeature -Name $script:testFeatureName - $feature.Installed | Should Be $true + $feature.Installed | Should -BeTrue } } finally @@ -152,23 +152,23 @@ try -OutputPath $configurationPath ` -ErrorAction 'Stop' Start-DscConfiguration -Path $configurationPath -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } It 'Should be able to call Get-DscConfiguration without throwing' { - { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw + { Get-DscConfiguration -ErrorAction 'Stop' } | Should -Not -Throw } - + It 'Should return the correct configuration' { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' - $currentConfig.Name | Should Be $script:testFeatureName - $currentConfig.IncludeAllSubFeature | Should Be $false - $currentConfig.Ensure | Should Be 'Absent' + $currentConfig.Name | Should -Be $script:testFeatureName + $currentConfig.IncludeAllSubFeature | Should -BeFalse + $currentConfig.Ensure | Should -Be 'Absent' } It 'Should not be installed' { $feature = Get-WindowsFeature -Name $script:testFeatureName - $feature.Installed | Should Be $false + $feature.Installed | Should -BeFalse } } finally @@ -187,7 +187,7 @@ try <# This test triggers a pending reboot on the machine which crashes the WindowsFeatureSet and WindowsOptionalFeatureSet tests on AppVeyor. - + If anyone knows of a Windows Feature that exists on Server 2012 R2, does not require a reboot, and has subfeatures, please update $script:testFeatureWithSubFeaturesName with the name of that feature and turn these tests back on in AppVeyor @@ -221,22 +221,22 @@ try It 'Should be able to call Get-DscConfiguration without throwing' -Skip:$script:skipLongTests { { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw } - + It 'Should return the correct configuration' -Skip:$script:skipLongTests { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' $currentConfig.Name | Should Be $script:testFeatureWithSubFeaturesName - $currentConfig.IncludeAllSubFeature | Should Be $true + $currentConfig.IncludeAllSubFeature | Should -BeTrue $currentConfig.Ensure | Should Be 'Present' } It 'Should be Installed (includes check for subFeatures)' -Skip:$script:skipLongTests { $feature = Get-WindowsFeature -Name $script:testFeatureWithSubFeaturesName - $feature.Installed | Should Be $true + $feature.Installed | Should -BeTrue foreach ($subFeatureName in $feature.SubFeatures) { $subFeature = Get-WindowsFeature -Name $subFeatureName - $subFeature.Installed | Should Be $true + $subFeature.Installed | Should -BeTrue } } } @@ -262,22 +262,22 @@ try It 'Should be able to call Get-DscConfiguration without throwing' -Skip:$script:skipLongTests { { Get-DscConfiguration -ErrorAction 'Stop' } | Should Not Throw } - + It 'Should return the correct configuration' -Skip:$script:skipLongTests { $currentConfig = Get-DscConfiguration -ErrorAction 'Stop' $currentConfig.Name | Should Be $script:testFeatureWithSubFeaturesName - $currentConfig.IncludeAllSubFeature | Should Be $false + $currentConfig.IncludeAllSubFeature | Should -BeFalse $currentConfig.Ensure | Should Be 'Absent' } It 'Should not be installed (includes check for subFeatures)' -Skip:$script:skipLongTests { $feature = Get-WindowsFeature -Name $script:testFeatureWithSubFeaturesName - $feature.Installed | Should Be $false + $feature.Installed | Should -BeFalse foreach ($subFeatureName in $feature.SubFeatures) { $subFeature = Get-WindowsFeature -Name $subFeatureName - $subFeature.Installed | Should Be $false + $subFeature.Installed | Should -BeFalse } } } diff --git a/Tests/Integration/MSFT_WindowsFeature.config.ps1 b/Tests/Integration/MSFT_WindowsFeature.config.ps1 index 149a631..55ca249 100644 --- a/Tests/Integration/MSFT_WindowsFeature.config.ps1 +++ b/Tests/Integration/MSFT_WindowsFeature.config.ps1 @@ -1,4 +1,4 @@ -param +param ( [Parameter(Mandatory)] [System.String] @@ -8,8 +8,8 @@ Configuration $ConfigurationName { param - ( - [Parameter(Mandatory = $true)] + ( + [Parameter(Mandatory = $true)] [System.String] $Name, @@ -20,9 +20,9 @@ Configuration $ConfigurationName [System.Boolean] $IncludeAllSubFeature = $false ) - + Import-DscResource -ModuleName 'PSDscResources' - + Node Localhost { WindowsFeature WindowsFeatureTest diff --git a/Tests/Integration/MSFT_WindowsOptionalFeature.Integration.Tests.ps1 b/Tests/Integration/MSFT_WindowsOptionalFeature.Integration.Tests.ps1 index 6ddcf2e..8addf02 100644 --- a/Tests/Integration/MSFT_WindowsOptionalFeature.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_WindowsOptionalFeature.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -if ($PSVersionTable.PSVersion -lt [Version] '5.1') +if ($PSVersionTable.PSVersion -lt [Version] '5.1') { Write-Warning -Message 'Cannot run PSDscResources integration tests on PowerShell versions lower than 5.1' return @@ -25,7 +25,7 @@ try $script:confgurationFilePath = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_WindowsOptionalFeature.config.ps1' } - + It 'Should enable a valid Windows optional feature' { $configurationName = 'EnableWindowsOptionalFeature' @@ -45,16 +45,16 @@ try Dism\Disable-WindowsOptionalFeature -FeatureName $resourceParameters.Name -Online -NoRestart } - { + { . $script:confgurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -FeatureName $resourceParameters.Name -Online - $windowsOptionalFeature | Should Not Be $null - $windowsOptionalFeature.State -in $script:enabledStates | Should Be $true + $windowsOptionalFeature | Should -Not -Be $null + $windowsOptionalFeature.State -in $script:enabledStates | Should -BeTrue } finally { @@ -94,16 +94,16 @@ try Dism\Enable-WindowsOptionalFeature -FeatureName $resourceParameters.Name -Online -NoRestart } - { + { . $script:confgurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -FeatureName $resourceParameters.Name -Online - $windowsOptionalFeature | Should Not Be $null - $windowsOptionalFeature.State -in $script:disabledStates | Should Be $true + $windowsOptionalFeature | Should -Not -Be $null + $windowsOptionalFeature.State -in $script:disabledStates | Should -BeTrue } finally { @@ -133,19 +133,19 @@ try NoWindowsUpdateCheck = $true } - Dism\Get-WindowsOptionalFeature -FeatureName $resourceParameters.Name -Online | Should Be $null + Dism\Get-WindowsOptionalFeature -FeatureName $resourceParameters.Name -Online | Should -Be $null try { - { + { . $script:confgurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Throw "Feature name $($resourceParameters.Name) is unknown." + } | Should -Throw "Feature name $($resourceParameters.Name) is unknown." - Test-Path -Path $resourceParameters.LogPath | Should Be $true + Test-Path -Path $resourceParameters.LogPath | Should -BeTrue - Dism\Get-WindowsOptionalFeature -FeatureName $resourceParameters.Name -Online | Should Be $null + Dism\Get-WindowsOptionalFeature -FeatureName $resourceParameters.Name -Online | Should -Be $null } finally { diff --git a/Tests/Integration/MSFT_WindowsOptionalFeature.config.ps1 b/Tests/Integration/MSFT_WindowsOptionalFeature.config.ps1 index dd59b61..772087d 100644 --- a/Tests/Integration/MSFT_WindowsOptionalFeature.config.ps1 +++ b/Tests/Integration/MSFT_WindowsOptionalFeature.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,22 +11,22 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [ValidateSet('Present', 'Absent')] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Ensure = 'Present', [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath = (Join-Path -Path (Get-Location) -ChildPath 'WOFTestLog.txt'), - [Boolean] + [System.Boolean] $RemoveFilesOnDisable = $false, - [Boolean] + [System.Boolean] $NoWindowsUpdateCheck = $true ) diff --git a/Tests/Integration/MSFT_WindowsPackageCab.Integration.Tests.ps1 b/Tests/Integration/MSFT_WindowsPackageCab.Integration.Tests.ps1 index 77493bd..a58ef0d 100644 --- a/Tests/Integration/MSFT_WindowsPackageCab.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_WindowsPackageCab.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -if ($PSVersionTable.PSVersion -lt [Version] '5.1') +if ($PSVersionTable.PSVersion -lt [Version] '5.1') { Write-Warning -Message 'Cannot run PSDscResources integration tests on PowerShell versions lower than 5.1' return @@ -21,14 +21,14 @@ try Describe 'WindowsPackageCab Integration Tests' { BeforeAll { Import-Module -Name 'Dism' - + $script:installedStates = @( 'Installed', 'InstallPending' ) $script:confgurationFilePath = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_WindowsPackageCab.config.ps1' - $script:testPackageName = '' + $script:testPackageName = '' $script:testSourcePath = Join-Path -Path $PSScriptRoot -ChildPath '' - $script:cabPackageNotProvided = $script:testPackageName -eq [String]::Empty + $script:cabPackageNotProvided = $script:testPackageName -eq [System.String]::Empty try { @@ -58,7 +58,7 @@ try { try { - $windowsPackage = Dism\Get-WindowsPackage -PackageName $script:testPackageName -Online + $windowsPackage = Dism\Get-WindowsPackage -PackageName $script:testPackageName -Online if ($null -ne $windowsPackage -and $windowsPackage.PackageState -in $script:installedStates) { Dism\Remove-WindowsPackage -PackageName $script:testPackageName.Name -Online -NoRestart @@ -70,7 +70,7 @@ try } } } - + It 'Should install a Windows package through a cab file' -Skip:$script:cabPackageNotProvided { $configurationName = 'InstallWindowsPackageCab' @@ -80,17 +80,17 @@ try Ensure = 'Present' } - { + { . $script:confgurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw - { $windowsPackage = Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should Not Throw + { $null = Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should -Not -Throw $windowsPackage = Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online - $windowsPackage | Should Not Be $null - $windowsPackage.PackageState -in $script:installedStates | Should Be $true + $windowsPackage | Should -Not -Be $null + $windowsPackage.PackageState -in $script:installedStates | Should -BeTrue } It 'Should uninstall a Windows package through a cab file' -Skip:$script:cabPackageNotProvided { @@ -104,15 +104,15 @@ try Dism\Add-WindowsPackage -PackagePath $resourceParameters.SourcePath -Online -NoRestart - { $windowsPackage = Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should Not Throw + { $null = Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should -Not -Throw - { + { . $script:confgurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw - { $windowsPackage = Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should Throw + { $null = Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should -Throw } It 'Should not install an invalid Windows package through a cab file' { @@ -125,17 +125,17 @@ try LogPath = (Join-Path -Path $TestDrive -ChildPath 'InvalidWindowsPackageCab.log') } - { Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should Throw + { Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should -Throw - { + { . $script:confgurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Throw + } | Should -Throw - Test-Path -Path $resourceParameters.LogPath | Should Be $true + Test-Path -Path $resourceParameters.LogPath | Should -BeTrue - { Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should Throw + { Dism\Get-WindowsPackage -PackageName $resourceParameters.Name -Online } | Should -Throw } } } diff --git a/Tests/Integration/MSFT_WindowsPackageCab.config.ps1 b/Tests/Integration/MSFT_WindowsPackageCab.config.ps1 index 94fc5b2..a4da977 100644 --- a/Tests/Integration/MSFT_WindowsPackageCab.config.ps1 +++ b/Tests/Integration/MSFT_WindowsPackageCab.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,21 +11,21 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Name, [Parameter(Mandatory = $true)] [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $SourcePath, [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath = (Join-Path -Path (Get-Location) -ChildPath 'WindowsPackageCabTestLog.txt') ) diff --git a/Tests/Integration/MSFT_WindowsProcess.Integration.Tests.ps1 b/Tests/Integration/MSFT_WindowsProcess.Integration.Tests.ps1 index 683077a..73acb97 100644 --- a/Tests/Integration/MSFT_WindowsProcess.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_WindowsProcess.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' if ($PSVersionTable.PSVersion -lt [Version] '5.1') @@ -24,7 +24,7 @@ Describe 'WindowsProcess Integration Tests' { $script:logFilePath = Join-Path -Path $TestDrive -ChildPath 'ProcessTestLog.txt' $script:configurationFilePathNoCredential = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_WindowsProcess_NoCredential.config.ps1' - $script:configurationFilePathWithCredential = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_WindowsProcess_WithCredential.config.ps1' + $script:configurationFilePathWithCredential = Join-Path -Path $PSScriptRoot -ChildPath 'MSFT_WindowsProcess_WithCredential.config.ps1' $null = Stop-Process -Name $script:testProcessName -Force -ErrorAction 'SilentlyContinue' } @@ -55,11 +55,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -68,7 +68,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should not be able to retrieve the process after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Throw } @@ -86,7 +86,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } } @@ -110,11 +110,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -123,7 +123,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should be able to retrieve the process after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Not Throw } @@ -142,7 +142,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } } @@ -171,11 +171,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -184,7 +184,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should be able to retrieve the process after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Not Throw } @@ -203,7 +203,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } } @@ -232,14 +232,14 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } # Remove the created log file so that we can check that the configuration did not re-create it $null = Remove-Item -Path $script:logFilePath -Force -ErrorAction 'SilentlyContinue' It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -248,7 +248,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should not be able to retrieve the process after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Throw } @@ -266,7 +266,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } } @@ -290,11 +290,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -308,7 +308,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the second process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should be able to retrieve the processes after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Not Throw } @@ -327,7 +327,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } } @@ -361,14 +361,14 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } # Remove the created log file so that we can check that the configuration did not re-create it $null = Remove-Item -Path $script:logFilePath -Force -ErrorAction 'SilentlyContinue' It 'Should compile and run configuration' { - { + { . $script:configurationFilePathNoCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -395,11 +395,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } } } - + if ($env:AppVeyor) { Describe 'Credential provided - Only runs in AppVeyor' { $script:testCredential = Get-AppVeyorAdministratorCredential @@ -437,11 +437,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathWithCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $script:credentialConfigurationData @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -450,7 +450,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should not be able to retrieve the process after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Throw } @@ -468,7 +468,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } } @@ -493,11 +493,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathWithCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $script:credentialConfigurationData @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -506,7 +506,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should be able to retrieve the process after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Not Throw } @@ -525,7 +525,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } } @@ -555,11 +555,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathWithCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $script:credentialConfigurationData @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -568,7 +568,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should be able to retrieve the process after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Not Throw } @@ -587,7 +587,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } } @@ -617,14 +617,14 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } # Remove the created log file so that we can check that the configuration did not re-create it $null = Remove-Item -Path $script:logFilePath -Force -ErrorAction 'SilentlyContinue' It 'Should compile and run configuration' { - { + { . $script:configurationFilePathWithCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $script:credentialConfigurationData @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -633,7 +633,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should not be able to retrieve the process after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Throw } @@ -651,7 +651,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } } @@ -676,11 +676,11 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } It 'Should compile and run configuration' { - { + { . $script:configurationFilePathWithCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $script:credentialConfigurationData @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -694,7 +694,7 @@ Describe 'WindowsProcess Integration Tests' { # Wait a moment for the second process to stop/start $null = Start-Sleep -Seconds 1 - + It 'Should be able to retrieve the processes after configuration' { { $null = Get-Process -Name $script:testProcessName } | Should Not Throw } @@ -713,7 +713,7 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } } @@ -748,14 +748,14 @@ Describe 'WindowsProcess Integration Tests' { It 'Should be able to find the log file before configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $true + $pathResult | Should -BeTrue } # Remove the created log file so that we can check that the configuration did not re-create it $null = Remove-Item -Path $script:logFilePath -Force -ErrorAction 'SilentlyContinue' It 'Should compile and run configuration' { - { + { . $script:configurationFilePathWithCredential -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $script:credentialConfigurationData @processParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force @@ -782,10 +782,10 @@ Describe 'WindowsProcess Integration Tests' { It 'Should not be able to find the log file after configuration' { $pathResult = Test-Path -Path $logFilePath - $pathResult | Should Be $false + $pathResult | Should -BeFalse } } } } } - + diff --git a/Tests/Integration/MSFT_WindowsProcess_NoCredential.config.ps1 b/Tests/Integration/MSFT_WindowsProcess_NoCredential.config.ps1 index f3e2b9a..858dbb3 100644 --- a/Tests/Integration/MSFT_WindowsProcess_NoCredential.config.ps1 +++ b/Tests/Integration/MSFT_WindowsProcess_NoCredential.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,16 +11,16 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [AllowEmptyString()] - [String] + [System.String] $Arguments, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present' ) diff --git a/Tests/Integration/MSFT_WindowsProcess_WithCredential.config.ps1 b/Tests/Integration/MSFT_WindowsProcess_WithCredential.config.ps1 index 38e5b07..a12e918 100644 --- a/Tests/Integration/MSFT_WindowsProcess_WithCredential.config.ps1 +++ b/Tests/Integration/MSFT_WindowsProcess_WithCredential.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,16 +11,16 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Path, [Parameter(Mandatory = $true)] [AllowEmptyString()] - [String] + [System.String] $Arguments, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [Parameter(Mandatory = $true)] diff --git a/Tests/Integration/ProcessSet.Integration.Tests.ps1 b/Tests/Integration/ProcessSet.Integration.Tests.ps1 index 9a53a9e..9e6f19f 100644 --- a/Tests/Integration/ProcessSet.Integration.Tests.ps1 +++ b/Tests/Integration/ProcessSet.Integration.Tests.ps1 @@ -1,4 +1,4 @@ - + if ($PSVersionTable.PSVersion -lt [Version] '5.1') { Write-Warning -Message 'Cannot run PSDscResources integration tests on PowerShell versions lower than 5.1' @@ -72,16 +72,16 @@ try } It "Should not have started process $processName before configuration" { - $process | Should Be $null + $process | Should -Be $null } } It 'Should compile and run configuration' { - { + { . $script:configurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @processSetParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } foreach ($processPath in $processSetParameters.ProcessPaths) @@ -90,7 +90,7 @@ try $process = Get-Process -Name $processName -ErrorAction 'SilentlyContinue' It "Should have started process $processName after configuration" { - $process | Should Not Be $null + $process | Should -Not -Be $null } } } @@ -123,16 +123,16 @@ try } It "Should have started process $processName before configuration" { - $process | Should Not Be $null + $process | Should -Not -Be $null } } It 'Should compile and run configuration' { - { + { . $script:configurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @processSetParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } foreach ($processPath in $processSetParameters.ProcessPaths) @@ -141,7 +141,7 @@ try $process = Get-Process -Name $processName -ErrorAction 'SilentlyContinue' It "Should have stopped process $processName after configuration" { - $process | Should Be $null + $process | Should -Be $null } } } diff --git a/Tests/Integration/ProcessSet.config.ps1 b/Tests/Integration/ProcessSet.config.ps1 index 6c36f61..8f60920 100644 --- a/Tests/Integration/ProcessSet.config.ps1 +++ b/Tests/Integration/ProcessSet.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,11 +11,11 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $ProcessPaths, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present' ) diff --git a/Tests/Integration/ServiceSet.Integration.Tests.ps1 b/Tests/Integration/ServiceSet.Integration.Tests.ps1 index b4c7b80..6d9f33e 100644 --- a/Tests/Integration/ServiceSet.Integration.Tests.ps1 +++ b/Tests/Integration/ServiceSet.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -<# +<# These tests should only be run in AppVeyor since they currently require the AppVeyor administrator account credential to run. @@ -143,30 +143,30 @@ try } It 'Should compile and apply the MOF without throwing' { - { + { . $script:confgurationFilePathAllExceptBuiltInAccount -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive -ConfigurationData $configData @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $service = Get-Service -Name $resourceParameters.Name[0] -ErrorAction 'SilentlyContinue' $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$($resourceParameters.Name[0])'" -ErrorAction 'SilentlyContinue' It 'Should not have removed service with the specified name' { - $service | Should Not Be $null - $serviceCimInstance | Should Not Be $null + $service | Should -Not -Be $null + $serviceCimInstance | Should -Not -Be $null - $service.Name | Should Be $resourceParameters.Name[0] - $serviceCimInstance.Name | Should Be $resourceParameters.Name[0] + $service.Name | Should -Be $resourceParameters.Name[0] + $serviceCimInstance.Name | Should -Be $resourceParameters.Name[0] } It 'Should have set the service state to the specified state' { - $service.Status | Should Be $resourceParameters.State + $service.Status | Should -Be $resourceParameters.State } It 'Should have set the service startup type to the specified startup type' { - $serviceCimInstance.StartMode | Should Be $resourceParameters.StartupType + $serviceCimInstance.StartMode | Should -Be $resourceParameters.StartupType } It 'Should have set the service start name to the appveyor account name' { @@ -185,11 +185,11 @@ try } It 'Should compile and apply the MOF without throwing' { - { + { . $script:confgurationFilePathBuiltInAccountOnly -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $serviceCount = 1 @@ -200,19 +200,19 @@ try $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$serviceName'" -ErrorAction 'SilentlyContinue' It "Should not have removed service $serviceCount" { - $service | Should Not Be $null - $serviceCimInstance | Should Not Be $null + $service | Should -Not -Be $null + $serviceCimInstance | Should -Not -Be $null - $service.Name | Should Be $serviceName - $serviceCimInstance.Name | Should Be $serviceName + $service.Name | Should -Be $serviceName + $serviceCimInstance.Name | Should -Be $serviceName } It "Should have set the state of service $serviceCount to Running (default action of Service)" { - $service.Status | Should Be 'Running' + $service.Status | Should -Be 'Running' } It "Should have set the start name of service $serviceCount to the specified built-in account name" { - $serviceCimInstance.StartName | Should Be $resourceParameters.BuiltInAccount + $serviceCimInstance.StartName | Should -Be $resourceParameters.BuiltInAccount } $serviceCount += 1 @@ -230,11 +230,11 @@ try } It 'Should compile and apply the MOF without throwing' { - { + { . $script:confgurationFilePathBuiltInAccountOnly -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @resourceParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } $serviceCount = 1 @@ -245,8 +245,8 @@ try $serviceCimInstance = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$serviceName'" -ErrorAction 'SilentlyContinue' It "Should have removed service $serviceCount" { - $service | Should Be $null - $serviceCimInstance | Should Be $null + $service | Should -Be $null + $serviceCimInstance | Should -Be $null } $serviceCount += 1 diff --git a/Tests/Integration/ServiceSet_AllExceptBuiltInAccount.config.ps1 b/Tests/Integration/ServiceSet_AllExceptBuiltInAccount.config.ps1 index e839623..88f1c1b 100644 --- a/Tests/Integration/ServiceSet_AllExceptBuiltInAccount.config.ps1 +++ b/Tests/Integration/ServiceSet_AllExceptBuiltInAccount.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,12 +11,12 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Name, [ValidateSet('Present', 'Absent')] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Ensure = 'Present', [Parameter(Mandatory = $true)] @@ -26,11 +26,11 @@ Configuration $ConfigurationName $Credential, [ValidateSet('Running', 'Stopped', 'Ignore')] - [String] + [System.String] $State = 'Running', [ValidateSet('Automatic', 'Manual', 'Disabled')] - [String] + [System.String] $StartupType = 'Automatic' ) @@ -44,7 +44,7 @@ Configuration $ConfigurationName Ensure = $Ensure Credential = $Credential State = $State - StartupType = $StartupType + StartupType = $StartupType } } } diff --git a/Tests/Integration/ServiceSet_BuiltInAccountOnly.config.ps1 b/Tests/Integration/ServiceSet_BuiltInAccountOnly.config.ps1 index c85009c..3cdfd84 100644 --- a/Tests/Integration/ServiceSet_BuiltInAccountOnly.config.ps1 +++ b/Tests/Integration/ServiceSet_BuiltInAccountOnly.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,17 +11,17 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $Name, [ValidateSet('Present', 'Absent')] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Ensure = 'Present', [Parameter(Mandatory = $true)] [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')] - [String] + [System.String] $BuiltInAccount ) diff --git a/Tests/Integration/WindowsFeatureSet.Integration.Tests.ps1 b/Tests/Integration/WindowsFeatureSet.Integration.Tests.ps1 index 2b5edb6..66e8b39 100644 --- a/Tests/Integration/WindowsFeatureSet.Integration.Tests.ps1 +++ b/Tests/Integration/WindowsFeatureSet.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -if ($PSVersionTable.PSVersion -lt [Version] '5.1') +if ($PSVersionTable.PSVersion -lt [Version] '5.1') { Write-Warning -Message 'Cannot run PSDscResources integration tests on PowerShell versions lower than 5.1' return @@ -62,7 +62,7 @@ try $windowsFeature = Get-WindowsFeature -Name $windowsFeatureName It "Should be able to retrieve Windows feature $windowsFeatureName before the configuration" { - $windowsFeature | Should Not Be $null + $windowsFeature | Should -Not -Be $null } if ($windowsFeature.Installed) @@ -81,16 +81,16 @@ try } It "Should have uninstalled Windows feature $windowsFeatureName before the configuration" { - $windowsFeature.Installed | Should Be $false + $windowsFeature.Installed | Should -BeFalse } } It 'Should compile and run configuration' { - { + { . $script:configurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @windowsFeatureSetParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } foreach ($windowsFeatureName in $windowsFeatureSetParameters.WindowsFeatureNames) @@ -98,7 +98,7 @@ try $windowsFeature = Get-WindowsFeature -Name $windowsFeatureName It "Should be able to retrieve Windows feature $windowsFeatureName after the configuration" { - $windowsFeature | Should Not Be $null + $windowsFeature | Should -Not -Be $null } if (-not $windowsFeature.Installed) @@ -114,16 +114,16 @@ try } It "Should have installed Windows feature $windowsFeatureName after the configuration" { - $windowsFeature.Installed | Should Be $true + $windowsFeature.Installed | Should -BeTrue } } - + It 'Should have created the log file' { - Test-Path -Path $windowsFeatureSetParameters.LogPath | Should Be $true + Test-Path -Path $windowsFeatureSetParameters.LogPath | Should -BeTrue } It 'Should have created content in the log file' { - Get-Content -Path $windowsFeatureSetParameters.LogPath -Raw | Should Not Be $null + Get-Content -Path $windowsFeatureSetParameters.LogPath -Raw | Should -Not -Be $null } } @@ -141,7 +141,7 @@ try $windowsFeature = Get-WindowsFeature -Name $windowsFeatureName It "Should be able to retrieve Windows feature $windowsFeatureName before the configuration" { - $windowsFeature | Should Not Be $null + $windowsFeature | Should -Not -Be $null } if (-not $windowsFeature.Installed) @@ -160,16 +160,16 @@ try } It "Should have installed Windows feature $windowsFeatureName before the configuration" { - $windowsFeature.Installed | Should Be $true + $windowsFeature.Installed | Should -BeTrue } } It 'Should compile and run configuration' { - { + { . $script:configurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @windowsFeatureSetParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } foreach ($windowsFeatureName in $windowsFeatureSetParameters.WindowsFeatureNames) @@ -177,7 +177,7 @@ try $windowsFeature = Get-WindowsFeature -Name $windowsFeatureName It "Should be able to retrieve Windows feature $windowsFeatureName after the configuration" { - $windowsFeature | Should Not Be $null + $windowsFeature | Should -Not -Be $null } if ($windowsFeature.Installed) @@ -193,16 +193,16 @@ try } It "Should have uninstalled Windows feature $windowsFeatureName after the configuration" { - $windowsFeature.Installed | Should Be $false + $windowsFeature.Installed | Should -BeFalse } } - + It 'Should have created the log file' { - Test-Path -Path $windowsFeatureSetParameters.LogPath | Should Be $true + Test-Path -Path $windowsFeatureSetParameters.LogPath | Should -BeTrue } It 'Should have created content in the log file' { - Get-Content -Path $windowsFeatureSetParameters.LogPath -Raw | Should Not Be $null + Get-Content -Path $windowsFeatureSetParameters.LogPath -Raw | Should -Not -Be $null } } } diff --git a/Tests/Integration/WindowsFeatureSet.config.ps1 b/Tests/Integration/WindowsFeatureSet.config.ps1 index 8f20e3d..0139bd1 100644 --- a/Tests/Integration/WindowsFeatureSet.config.ps1 +++ b/Tests/Integration/WindowsFeatureSet.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,15 +11,15 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $WindowsFeatureNames, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath ) diff --git a/Tests/Integration/WindowsOptionalFeatureSet.Integration.Tests.ps1 b/Tests/Integration/WindowsOptionalFeatureSet.Integration.Tests.ps1 index 8966f61..4ac2561 100644 --- a/Tests/Integration/WindowsOptionalFeatureSet.Integration.Tests.ps1 +++ b/Tests/Integration/WindowsOptionalFeatureSet.Integration.Tests.ps1 @@ -1,4 +1,4 @@ -if ($PSVersionTable.PSVersion -lt [Version] '5.1') +if ($PSVersionTable.PSVersion -lt [Version] '5.1') { Write-Warning -Message 'Cannot run PSDscResources integration tests on PowerShell versions lower than 5.1' return @@ -68,7 +68,7 @@ try $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -Online -FeatureName $windowsOptionalFeatureName It "Should be able to retrieve Windows optional feature $windowsOptionalFeatureName before the configuration" { - $windowsOptionalFeature | Should Not Be $null + $windowsOptionalFeature | Should -Not -Be $null } if ($windowsOptionalFeature.State -in $script:enabledStates) @@ -87,16 +87,16 @@ try } It "Should have disabled Windows optional feature $windowsOptionalFeatureName before the configuration" { - $windowsOptionalFeature.State -in $script:disabledStates | Should Be $true + $windowsOptionalFeature.State -in $script:disabledStates | Should -BeTrue } } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @wofSetParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } foreach ($windowsOptionalFeatureName in $wofSetParameters.WindowsOptionalFeatureNames) @@ -104,7 +104,7 @@ try $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -Online -FeatureName $windowsOptionalFeatureName It "Should be able to retrieve Windows optional feature $windowsOptionalFeatureName after the configuration" { - $windowsOptionalFeature | Should Not Be $null + $windowsOptionalFeature | Should -Not -Be $null } # May need to wait a moment for the correct state to populate @@ -117,16 +117,16 @@ try } It "Should have enabled Windows optional feature $windowsOptionalFeatureName after the configuration" { - $windowsOptionalFeature.State -in $script:enabledStates | Should Be $true + $windowsOptionalFeature.State -in $script:enabledStates | Should -BeTrue } } - + It 'Should have created the log file' { - Test-Path -Path $wofSetParameters.LogPath | Should Be $true + Test-Path -Path $wofSetParameters.LogPath | Should -BeTrue } It 'Should have created content in the log file' { - Get-Content -Path $wofSetParameters.LogPath -Raw | Should Not Be $null + Get-Content -Path $wofSetParameters.LogPath -Raw | Should -Not -Be $null } } @@ -144,7 +144,7 @@ try $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -Online -FeatureName $windowsOptionalFeatureName It "Should be able to retrieve Windows optional feature $windowsOptionalFeatureName before the configuration" { - $windowsOptionalFeature | Should Not Be $null + $windowsOptionalFeature | Should -Not -Be $null } if ($windowsOptionalFeature.State -in $script:disabledStates) @@ -163,16 +163,16 @@ try } It "Should have enabled Windows optional feature $windowsOptionalFeatureName before the configuration" { - $windowsOptionalFeature.State -in $script:enabledStates | Should Be $true + $windowsOptionalFeature.State -in $script:enabledStates | Should -BeTrue } } It 'Should compile and run configuration' { - { + { . $script:confgurationFilePath -ConfigurationName $configurationName & $configurationName -OutputPath $TestDrive @wofSetParameters Start-DscConfiguration -Path $TestDrive -ErrorAction 'Stop' -Wait -Force - } | Should Not Throw + } | Should -Not -Throw } foreach ($windowsOptionalFeatureName in $wofSetParameters.WindowsOptionalFeatureNames) @@ -180,7 +180,7 @@ try $windowsOptionalFeature = Dism\Get-WindowsOptionalFeature -Online -FeatureName $windowsOptionalFeatureName It "Should be able to retrieve Windows optional feature $windowsOptionalFeatureName after the confguration" { - $windowsOptionalFeature | Should Not Be $null + $windowsOptionalFeature | Should -Not -Be $null } # May need to wait a moment for the correct state to populate @@ -193,16 +193,16 @@ try } It "Should have disabled Windows optional feature $windowsOptionalFeatureName after the confguration" { - $windowsOptionalFeature.State -in $script:disabledStates | Should Be $true + $windowsOptionalFeature.State -in $script:disabledStates | Should -BeTrue } } - + It 'Should have created the log file' { - Test-Path -Path $wofSetParameters.LogPath | Should Be $true + Test-Path -Path $wofSetParameters.LogPath | Should -BeTrue } It 'Should have created content in the log file' { - Get-Content -Path $wofSetParameters.LogPath -Raw | Should Not Be $null + Get-Content -Path $wofSetParameters.LogPath -Raw | Should -Not -Be $null } } } diff --git a/Tests/Integration/WindowsOptionalFeatureSet.config.ps1 b/Tests/Integration/WindowsOptionalFeatureSet.config.ps1 index 694887c..ade4296 100644 --- a/Tests/Integration/WindowsOptionalFeatureSet.config.ps1 +++ b/Tests/Integration/WindowsOptionalFeatureSet.config.ps1 @@ -1,7 +1,7 @@ -param +param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $ConfigurationName ) @@ -11,15 +11,15 @@ Configuration $ConfigurationName ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String[]] + [System.String[]] $WindowsOptionalFeatureNames, [ValidateSet('Present', 'Absent')] - [String] + [System.String] $Ensure = 'Present', [ValidateNotNullOrEmpty()] - [String] + [System.String] $LogPath ) diff --git a/Tests/TestHelpers/CommonTestHelper.psm1 b/Tests/TestHelpers/CommonTestHelper.psm1 index c5671e9..3dd236e 100644 --- a/Tests/TestHelpers/CommonTestHelper.psm1 +++ b/Tests/TestHelpers/CommonTestHelper.psm1 @@ -1,4 +1,4 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] param () $errorActionPreference = 'Stop' @@ -10,6 +10,18 @@ Set-StrictMode -Version 'Latest' #> $script:appVeyorAdministratorCredential = $null +<# + This is the name of the magic file that will be written to the .git folder + in DSCResource.Tests to determine the last time it was updated. +#> +$script:dscResourceTestsMagicFile = 'DSC_LAST_FETCH' + +<# + This is the number of minutes after which the DSCResource.Tests + will be updated. +#> +$script:dscResourceTestsRefreshAfterMinutes = 120 + <# String data for unit test names to be used with the generic test functions. Maps command names to the appropriate test names to insert when checking that @@ -65,24 +77,26 @@ Test-Path = test that the path {0} exists #> function Get-TestName { - [OutputType([String])] + [OutputType([System.String])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Command, - [Boolean] + [Parameter()] + [System.Boolean] $IsCalled = $true, - [String] + [Parameter()] + [System.String] $Custom = '' ) $testName = '' - if (-not [String]::IsNullOrEmpty($Custom)) + if (-not [System.String]::IsNullOrEmpty($Custom)) { $testName = ($testStrings.$Command -f $Custom) } @@ -115,7 +129,8 @@ function Invoke-ExpectedMocksAreCalledTest [CmdletBinding()] param ( - [Hashtable[]] + [Parameter()] + [System.Collections.Hashtable[]] $MocksCalled ) @@ -157,7 +172,7 @@ function Invoke-ExpectedMocksAreCalledTest Each item in the array is a hashtable that contains the name of the command being mocked, the number of times it is called (can be 0) and, optionally, an extra custom string to make the test name more descriptive. The custom - string will only work if the command has a corresponding variable in the + string will only work if the command has a corresponding variable in the string data name. .PARAMETER ShouldThrow @@ -171,41 +186,46 @@ function Invoke-ExpectedMocksAreCalledTest The string that should be used to create the name of the test that checks for the correct error being thrown. #> -function Invoke-GenericUnitTest { +function Invoke-GenericUnitTest +{ [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [ScriptBlock] + [System.Management.Automation.ScriptBlock] $Function, [Parameter(Mandatory = $true)] - [Hashtable] + [System.Collections.Hashtable] $FunctionParameters, - [Hashtable[]] + [Parameter()] + [System.Collections.Hashtable[]] $MocksCalled, - [Boolean] + [Parameter()] + [System.Boolean] $ShouldThrow = $false, - [String] + [Parameter()] + [System.String] $ErrorMessage = '', - [String] + [Parameter()] + [System.String] $ErrorTestName = '' ) if ($ShouldThrow) { It "Should throw an error for $ErrorTestName" { - { $null = $($Function.Invoke($FunctionParameters)) } | Should Throw $ErrorMessage + { $null = $($Function.Invoke($FunctionParameters)) } | Should -Throw -ExpectedMessage $ErrorMessage } } else { It 'Should not throw' { - { $null = $($Function.Invoke($FunctionParameters)) } | Should Not Throw + { $null = $($Function.Invoke($FunctionParameters)) } | Should -Not -Throw } } @@ -227,7 +247,7 @@ function Invoke-GenericUnitTest { Each item in the array is a hashtable that contains the name of the command being mocked, the number of times it is called (can be 0) and, optionally, an extra custom string to make the test name more descriptive. The custom - string will only work if the command has a corresponding variable in the + string will only work if the command has a corresponding variable in the string data name. .PARAMETER ExpectedReturnValue @@ -239,19 +259,20 @@ function Invoke-GetTargetResourceUnitTest param ( [Parameter(Mandatory = $true)] - [Hashtable] + [System.Collections.Hashtable] $GetTargetResourceParameters, - [Hashtable[]] + [Parameter()] + [System.Collections.Hashtable[]] $MocksCalled, [Parameter(Mandatory = $true)] - [Hashtable] + [System.Collections.Hashtable] $ExpectedReturnValue ) It 'Should not throw' { - { $null = Get-TargetResource @GetTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @GetTargetResourceParameters } | Should -Not -Throw } Invoke-ExpectedMocksAreCalledTest -MocksCalled $MocksCalled @@ -259,17 +280,17 @@ function Invoke-GetTargetResourceUnitTest $getTargetResourceResult = Get-TargetResource @GetTargetResourceParameters It 'Should return a Hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It "Should return a Hashtable with $($ExpectedReturnValue.Keys.Count) properties" { - $getTargetResourceResult.Keys.Count | Should Be $ExpectedReturnValue.Keys.Count + $getTargetResourceResult.Keys.Count | Should -Be $ExpectedReturnValue.Keys.Count } foreach ($key in $ExpectedReturnValue.Keys) { It "Should return a Hashtable with the $key property as $($ExpectedReturnValue.$key)" { - $getTargetResourceResult.$key | Should Be $ExpectedReturnValue.$key + $getTargetResourceResult.$key | Should -Be $ExpectedReturnValue.$key } } } @@ -288,7 +309,7 @@ function Invoke-GetTargetResourceUnitTest Each item in the array is a hashtable that contains the name of the command being mocked, the number of times it is called (can be 0) and, optionally, an extra custom string to make the test name more descriptive. The custom - string will only work if the command has a corresponding variable in the + string will only work if the command has a corresponding variable in the string data name. .PARAMETER ShouldThrow @@ -302,37 +323,42 @@ function Invoke-GetTargetResourceUnitTest The string that should be used to create the name of the test that checks for the correct error being thrown. #> -function Invoke-SetTargetResourceUnitTest { +function Invoke-SetTargetResourceUnitTest +{ [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [Hashtable] + [System.Collections.Hashtable] $SetTargetResourceParameters, - [Hashtable[]] + [Parameter()] + [System.Collections.Hashtable[]] $MocksCalled, - [Boolean] + [Parameter()] + [System.Boolean] $ShouldThrow = $false, - [String] + [Parameter()] + [System.String] $ErrorMessage = '', - [String] + [Parameter()] + [System.String] $ErrorTestName = '' ) if ($ShouldThrow) { It "Should throw an error for $ErrorTestName" { - { $null = Set-TargetResource @SetTargetResourceParameters } | Should Throw $ErrorMessage + { $null = Set-TargetResource @SetTargetResourceParameters } | Should -Throw -ExpectedMessage $ErrorMessage } } else { It 'Should not throw' { - { $null = Set-TargetResource @SetTargetResourceParameters } | Should Not Throw + { $null = Set-TargetResource @SetTargetResourceParameters } | Should -Not -Throw } } @@ -354,7 +380,7 @@ function Invoke-SetTargetResourceUnitTest { Each item in the array is a hashtable that contains the name of the command being mocked, the number of times it is called (can be 0) and, optionally, an extra custom string to make the test name more descriptive. The custom - string will only work if the command has a corresponding variable in the + string will only work if the command has a corresponding variable in the string data name. .PARAMETER ExpectedReturnValue @@ -366,19 +392,20 @@ function Invoke-TestTargetResourceUnitTest param ( [Parameter(Mandatory = $true)] - [Hashtable] + [System.Collections.Hashtable] $TestTargetResourceParameters, - [Hashtable[]] + [Parameter()] + [System.Collections.Hashtable[]] $MocksCalled, [Parameter(Mandatory = $true)] - [Boolean] + [System.Boolean] $ExpectedReturnValue ) It 'Should not throw' { - { $null = Test-TargetResource @TestTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @TestTargetResourceParameters } | Should -Not -Throw } Invoke-ExpectedMocksAreCalledTest -MocksCalled $MocksCalled @@ -386,7 +413,7 @@ function Invoke-TestTargetResourceUnitTest $testTargetResourceResult = Test-TargetResource @TestTargetResourceParameters It "Should return $ExpectedReturnValue" { - $testTargetResourceResult | Should Be $ExpectedReturnValue + $testTargetResourceResult | Should -Be $ExpectedReturnValue } } @@ -408,16 +435,17 @@ function Test-GetTargetResourceResult ( [Parameter(Mandatory = $true)] [ValidateNotNull()] - [Hashtable] + [System.Collections.Hashtable] $GetTargetResourceResult, - [String[]] + [Parameter()] + [System.String[]] $GetTargetResourceResultProperties ) foreach ($property in $GetTargetResourceResultProperties) { - $GetTargetResourceResult[$property] | Should Not Be $null + $GetTargetResourceResult[$property] | Should -Not -Be $null } } @@ -430,13 +458,13 @@ function Test-GetTargetResourceResult #> function Test-IsLocalMachine { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $Scope ) @@ -467,7 +495,6 @@ function Test-IsLocalMachine NOTE: This is likely overkill; consider removing it. #> $networkAdapters = @(Get-CimInstance Win32_NetworkAdapterConfiguration) - foreach ($networkAdapter in $networkAdapters) { if ($null -ne $networkAdapter.IPAddress) @@ -500,23 +527,24 @@ function Test-IsLocalMachine #> function Wait-ScriptBlockReturnTrue { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [ScriptBlock] + [System.Management.Automation.ScriptBlock] $ScriptBlock, - [Int] + [Parameter()] + [System.Int32] $TimeoutSeconds = 5 ) - $startTime = [DateTime]::Now + $startTime = [System.DateTime]::Now $invokeScriptBlockResult = $false - while (-not $invokeScriptBlockResult -and (([DateTime]::Now - $startTime).TotalSeconds -lt $TimeoutSeconds)) + while (-not $invokeScriptBlockResult -and (([System.DateTime]::Now - $startTime).TotalSeconds -lt $TimeoutSeconds)) { $invokeScriptBlockResult = $ScriptBlock.Invoke() Start-Sleep -Seconds 1 @@ -534,12 +562,12 @@ function Wait-ScriptBlockReturnTrue #> function Test-IsFileLocked { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Path ) @@ -550,7 +578,7 @@ function Test-IsFileLocked try { - $content = Get-Content -Path $Path + Get-Content -Path $Path | Out-Null return $false } catch @@ -573,19 +601,20 @@ function Test-IsFileLocked .PARAMETER ExpectedOutput The output expected to be in the output from running WhatIf with the Set-TargetResource cmdlet. If this parameter is empty or null, this cmdlet will check that there was no output from - Set-TargetResource with WhatIf specified. + Set-TargetResource with WhatIf specified. #> function Test-SetTargetResourceWithWhatIf { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [Hashtable] + [System.Collections.Hashtable] $Parameters, - - [String[]] + + [Parameter()] + [System.String[]] $ExpectedOutput ) @@ -609,7 +638,7 @@ function Test-SetTargetResourceWithWhatIf Wait-ScriptBlockReturnTrue -ScriptBlock {-not (Test-IsFileLocked -Path $transcriptPath)} $transcriptContent = Get-Content -Path $transcriptPath -Raw - $transcriptContent | Should Not Be $null + $transcriptContent | Should -Not -Be $null $regexString = '\*+[^\*]*\*+' @@ -627,13 +656,13 @@ function Test-SetTargetResourceWithWhatIf if ($null -eq $ExpectedOutput -or $ExpectedOutput.Count -eq 0) { - [String]::IsNullOrEmpty($transcriptContent) | Should Be $true + [System.String]::IsNullOrEmpty($transcriptContent) | Should -BeTrue } else { foreach ($expectedOutputPiece in $ExpectedOutput) { - $transcriptContent.Contains($expectedOutputPiece) | Should Be $true + $transcriptContent.Contains($expectedOutputPiece) | Should -BeTrue } } } @@ -707,23 +736,23 @@ function Get-AppVeyorAdministratorCredential #> function Enter-DscResourceTestEnvironment { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $DscResourceModuleName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $DscResourceName, [Parameter(Mandatory = $true)] [ValidateSet('Unit', 'Integration')] - [String] + [System.String] $TestType ) @@ -732,26 +761,9 @@ function Enter-DscResourceTestEnvironment $dscResourceTestsPath = Join-Path -Path $moduleRootPath -ChildPath 'DSCResource.Tests' $testHelperFilePath = Join-Path -Path $dscResourceTestsPath -ChildPath 'TestHelper.psm1' - if (-not (Test-Path -Path $dscResourceTestsPath)) + if (Test-DscResourceTestsNeedsInstallOrUpdate) { - Push-Location $moduleRootPath - git clone 'https://github.com/PowerShell/DscResource.Tests' --quiet - Pop-Location - } - else - { - $gitInstalled = $null -ne (Get-Command -Name 'git' -ErrorAction 'SilentlyContinue') - - if ($gitInstalled) - { - Push-Location $dscResourceTestsPath - git pull origin dev --quiet - Pop-Location - } - else - { - Write-Verbose -Message 'Git not installed. Leaving current DSCResource.Tests as is.' - } + Install-DscResourceTestsModule } Import-Module -Name $testHelperFilePath @@ -762,6 +774,157 @@ function Enter-DscResourceTestEnvironment -TestType $TestType } +<# + .SYNOPSIS + Tests to see if DSCResource.Tests needs to be downloaded + or updated. + + .DESCRIPTION + This function returns true if the DSCResource.Tests + content needs to be downloaded or updated. + + A magic file in the .Git folder of DSCResource.Tests + is used to determine if the repository needs to be + updated. + + If the last write time of the magic file is over a + specified number of minutes old then this will cause + the function to return true. + + .PARAMETER RefreshAfterMinutes + The number of minutes old the magic file should be + before requiring an update. Defaults to the value + defined in $script:dscResourceTestsRefreshAfterMinutes +#> +function Test-DscResourceTestsNeedsInstallOrUpdate +{ + [OutputType([System.Boolean])] + [CmdletBinding()] + param + ( + [Parameter()] + [System.Int32] + $RefreshAfterMinutes = $script:dscResourceTestsRefreshAfterMinutes + ) + + $testsFolderPath = Split-Path -Path $PSScriptRoot -Parent + $moduleRootPath = Split-Path -Path $testsFolderPath -Parent + $dscResourceTestsPath = Join-Path -Path $moduleRootPath -ChildPath 'DSCResource.Tests' + + if (Test-Path -Path $dscResourceTestsPath) + { + $magicFilePath = Get-DscResourceTestsMagicFilePath -DscResourceTestsPath $DscResourceTestsPath + + if (Test-Path -Path $magicFilePath) + { + $magicFileLastWriteTime = (Get-Item -Path $magicFilePath).LastWriteTime + $magicFileAge = New-TimeSpan -End (Get-Date) -Start $magicFileLastWriteTime + + if ($magicFileAge.Minutes -lt $RefreshAfterMinutes) + { + Write-Debug -Message ('DSCResource.Tests was last updated {0} minutes ago. Update not required.' -f $magicFileAge.Minutes) + return $false + } + else + { + Write-Verbose -Message ('DSCResource.Tests was last updated {0} minutes ago. Update required.' -f $magicFileAge.Minutes) -Verbose + } + } + } + + return $true +} + +<# + .SYNOPSIS + Installs the DSCResource.Tests content. + + .DESCRIPTION + This function uses Git to install or update the + DSCResource.Tests repository. + + It will then create or update the magic file in + the .git folder in the DSCResource.Tests folder. + + If Git is not installed and the DSCResource.Tests + folder is not available then an exception will + be thrown. + + If the DSCResource.Tests folder does exist but + Git is not installed then a warning will be + displayed and the repository will not be pulled. +#> +function Install-DscResourceTestsModule +{ + [CmdletBinding()] + param + ( + ) + + $testsFolderPath = Split-Path -Path $PSScriptRoot -Parent + $moduleRootPath = Split-Path -Path $testsFolderPath -Parent + $dscResourceTestsPath = Join-Path -Path $moduleRootPath -ChildPath 'DSCResource.Tests' + $gitInstalled = $null -ne (Get-Command -Name 'git' -ErrorAction 'SilentlyContinue') + $writeMagicFile = $false + + if (Test-Path -Path $dscResourceTestsPath) + { + if ($gitInstalled) + { + Push-Location -Path $dscResourceTestsPath + Write-Verbose -Message 'Updating DSCResource.Tests.' -Verbose + & git @('pull','origin','dev','--quiet') + $writeMagicFile = $true + Pop-Location + } + else + { + Write-Warning -Message 'Git not installed. DSCResource.Tests will not be updated.' + } + } + else + { + if (-not $gitInstalled) + { + throw 'Git not installed. Can not pull DSCResource.Tests.' + } + + Push-Location -Path $moduleRootPath + Write-Verbose -Message 'Cloning DSCResource.Tests.' -Verbose + & git @('clone','https://github.com/PowerShell/DscResource.Tests','--quiet') + $writeMagicFile = $true + Pop-Location + } + + if ($writeMagicFile) + { + # Write the magic file + $magicFilePath = Get-DscResourceTestsMagicFilePath -DscResourceTestsPath $DscResourceTestsPath + $null = Set-Content -Path $magicFilePath -Value (Get-Date) -Force + } +} + +<# + .SYNOPSIS + Gets the full path of the magic file used to + determine the last date/time the DSCResource.Tests + folder was updated. + + .PARAMETER DscResourceTestsPath + The path to the folder that contains DSCResource.Tests. +#> +function Get-DscResourceTestsMagicFilePath +{ + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $DscResourceTestsPath + ) + + return $DscResourceTestsPath | Join-Path -ChildPath '.git' | Join-Path -ChildPath $script:dscResourceTestsMagicFile +} + <# .SYNOPSIS Exits the specified DSC Resource test environment. @@ -776,7 +939,7 @@ function Exit-DscResourceTestEnvironment ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [Hashtable] + [System.Collections.Hashtable] $TestEnvironment ) @@ -790,6 +953,86 @@ function Exit-DscResourceTestEnvironment Restore-TestEnvironment -TestEnvironment $TestEnvironment } +<# + .SYNOPSIS + Finds an unused TCP port in the specified port range. By default, + searches within ports 38473 - 38799, which at the time of writing, show + as unassigned in: + https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml + + .PARAMETER LowestPortNumber + The TCP port number at which to begin the unused port search. Must be + greater than 0. + + .PARAMETER HighestPortNumber + The highest TCP port number to search for unused ports within. Must be + greater than 0, and greater than LowestPortNumber. + + .PARAMETER ExcludePorts + TCP ports to exclude from the search, even if they fall within the + LowestPortNumber and HighestPortNumber range. +#> +function Get-UnusedTcpPort +{ + [OutputType([System.UInt16])] + [CmdletBinding()] + param + ( + [Parameter()] + [ValidateScript({$_ -gt 0})] + [System.UInt16] + $LowestPortNumber = 38473, + + [Parameter()] + [ValidateScript({$_ -gt $0})] + [System.UInt16] + $HighestPortNumber = 38799, + + [Parameter()] + [System.UInt16[]] + $ExcludePorts = @() + ) + + if ($HighestPortNumber -lt $LowestPortNumber) + { + throw 'HighestPortNumber must be greater than or equal to LowestPortNumber' + } + + [System.UInt16] $unusedPort = 0 + + [System.Collections.ArrayList] $usedAndExcludedPorts = (Get-NetTCPConnection).LocalPort | Where-Object -FilterScript { + $_ -ge $LowestPortNumber -and $_ -le $HighestPortNumber + } + + if (!(Test-Path -Path variable:usedAndExcludedPorts) -or ($null -eq $usedAndExcludedPorts)) + { + [System.Collections.ArrayList] $usedAndExcludedPorts = @() + } + + if (!(Test-Path -Path variable:ExcludePorts) -or ($null -eq $ExcludePorts)) + { + $ExcludePorts = @() + } + + $null = $usedAndExcludedPorts.Add($ExcludePorts) + + foreach ($port in $LowestPortNumber..$HighestPortNumber) + { + if (!($usedAndExcludedPorts.Contains($port))) + { + $unusedPort = $port + break + } + } + + if ($unusedPort -eq 0) + { + throw "Failed to find unused TCP port between ports $LowestPortNumber and $HighestPortNumber." + } + + return $unusedPort +} + Export-ModuleMember -Function @( 'Test-GetTargetResourceResult', ` 'Wait-ScriptBlockReturnTrue', ` @@ -802,5 +1045,6 @@ Export-ModuleMember -Function @( 'Invoke-SetTargetResourceUnitTest', ` 'Invoke-TestTargetResourceUnitTest', ` 'Invoke-ExpectedMocksAreCalledTest', ` - 'Invoke-GenericUnitTest' + 'Invoke-GenericUnitTest', ` + 'Get-UnusedTcpPort' ) diff --git a/Tests/TestHelpers/DSCTestService.cs b/Tests/TestHelpers/DSCTestService.cs index 6903e89..41fdf3b 100644 --- a/Tests/TestHelpers/DSCTestService.cs +++ b/Tests/TestHelpers/DSCTestService.cs @@ -1,4 +1,4 @@ -namespace TestServiceNamespace +namespace TestServiceNamespace { using System; using System.ComponentModel; diff --git a/Tests/TestHelpers/DSCTestServiceNew.cs b/Tests/TestHelpers/DSCTestServiceNew.cs index 6903e89..41fdf3b 100644 --- a/Tests/TestHelpers/DSCTestServiceNew.cs +++ b/Tests/TestHelpers/DSCTestServiceNew.cs @@ -1,4 +1,4 @@ -namespace TestServiceNamespace +namespace TestServiceNamespace { using System; using System.ComponentModel; diff --git a/Tests/TestHelpers/MSFT_Archive.TestHelper.psm1 b/Tests/TestHelpers/MSFT_Archive.TestHelper.psm1 index 2b5f3ef..146952e 100644 --- a/Tests/TestHelpers/MSFT_Archive.TestHelper.psm1 +++ b/Tests/TestHelpers/MSFT_Archive.TestHelper.psm1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' Add-Type -AssemblyName 'System.IO.Compression.FileSystem' @@ -66,7 +66,7 @@ function ConvertTo-FileStructure .SYNOPSIS Creates a new zip file with the specified name and file structure under the specified parent path. Returns the file path to the compressed zip file. - + .PARAMETER ParentPath The path under which the new zip file should be created. @@ -78,7 +78,7 @@ function ConvertTo-FileStructure Nested hashtable values denote directories with the key as the name of the directory and the hashtable value as the contents. String values denote files with the key as the name of the file and the value as the contents. - + .EXAMPLE $zipFileStructure = @{ DirectoryName = @{ diff --git a/Tests/TestHelpers/MSFT_GroupResource.TestHelper.psm1 b/Tests/TestHelpers/MSFT_GroupResource.TestHelper.psm1 index 5b8175a..9aa9466 100644 --- a/Tests/TestHelpers/MSFT_GroupResource.TestHelper.psm1 +++ b/Tests/TestHelpers/MSFT_GroupResource.TestHelper.psm1 @@ -1,4 +1,4 @@ - + $errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' @@ -31,24 +31,24 @@ if (-not (Test-IsNanoServer)) #> function Test-GroupExists { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $GroupName, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude ) @@ -80,25 +80,25 @@ function Test-GroupExists #> function Test-GroupExistsOnFullSKU { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude ) @@ -217,25 +217,25 @@ function Test-GroupExistsOnFullSKU #> function Test-GroupExistsOnNanoServer { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] - [String[]] + [System.String[]] $Members, [Parameter()] - [String[]] + [System.String[]] $MembersToInclude, [Parameter()] - [String[]] + [System.String[]] $MembersToExclude ) @@ -375,15 +375,15 @@ function New-Group ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members ) @@ -422,19 +422,19 @@ function New-GroupOnFullSKU ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members ) - $adsiComputerEntry = [ADSI] "WinNT://$env:computerName" + $adsiComputerEntry = [System.DirectoryServices.DirectoryEntry] "WinNT://$env:computerName" $adsiGroupEntry = $adsiComputerEntry.Create('Group', $GroupName) if ($PSBoundParameters.ContainsKey('Description')) @@ -446,7 +446,7 @@ function New-GroupOnFullSKU if ($PSBoundParameters.ContainsKey("Members")) { - $adsiGroupEntry = [ADSI]"WinNT://$env:computerName/$GroupName,group" + $adsiGroupEntry = [System.DirectoryServices.DirectoryEntry] "WinNT://$env:computerName/$GroupName,group" foreach ($memberUserName in $Members) { @@ -475,15 +475,15 @@ function New-GroupOnNanoServer ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName, [Parameter()] - [String] + [System.String] $Description, [Parameter()] - [String[]] + [System.String[]] $Members ) @@ -514,7 +514,7 @@ function Remove-Group ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName ) @@ -547,11 +547,11 @@ function Remove-GroupOnFullSKU ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName ) - $adsiComputerEntry = [ADSI]("WinNT://$env:computerName") + $adsiComputerEntry = [System.DirectoryServices.DirectoryEntry] ("WinNT://$env:computerName") $null = $adsiComputerEntry.Delete('Group', $GroupName) } @@ -569,7 +569,7 @@ function Remove-GroupOnNanoServer ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $GroupName ) @@ -585,12 +585,12 @@ function Remove-GroupOnNanoServer #> function Test-UserExists { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Username ) @@ -613,12 +613,12 @@ function Test-UserExists #> function Test-UserExistsOnFullSKU { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Username ) @@ -642,12 +642,12 @@ function Test-UserExistsOnFullSKU #> function Test-UserExistsOnNanoServer { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Username ) @@ -726,7 +726,7 @@ function New-UserOnFullSKU $userName = $Credential.UserName $password = $Credential.GetNetworkCredential().Password - $adsiComputerEntry = [ADSI]("WinNT://$env:computerName") + $adsiComputerEntry = [System.DirectoryServices.DirectoryEntry] ("WinNT://$env:computerName") $adsiUserEntry = $adsiComputerEntry.Create('User', $userName) $null = $adsiUserEntry.SetPassword($password) $null = $adsiUserEntry.SetInfo() @@ -769,7 +769,7 @@ function Remove-User param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $UserName ) @@ -801,11 +801,11 @@ function Remove-UserOnFullSKU param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $UserName ) - $adsiComputerEntry = [ADSI]("WinNT://$env:computerName") + $adsiComputerEntry = [System.DirectoryServices.DirectoryEntry] ("WinNT://$env:computerName") $null = $adsiComputerEntry.Delete('User', $UserName) } @@ -822,7 +822,7 @@ function Remove-UserOnNanoServer param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $UserName ) diff --git a/Tests/TestHelpers/MSFT_MsiPackageResource.TestHelper.psm1 b/Tests/TestHelpers/MSFT_MsiPackageResource.TestHelper.psm1 index b96befe..6db9850 100644 --- a/Tests/TestHelpers/MSFT_MsiPackageResource.TestHelper.psm1 +++ b/Tests/TestHelpers/MSFT_MsiPackageResource.TestHelper.psm1 @@ -1,6 +1,8 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' +$testJobPrefix = 'MsiPackageTestJob' + <# .SYNOPSIS Tests if the package with the given Id is installed. @@ -10,11 +12,11 @@ Set-StrictMode -Version 'Latest' #> function Test-PackageInstalledById { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( - [String] + [System.String] $ProductId ) @@ -23,7 +25,7 @@ function Test-PackageInstalledById $productEntry = $null - if (-not [String]::IsNullOrEmpty($ProductId)) + if (-not [System.String]::IsNullOrEmpty($ProductId)) { $productEntryKeyLocation = Join-Path -Path $uninstallRegistryKey -ChildPath $ProductId $productEntry = Get-Item -Path $productEntryKeyLocation -ErrorAction 'SilentlyContinue' @@ -55,26 +57,42 @@ function Test-PackageInstalledById .PARAMETER Https Indicates whether the server should use Https. If True then the file server will use Https - and listen on port 'https://localhost:1243'. Otherwise the file server will use Http and - listen on port 'http://localhost:1242' + and listen on port 'https://localhost:HttpsPort'. Otherwise the file server will use Http and + listen on port 'http://localhost:HttpPort' Default value is False (Http). + + .PARAMETER HttpPort + Specifies the TCP port to register an Http based HttpListener on. + + .PARAMETER HttspPort + Specifies the TCP port to register an Https based HttpListener on. #> function Start-Server { - [OutputType([Hashtable])] + [OutputType([System.Collections.Hashtable])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $FilePath, - [String] + [System.String] $LogPath = (Join-Path -Path $PSScriptRoot -ChildPath 'PackageTestLogFile.txt'), [System.Boolean] - $Https = $false + $Https = $false, + + [Parameter(Mandatory = $true)] + [ValidateScript({$_ -gt 0})] + [System.UInt16] + $HttpPort, + + [Parameter(Mandatory = $true)] + [ValidateScript({$_ -gt 0})] + [System.UInt16] + $HttpsPort ) # Create an event object to let the client know when the server is ready to begin receiving requests. @@ -82,7 +100,7 @@ function Start-Server 'HttpIntegrationTest.FileServerStarted') $null = $fileServerStarted.Reset() - <# + <# The server is run on a separate process so that it can receive requests while the tests continue to run. It takes in the same parameterss that are passed in to this function. All helper functions that the server uses have to be @@ -90,7 +108,7 @@ function Start-Server #> $server = { - param($FilePath, $LogPath, $Https) + param($FilePath, $LogPath, $Https, $HttpPort, $HttpsPort) <# .SYNOPSIS @@ -101,6 +119,9 @@ function Start-Server .PARAMETER Https Indicates whether https was used and if so, removes the SSL binding. + + .PARAMETER HttspPort + Specifies the TCP port to de-register an Https based HttpListener from. #> function Stop-Listener { @@ -109,16 +130,21 @@ function Start-Server ( [Parameter(Mandatory = $true)] [System.Net.HttpListener] - $HttpListener, + $HttpListener, [Parameter(Mandatory = $true)] [System.Boolean] - $Https + $Https, + + [Parameter(Mandatory = $true)] + [ValidateScript({$_ -gt 0})] + [System.UInt16] + $HttpsPort ) Write-Log -LogFile $LogPath -Message 'Finished listening for requests. Shutting down HTTP server.' - - $ipPort = '0.0.0.0:1243' + + $ipPort = "0.0.0.0:$HttpsPort" if ($null -eq $HttpListener) { @@ -159,16 +185,25 @@ function Start-Server <# .SYNOPSIS Creates and registers an SSL certificate for Https connections. + + .PARAMETER HttspPort + Specifies the TCP port to register an Https based HttpListener on. #> function Register-Ssl { [CmdletBinding()] - param() + param + ( + [Parameter(Mandatory = $true)] + [ValidateScript({$_ -gt 0})] + [System.UInt16] + $HttpsPort + ) # Create certificate $certificate = New-SelfSignedCertificate -CertStoreLocation 'Cert:\LocalMachine\My' -DnsName localhost Write-Log -LogFile $LogPath -Message 'Created certificate' - + $hash = $certificate.Thumbprint $certPassword = ConvertTo-SecureString -String 'password12345' -AsPlainText -Force $tempPath = 'C:\certForTesting' @@ -176,11 +211,11 @@ function Start-Server $null = Export-PfxCertificate -Cert $certificate -FilePath $tempPath -Password $certPassword $null = Import-PfxCertificate -CertStoreLocation 'Cert:\LocalMachine\Root' -FilePath 'C:\certForTesting' -Password $certPassword Remove-Item -Path $tempPath - + Write-Log -LogFile $LogPath -Message 'Finished importing certificate into root. About to bind it to port.' - + # Use net shell command to directly bind certificate to designated testing port - $null = netsh http add sslcert ipport=0.0.0.0:1243 certhash=$hash appid='{833f13c2-319a-4799-9d1a-5b267a0c3593}' clientcertnegotiation=enable + $null = netsh http add sslcert ipport=0.0.0.0:$HttpsPort certhash=$hash appid='{833f13c2-319a-4799-9d1a-5b267a0c3593}' clientcertnegotiation=enable } <# @@ -197,39 +232,39 @@ function Start-Server ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [ScriptBlock] + [System.Management.Automation.ScriptBlock] $Callback ) # Add the CallbackEventBridge type if it's not already defined - if (-not ('CallbackEventBridge' -as [Type])) + if (-not ('CallbackEventBridge' -as [System.Type])) { - Add-Type @' - using System; - - public sealed class CallbackEventBridge { - public event AsyncCallback CallbackComplete = delegate { }; - - private CallbackEventBridge() {} - + Add-Type @' + using System; + + public sealed class CallbackEventBridge { + public event AsyncCallback CallbackComplete = delegate { }; + + private CallbackEventBridge() {} + private void CallbackInternal(IAsyncResult result) - { - CallbackComplete(result); - } - + { + CallbackComplete(result); + } + public AsyncCallback Callback - { - get { return new AsyncCallback(CallbackInternal); } - } - + { + get { return new AsyncCallback(CallbackInternal); } + } + public static CallbackEventBridge Create() - { - return new CallbackEventBridge(); - } - } + { + return new CallbackEventBridge(); + } + } '@ } - + $bridge = [CallbackEventBridge]::Create() Register-ObjectEvent -InputObject $bridge -EventName 'CallbackComplete' -Action $Callback -MessageData $args > $null $bridge.Callback @@ -249,7 +284,7 @@ function Start-Server .PARAMETER ScriptBlock The code to execute. - + #> function Invoke-ConsoleCommand { @@ -257,15 +292,15 @@ function Start-Server param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Target, [Parameter(Mandatory = $true)] - [String] + [System.String] $Action, [Parameter(Mandatory = $true)] - [ScriptBlock] + [System.Management.Automation.ScriptBlock] $ScriptBlock ) @@ -277,7 +312,7 @@ function Start-Server $message = ('Failed action ''{0}'' on target ''{1}'' (exit code {2}): {3}' -f $Action,$Target,$LASTEXITCODE,$output) Write-Error -Message $message Write-Log -LogFile $LogPath -Message "Error from Invoke-ConsoleCommand: $message" - } + } else { $nonNullOutput = $output | Where-Object { $_ -ne $null } @@ -302,14 +337,14 @@ function Start-Server param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $LogFile, [Parameter(Mandatory = $true)] - [String] + [System.String] $Message ) - + $Message >> $LogFile } @@ -332,11 +367,11 @@ function Start-Server # Set up the listener if ($Https) { - $HttpListener.Prefixes.Add([Uri]'https://localhost:1243') - + $HttpListener.Prefixes.Add([Uri] "https://localhost:$HttpsPort") + try { - Register-SSL + Register-SSL -HttpsPort $HttpsPort } catch { @@ -349,7 +384,7 @@ function Start-Server } else { - $HttpListener.Prefixes.Add([Uri]'http://localhost:1242') + $HttpListener.Prefixes.Add([Uri] "http://localhost:$HttpPort") } Write-Log -LogFile $LogPath -Message 'Finished listener setup - about to start listener' @@ -374,7 +409,7 @@ function Start-Server .PARAMETER Result th IAsyncResult containing the listener object and path to the MSI file. - + #> $requestListener = { @@ -388,7 +423,7 @@ function Start-Server Write-Log -LogFile $LogPath -Message 'Starting request listener' $asyncState = $Result.AsyncState - [System.Net.HttpListener]$listener = $asyncState.Listener + [System.Net.HttpListener] $listener = $asyncState.Listener $filepath = $asyncState.FilePath Write-Log -LogFile $LogPath -Message (ConvertTo-Json $asyncState) @@ -405,7 +440,7 @@ function Start-Server $numBytes = $fileInfo.Length $fileStream = New-Object -TypeName 'System.IO.FileStream' -ArgumentList @( $filePath, 'Open' ) $binaryReader = New-Object -TypeName 'System.IO.BinaryReader' -ArgumentList @( $fileStream ) - [Byte[]] $buf = $binaryReader.ReadBytes($numBytes) + [System.Byte[]] $buf = $binaryReader.ReadBytes($numBytes) $fileStream.Close() Write-Log -LogFile $LogPath -Message 'Buffer prepared for response' @@ -450,8 +485,22 @@ function Start-Server catch { $errorMessage = "There were problems setting up the HTTP(s) listener. Error: $_" + Write-Log -LogFile $LogPath -Message $errorMessage - throw $errorMessage + + 'Error Record Info' >> $LogPath + $_ | ConvertTo-Xml -As String >> $LogPath + + 'Exception Info' >> $LogPath + $_.Exception | ConvertTo-Xml -As String >> $LogPath + + 'Running Process Info' >> $LogPath + Get-Process | Format-List | Out-String >> $LogPath + + 'Open TCP Connections Info' >> $LogPath + Get-NetTCPConnection | Format-List | Out-String >> $LogPath + + throw $_ } finally { @@ -459,19 +508,39 @@ function Start-Server { $fileServerStarted.Dispose() } - + Write-Log -LogFile $LogPath -Message 'Stopping the Server' - Stop-Listener -HttpListener $HttpListener -Https $Https + Stop-Listener -HttpListener $HttpListener -Https $Https -HttpsPort $HttpsPort } } - $job = Start-Job -ScriptBlock $server -ArgumentList @( $FilePath, $LogPath, $Https ) + if ($Https) + { + $jobName = $testJobPrefix + 'Https' + } + else + { + $jobName = $testJobPrefix + 'Http' + } + + $job = Start-Job -ScriptBlock $server -Name $jobName -ArgumentList @( $FilePath, $LogPath, $Https, $HttpPort, $HttpsPort ) + + # Verify that the job is receivable and does not contain an exception. If it does, re-throw it. + try + { + $null = $job | Receive-Job + } + catch + { + Write-Error -Message 'Failed to setup HTTP(S) listener for MsiPackage Tests' + throw $_ + } <# - Return the event object so that client knows when it can start sending requests and + Return the event object so that client knows when it can start sending requests and the job object so that the client can stop the job once it is done sending requests. #> - return @{ + return @{ FileServerStarted = $fileServerStarted Job = $job } @@ -501,7 +570,7 @@ function Stop-Server $FileServerStarted, [System.Management.Automation.Job] - $Job + $Job ) if ($null -ne $FileServerStarted) @@ -516,6 +585,20 @@ function Stop-Server } } +<# + .SYNOPSIS + Removes any jobs associated with HTTP(S) servers that were created + for MsiPackage tests. +#> +function Stop-EveryTestServerInstance +{ + [CmdletBinding()] + param () + + Get-Job -Name "$($testJobPrefix)*" | Stop-Job + Get-Job -Name "$($testJobPrefix)*" | Remove-Job +} + <# .SYNOPSIS Creates a new MSI package for testing. @@ -526,11 +609,11 @@ function Stop-Server function New-TestMsi { [CmdletBinding()] - param + param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $DestinationPath ) @@ -1061,4 +1144,5 @@ Export-ModuleMember -Function ` New-TestMsi, ` Start-Server, ` Stop-Server, ` - Test-PackageInstalledById + Test-PackageInstalledById, ` + Stop-EveryTestServerInstance diff --git a/Tests/TestHelpers/MSFT_RegistryResource.TestHelper.psm1 b/Tests/TestHelpers/MSFT_RegistryResource.TestHelper.psm1 index 18029f6..910c956 100644 --- a/Tests/TestHelpers/MSFT_RegistryResource.TestHelper.psm1 +++ b/Tests/TestHelpers/MSFT_RegistryResource.TestHelper.psm1 @@ -3,18 +3,18 @@ Tests if a registry key exists. .PARAMETER KeyPath - The path to the registry key to test for existence. + The path to the registry key to test for existence. Must include the registry hive. #> function Test-RegistryKeyExists { [CmdletBinding()] - [OutputType([Boolean])] - param + [OutputType([System.Boolean])] + param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath ) @@ -26,7 +26,7 @@ function Test-RegistryKeyExists Tests if a registry key value exists. .PARAMETER KeyPath - The path to the registry key that should contain the value to test for existence. + The path to the registry key that should contain the value to test for existence. Must include the registry hive. .PARAMETER ValueName @@ -41,28 +41,28 @@ function Test-RegistryKeyExists function Test-RegistryValueExists { [CmdletBinding()] - [OutputType([Boolean])] + [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath, [Parameter(Mandatory = $true)] [ValidateNotNull()] [AllowEmptyString()] - [String] + [System.String] $ValueName, - [String] + [System.String] $ValueData, [ValidateNotNullOrEmpty()] - [String] + [System.String] $ValueType ) - try + try { $registryValue = Get-ItemProperty -Path $KeyPath -Name $ValueName -ErrorAction 'SilentlyContinue' Write-Verbose -Message "Test-RegistryValueExists - Registry key value: $registryKeyValue" @@ -87,7 +87,7 @@ function Test-RegistryValueExists $registryValueExists = $registryValueExists -and ($registryValue.GetType().Name -eq 'Byte[]') $registryValue = Convert-ByteArrayToHexString -Data $registryValue } - else + else { $registryValueExists = $registryValueExists -and ($registryValue.GetType().Name -eq $ValueType) } @@ -113,7 +113,7 @@ function Test-RegistryValueExists Creates a registry key. .PARAMETER KeyPath - The path to the registry key to be created. + The path to the registry key to be created. Must include the registry hive. #> function New-TestRegistryKey @@ -123,17 +123,17 @@ function New-TestRegistryKey ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath ) $parentPath = Split-Path -Path $KeyPath -Parent - + if (-not (Test-RegistryKeyExists -KeyPath $parentPath)) { New-TestRegistryKey -KeyPath $parentPath } - + Write-Verbose -Message "New-TestRegistryKey - Creating new registry key at: $KeyPath" $null = New-Item -Path $KeyPath @@ -144,7 +144,7 @@ function New-TestRegistryKey Creates a registry key. .PARAMETER KeyPath - The path to the registry key to be created. + The path to the registry key to be created. Must include the registry hive. .PARAMETER ValueName @@ -163,20 +163,20 @@ function New-RegistryValue ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath, [Parameter(Mandatory = $true)] [ValidateNotNull()] [AllowEmptyString()] - [String] + [System.String] $ValueName, - [Object] + [System.Object] $ValueData, [ValidateNotNullOrEmpty()] - [String] + [System.String] $ValueType ) @@ -199,11 +199,11 @@ function New-RegistryValue $convertedValueData += [Convert]::ToInt32($ValueData.Substring($index, 2), 16) } - $ValueData = [Byte[]] $convertedValueData + $ValueData = [System.Byte[]] $convertedValueData Write-Verbose -Message "New-RegistryValue - Binary data: $ValueData" } - + $null = New-ItemProperty -Path $KeyPath -Name $ValueName -Value $ValueData -PropertyType $ValueType } @@ -212,17 +212,17 @@ function New-RegistryValue Removes a registry key. .PARAMETER KeyPath - The path to the registry key to remove + The path to the registry key to remove Must include the registry hive. #> function Remove-RegistryKey { [CmdletBinding()] - param + param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath ) @@ -234,7 +234,7 @@ function Remove-RegistryKey Removes a registry value. .PARAMETER KeyPath - The path to the registry key that contains the value to remove. + The path to the registry key that contains the value to remove. Must include the registry hive. .PARAMETER ValueName @@ -243,17 +243,17 @@ function Remove-RegistryKey function Remove-RegistryValue { [CmdletBinding()] - param + param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath, [Parameter(Mandatory = $true)] [ValidateNotNull()] [AllowEmptyString()] - [String] + [System.String] $ValueName ) @@ -270,11 +270,11 @@ function Remove-RegistryValue function Mount-RegistryDrive { [CmdletBinding()] - param + param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath ) @@ -327,11 +327,11 @@ function Mount-RegistryDrive function Dismount-RegistryDrive { [CmdletBinding()] - param + param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath ) @@ -351,12 +351,12 @@ function Dismount-RegistryDrive function Test-RegistryDriveMounted { [CmdletBinding()] - [OutputType([Boolean])] + [OutputType([System.Boolean])] param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $KeyPath ) diff --git a/Tests/TestHelpers/MSFT_ServiceResource.TestHelper.psm1 b/Tests/TestHelpers/MSFT_ServiceResource.TestHelper.psm1 index 37c6d42..398241b 100644 --- a/Tests/TestHelpers/MSFT_ServiceResource.TestHelper.psm1 +++ b/Tests/TestHelpers/MSFT_ServiceResource.TestHelper.psm1 @@ -29,32 +29,32 @@ function New-ServiceExecutable param ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceCodePath, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceDisplayName, [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceDescription, [Parameter()] [ValidateNotNullOrEmpty()] - [String] + [System.String] $ServiceDependsOn = "''", [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [String] + [System.String] $OutputPath ) @@ -89,7 +89,7 @@ function Remove-ServiceWithTimeout ( [Parameter(Mandatory = $true)] [ValidateNotNullorEmpty()] - [String] + [System.String] $Name ) @@ -98,9 +98,9 @@ function Remove-ServiceWithTimeout & 'sc.exe' 'delete' $Name $serviceDeleted = $false - $start = [DateTime]::Now + $start = [System.DateTime]::Now - while (-not $serviceDeleted -and ([DateTime]::Now - $start).TotalMilliseconds -lt 5000) + while (-not $serviceDeleted -and ([System.DateTime]::Now - $start).TotalMilliseconds -lt 5000) { $service = Get-Service -Name $Name -ErrorAction 'SilentlyContinue' @@ -124,12 +124,12 @@ function Remove-ServiceWithTimeout #> function Test-ServiceExists { - [OutputType([Boolean])] + [OutputType([System.Boolean])] [CmdletBinding()] param ( [Parameter(Mandatory = $true)] - [String] + [System.String] $Name ) diff --git a/Tests/TestHelpers/MSFT_UserResource.TestHelper.psm1 b/Tests/TestHelpers/MSFT_UserResource.TestHelper.psm1 index 1ed7d5a..a6873c3 100644 --- a/Tests/TestHelpers/MSFT_UserResource.TestHelper.psm1 +++ b/Tests/TestHelpers/MSFT_UserResource.TestHelper.psm1 @@ -1,4 +1,4 @@ -Import-Module "$PSScriptRoot\..\..\DSCResources\CommonResourceHelper.psm1" -Force +Import-Module "$PSScriptRoot\..\..\DSCResources\CommonResourceHelper.psm1" -Force <# .SYNOPSIS diff --git a/Tests/TestHelpers/WMF5Dot1Installation.psm1 b/Tests/TestHelpers/WMF5Dot1Installation.psm1 index 6fb8af7..8b35ca7 100644 --- a/Tests/TestHelpers/WMF5Dot1Installation.psm1 +++ b/Tests/TestHelpers/WMF5Dot1Installation.psm1 @@ -1,4 +1,4 @@ -Set-StrictMode -Version 'latest' +Set-StrictMode -Version 'latest' $errorActionPreference = 'Stop' <# diff --git a/Tests/TestHelpers/WindowsProcessTestProcess.cs b/Tests/TestHelpers/WindowsProcessTestProcess.cs index ceb28b5..d3050f7 100644 --- a/Tests/TestHelpers/WindowsProcessTestProcess.cs +++ b/Tests/TestHelpers/WindowsProcessTestProcess.cs @@ -1,4 +1,4 @@ -using System.IO; +using System.IO; using System.Threading; // This is a test process used for testing configuring running and stopping a process on a machine diff --git a/Tests/Unit/CommonResourceHelper.Tests.ps1 b/Tests/Unit/CommonResourceHelper.Tests.ps1 index 241c18f..cf19d19 100644 --- a/Tests/Unit/CommonResourceHelper.Tests.ps1 +++ b/Tests/Unit/CommonResourceHelper.Tests.ps1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' Describe 'CommonResourceHelper Unit Tests' { @@ -14,140 +14,58 @@ Describe 'CommonResourceHelper Unit Tests' { InModuleScope 'CommonResourceHelper' { Describe 'Test-IsNanoServer' { $testComputerInfoNanoServer = @{ - OsProductType = 'Server' - OsServerLevel = 'NanoServer' + NanoServer = 1 } $testComputerInfoServerNotNano = @{ - OsProductType = 'Server' - OsServerLevel = 'NotNano' } - $testComputerInfoNotServer = @{ - OsProductType = 'NotServer' - OsServerLevel = 'NotNano' - } - - Mock -CommandName 'Test-CommandExists' -MockWith { return $true } - Mock -CommandName 'Get-ComputerInfo' -MockWith { return $testComputerInfoNanoServer } - - Context 'Get-ComputerInfo command exists and succeeds' { - Context 'Computer OS type is Server and OS server level is NanoServer' { - It 'Should not throw' { - { $null = Test-IsNanoServer } | Should -Not -Throw - } - - It 'Should test if the Get-ComputerInfo command exists' { - $testCommandExistsParameterFilter = { - return $Name -eq 'Get-ComputerInfo' - } - - Assert-MockCalled -CommandName 'Test-CommandExists' -ParameterFilter $testCommandExistsParameterFilter -Exactly 1 -Scope 'Context' - } - - It 'Should retrieve the computer info' { - Assert-MockCalled -CommandName 'Get-ComputerInfo' -Exactly 1 -Scope 'Context' - } - - It 'Should return true' { - Test-IsNanoServer | Should -Be $true - } + Context 'Computer OS type is Server and OS server level is NanoServer' { + Mock -CommandName 'Test-Path' -MockWith { return $true } + Mock -CommandName 'Get-ItemProperty' -MockWith { return $testComputerInfoNanoServer } + It 'Should not throw' { + { $null = Test-IsNanoServer } | Should -Not -Throw } - Context 'Computer OS type is Server and OS server level is not NanoServer' { - Mock -CommandName 'Get-ComputerInfo' -MockWith { return $testComputerInfoServerNotNano } - - It 'Should not throw' { - { $null = Test-IsNanoServer } | Should -Not -Throw - } - - It 'Should test if the Get-ComputerInfo command exists' { - $testCommandExistsParameterFilter = { - return $Name -eq 'Get-ComputerInfo' - } - - Assert-MockCalled -CommandName 'Test-CommandExists' -ParameterFilter $testCommandExistsParameterFilter -Exactly 1 -Scope 'Context' - } - - It 'Should retrieve the computer info' { - Assert-MockCalled -CommandName 'Get-ComputerInfo' -Exactly 1 -Scope 'Context' - } - - It 'Should return false' { - Test-IsNanoServer | Should -Be $false - } + It 'Should check the ServerLevels registry path' { + Assert-MockCalled -CommandName 'Get-ItemProperty' -Exactly 1 -Scope 'Context' } - Context 'Computer OS type is not Server' { - Mock -CommandName 'Get-ComputerInfo' -MockWith { return $testComputerInfoNotServer } - - It 'Should not throw' { - { $null = Test-IsNanoServer } | Should -Not -Throw - } - - It 'Should test if the Get-ComputerInfo command exists' { - $testCommandExistsParameterFilter = { - return $Name -eq 'Get-ComputerInfo' - } - - Assert-MockCalled -CommandName 'Test-CommandExists' -ParameterFilter $testCommandExistsParameterFilter -Exactly 1 -Scope 'Context' - } - - It 'Should retrieve the computer info' { - Assert-MockCalled -CommandName 'Get-ComputerInfo' -Exactly 1 -Scope 'Context' - } - - It 'Should return false' { - Test-IsNanoServer | Should -Be $false - } + It 'Should return true' { + Test-IsNanoServer | Should -BeTrue } } - Context 'Get-ComputerInfo command exists but throws an error and returns null' { - Mock -CommandName 'Get-ComputerInfo' -MockWith { return $null } + Context 'Computer OS type is Server and OS server level is not NanoServer' { + Mock -CommandName 'Test-Path' -MockWith { return $true } + Mock -CommandName 'Get-ItemProperty' -MockWith { return $testComputerInfoServerNotNano } It 'Should not throw' { { $null = Test-IsNanoServer } | Should -Not -Throw } - It 'Should test if the Get-ComputerInfo command exists' { - $testCommandExistsParameterFilter = { - return $Name -eq 'Get-ComputerInfo' - } - - Assert-MockCalled -CommandName 'Test-CommandExists' -ParameterFilter $testCommandExistsParameterFilter -Exactly 1 -Scope 'Context' - } - - It 'Should retrieve the computer info' { - Assert-MockCalled -CommandName 'Get-ComputerInfo' -Exactly 1 -Scope 'Context' + It 'Should check the ServerLevels registry path' { + Assert-MockCalled -CommandName 'Get-ItemProperty' -Exactly 1 -Scope 'Context' } It 'Should return false' { - Test-IsNanoServer | Should -Be $false + Test-IsNanoServer | Should -BeFalse } } - Context 'Get-ComputerInfo command does not exist' { - Mock -CommandName 'Test-CommandExists' -MockWith { return $false } + Context 'Computer OS type is not Server' { + Mock -CommandName 'Test-Path' -MockWith { return $false } It 'Should not throw' { { $null = Test-IsNanoServer } | Should -Not -Throw } - It 'Should test if the Get-ComputerInfo command exists' { - $testCommandExistsParameterFilter = { - return $Name -eq 'Get-ComputerInfo' - } - - Assert-MockCalled -CommandName 'Test-CommandExists' -ParameterFilter $testCommandExistsParameterFilter -Exactly 1 -Scope 'Context' - } - - It 'Should not attempt to retrieve the computer info' { - Assert-MockCalled -CommandName 'Get-ComputerInfo' -Exactly 0 -Scope 'Context' + It 'Should check the ServerLevels registry path' { + Assert-MockCalled -CommandName 'Test-Path' -Exactly 1 -Scope 'Context' } It 'Should return false' { - Test-IsNanoServer | Should -Be $false + Test-IsNanoServer | Should -BeFalse } } } @@ -171,7 +89,7 @@ Describe 'CommonResourceHelper Unit Tests' { } It 'Should return true' { - Test-CommandExists -Name $testCommandName | Should -Be $true + Test-CommandExists -Name $testCommandName | Should -BeTrue } } @@ -191,7 +109,7 @@ Describe 'CommonResourceHelper Unit Tests' { } It 'Should return false' { - Test-CommandExists -Name $testCommandName | Should -Be $false + Test-CommandExists -Name $testCommandName | Should -BeFalse } } } diff --git a/Tests/Unit/MSFT_Archive.Tests.ps1 b/Tests/Unit/MSFT_Archive.Tests.ps1 index e1572c1..cc2f315 100644 --- a/Tests/Unit/MSFT_Archive.Tests.ps1 +++ b/Tests/Unit/MSFT_Archive.Tests.ps1 @@ -28,7 +28,7 @@ Describe 'Archive Unit Tests' { $script:testCredential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList @( $testUsername, $secureTestPassword ) - $script:testGuid = [Guid]::NewGuid() + $script:testGuid = [System.Guid]::NewGuid() Describe 'Get-TargetResource' { $testPSDrive = @{ @@ -55,7 +55,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for Checksum specified while Validate is false' { $errorMessage = $script:localizedData.ChecksumSpecifiedAndValidateFalse -f $getTargetResourceParameters.Checksum, $getTargetResourceParameters.Path, $getTargetResourceParameters.Destination - { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw $errorMessage + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -66,7 +66,7 @@ Describe 'Archive Unit Tests' { } It 'Should throw an error for invalid archive path' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw $testInvalidArchivePathErrorMessage + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw -ExpectedMessage $testInvalidArchivePathErrorMessage } } @@ -79,7 +79,7 @@ Describe 'Archive Unit Tests' { } It 'Should throw an error for invalid destination' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw $testInvalidDestinationErrorMessage + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw -ExpectedMessage $testInvalidDestinationErrorMessage } } @@ -137,7 +137,7 @@ Describe 'Archive Unit Tests' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a Hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return a Hashtable with 3 properties' { @@ -211,7 +211,7 @@ Describe 'Archive Unit Tests' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a Hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return a Hashtable with 3 properties' { @@ -292,7 +292,7 @@ Describe 'Archive Unit Tests' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a Hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return a Hashtable with 3 properties' { @@ -374,7 +374,7 @@ Describe 'Archive Unit Tests' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a Hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return a Hashtable with 3 properties' { @@ -455,7 +455,7 @@ Describe 'Archive Unit Tests' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a Hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return a Hashtable with 3 properties' { @@ -537,7 +537,7 @@ Describe 'Archive Unit Tests' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a Hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return a Hashtable with 3 properties' { @@ -631,7 +631,7 @@ Describe 'Archive Unit Tests' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a Hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return a Hashtable with 3 properties' { @@ -679,7 +679,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for Checksum specified while Validate is false' { $errorMessage = $script:localizedData.ChecksumSpecifiedAndValidateFalse -f $setTargetResourceParameters.Checksum, $setTargetResourceParameters.Path, $setTargetResourceParameters.Destination - { Set-TargetResource @setTargetResourceParameters } | Should -Throw $errorMessage + { Set-TargetResource @setTargetResourceParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -690,7 +690,7 @@ Describe 'Archive Unit Tests' { } It 'Should throw an error for invalid archive path' { - { Set-TargetResource @setTargetResourceParameters } | Should -Throw $testInvalidArchivePathErrorMessage + { Set-TargetResource @setTargetResourceParameters } | Should -Throw -ExpectedMessage $testInvalidArchivePathErrorMessage } } @@ -703,7 +703,7 @@ Describe 'Archive Unit Tests' { } It 'Should throw an error for invalid destination' { - { Set-TargetResource @setTargetResourceParameters } | Should -Throw $testInvalidDestinationErrorMessage + { Set-TargetResource @setTargetResourceParameters } | Should -Throw -ExpectedMessage $testInvalidDestinationErrorMessage } } @@ -1398,7 +1398,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should -Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } @@ -1425,7 +1425,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should -Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } @@ -1454,7 +1454,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should -Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } @@ -1481,7 +1481,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should -Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } @@ -1512,7 +1512,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should -Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } @@ -1541,7 +1541,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should -Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } } @@ -1596,7 +1596,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for failed PSDrive creation' { $expectedPath = $mountPSDriveWithCredentialParameters.Path.Substring(0, $mountPSDriveWithCredentialParameters.Path.IndexOf('\')) $expectedErrorMessage = $script:localizedData.ErrorCreatingPSDrive -f $expectedPath, $mountPSDriveWithCredentialParameters.Credential.UserName - { $null = Mount-PSDriveWithCredential @mountPSDriveWithCredentialParameters } | Should -Throw $expectedErrorMessage + { $null = Mount-PSDriveWithCredential @mountPSDriveWithCredentialParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -1701,7 +1701,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for an invalid path' { $expectedErrorMessage = $script:localizedData.PathDoesNotContainValidPSDriveRoot -f $mountPSDriveWithCredentialParameters.Path - { $null = Mount-PSDriveWithCredential @mountPSDriveWithCredentialParameters } | Should -Throw $expectedErrorMessage + { $null = Mount-PSDriveWithCredential @mountPSDriveWithCredentialParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } @@ -1739,7 +1739,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for non-existent path' { $expectedErrorMessage = $script:localizedData.PathDoesNotExistAsLeaf -f $assertPathExistsAsLeafParameters.Path - { Assert-PathExistsAsLeaf @assertPathExistsAsLeafParameters } | Should -Throw $expectedErrorMessage + { Assert-PathExistsAsLeaf @assertPathExistsAsLeafParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } @@ -1799,7 +1799,7 @@ Describe 'Archive Unit Tests' { It 'Should throw error for file at destination' { $expectedErrorMessage = $script:localizedData.DestinationExistsAsFile -f $assertDestinationDoesNotExistAsFileParameters.Destination - { Assert-DestinationDoesNotExistAsFile @assertDestinationDoesNotExistAsFileParameters } | Should -Throw $expectedErrorMessage + { Assert-DestinationDoesNotExistAsFile @assertDestinationDoesNotExistAsFileParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } @@ -1817,7 +1817,7 @@ Describe 'Archive Unit Tests' { $testChecksumIsShaResult = Test-ChecksumIsSha @testChecksumIsShaParameters It 'Should return true' { - $testChecksumIsShaResult | Should -Be $true + $testChecksumIsShaResult | Should -BeTrue } } @@ -1833,7 +1833,7 @@ Describe 'Archive Unit Tests' { $testChecksumIsShaResult = Test-ChecksumIsSha @testChecksumIsShaParameters It 'Should return false' { - $testChecksumIsShaResult | Should -Be $false + $testChecksumIsShaResult | Should -BeFalse } } @@ -1849,7 +1849,7 @@ Describe 'Archive Unit Tests' { $testChecksumIsShaResult = Test-ChecksumIsSha @testChecksumIsShaParameters It 'Should return false' { - $testChecksumIsShaResult | Should -Be $false + $testChecksumIsShaResult | Should -BeFalse } } } @@ -1893,7 +1893,7 @@ Describe 'Archive Unit Tests' { It 'Should throw error for failure while opening archive entry' { $expectedErrorMessage = $script:localizedData.ErrorComparingHashes -f $testFileHashMatchesArchiveEntryHashParameters.FilePath, $testArchiveEntryFullName, $testFileHashMatchesArchiveEntryHashParameters.HashAlgorithmName - { $null = Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters } | Should -Throw $expectedErrorMessage + { $null = Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -1908,7 +1908,7 @@ Describe 'Archive Unit Tests' { It 'Should throw error for failure while opening a stream to the file' { $expectedErrorMessage = $script:localizedData.ErrorComparingHashes -f $testFileHashMatchesArchiveEntryHashParameters.FilePath, $testArchiveEntryFullName, $testFileHashMatchesArchiveEntryHashParameters.HashAlgorithmName - { $null = Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters } | Should -Throw $expectedErrorMessage + { $null = Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -1923,7 +1923,7 @@ Describe 'Archive Unit Tests' { It 'Should throw error for failure to retrieve the file hash or archive entry hash' { $expectedErrorMessage = $script:localizedData.ErrorComparingHashes -f $testFileHashMatchesArchiveEntryHashParameters.FilePath, $testArchiveEntryFullName, $testFileHashMatchesArchiveEntryHashParameters.HashAlgorithmName - { $null = Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters } | Should -Throw $expectedErrorMessage + { $null = Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -1999,7 +1999,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters | Should -Be $true + Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters | Should -BeTrue } } @@ -2088,7 +2088,7 @@ Describe 'Archive Unit Tests' { It 'Should return false' { $script:timesGetFileHashCalled = 0 - Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters | Should -Be $false + Test-FileHashMatchesArchiveEntryHash @testFileHashMatchesArchiveEntryHashParameters | Should -BeFalse } } } @@ -2287,7 +2287,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-FileMatchesArchiveEntryByChecksum @testFileMatchesArchiveEntryByChecksumParameters | Should -Be $false + Test-FileMatchesArchiveEntryByChecksum @testFileMatchesArchiveEntryByChecksumParameters | Should -BeFalse } } @@ -2347,7 +2347,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-FileMatchesArchiveEntryByChecksum @testFileMatchesArchiveEntryByChecksumParameters | Should -Be $true + Test-FileMatchesArchiveEntryByChecksum @testFileMatchesArchiveEntryByChecksumParameters | Should -BeTrue } } @@ -2403,7 +2403,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-FileMatchesArchiveEntryByChecksum @testFileMatchesArchiveEntryByChecksumParameters | Should -Be $false + Test-FileMatchesArchiveEntryByChecksum @testFileMatchesArchiveEntryByChecksumParameters | Should -BeFalse } } @@ -2459,7 +2459,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-FileMatchesArchiveEntryByChecksum @testFileMatchesArchiveEntryByChecksumParameters | Should -Be $true + Test-FileMatchesArchiveEntryByChecksum @testFileMatchesArchiveEntryByChecksumParameters | Should -BeTrue } } } @@ -2471,11 +2471,11 @@ Describe 'Archive Unit Tests' { } It 'Should not throw' { - { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should Not Throw + { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should -Not -Throw } It 'Should return false' { - Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should Be $false + Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should -BeFalse } } @@ -2485,11 +2485,11 @@ Describe 'Archive Unit Tests' { } It 'Should not throw' { - { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should Not Throw + { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should -Not -Throw } It 'Should return false' { - Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should Be $false + Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should -BeFalse } } @@ -2499,11 +2499,11 @@ Describe 'Archive Unit Tests' { } It 'Should not throw' { - { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should Not Throw + { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should -Not -Throw } It 'Should return false' { - Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should Be $false + Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should -BeFalse } } @@ -2513,11 +2513,11 @@ Describe 'Archive Unit Tests' { } It 'Should not throw' { - { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should Not Throw + { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should -Not -Throw } It 'Should return true' { - Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should Be $true + Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should -BeTrue } } @@ -2527,11 +2527,11 @@ Describe 'Archive Unit Tests' { } It 'Should not throw' { - { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should Not Throw + { $null = Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters } | Should -Not -Throw } It 'Should return true' { - Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should Be $true + Test-ArchiveEntryIsDirectory @testArchiveEntryNameIsDirectoryPathParameters | Should -BeTrue } } } @@ -2629,7 +2629,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $false + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeFalse } } @@ -2715,7 +2715,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $false + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeFalse } } @@ -2801,7 +2801,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $false + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeFalse } } @@ -2892,7 +2892,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $true + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeTrue } } @@ -2974,7 +2974,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $false + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeFalse } } @@ -3060,7 +3060,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $false + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeFalse } } @@ -3146,7 +3146,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $false + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeFalse } } @@ -3232,7 +3232,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $true + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeTrue } } @@ -3325,7 +3325,7 @@ Describe 'Archive Unit Tests' { } It 'Should return false' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $false + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeFalse } } @@ -3420,7 +3420,7 @@ Describe 'Archive Unit Tests' { } It 'Should return true' { - Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -Be $true + Test-ArchiveExistsAtDestination @testArchiveExistsAtDestinationParameters | Should -BeTrue } } } @@ -3568,7 +3568,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for failed copy from the file stream to the archive entry stream' { $expectedErrorMessage = $script:localizedData.ErrorCopyingFromArchiveToDestination -f $copyArchiveEntryToDestinationParameters.DestinationPath - { Copy-ArchiveEntryToDestination @copyArchiveEntryToDestinationParameters } | Should -Throw $expectedErrorMessage + { Copy-ArchiveEntryToDestination @copyArchiveEntryToDestinationParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -3857,7 +3857,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for attempting to overwrite an existing item without specifying the Force parameter' { $errorMessage = $script:localizedData.ForceNotSpecifiedToOverwriteItem -f $testItemPathAtDestination, $testArchiveEntryFullName - { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw $errorMessage + { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -3988,7 +3988,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for attempting to overwrite an existing item without specifying the Force parameter' { $errorMessage = $script:localizedData.ForceNotSpecifiedToOverwriteItem -f $testItemPathAtDestination, $testArchiveEntryFullName - { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw $errorMessage + { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -4483,7 +4483,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for attempting to overwrite an existing item without specifying the Force parameter' { $errorMessage = $script:localizedData.ForceNotSpecifiedToOverwriteItem -f $testItemPathAtDestination, $testArchiveEntryFullName - { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw $errorMessage + { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -4614,7 +4614,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for attempting to overwrite an existing item without specifying the Force parameter' { $errorMessage = $script:localizedData.ForceNotSpecifiedToOverwriteItem -f $testItemPathAtDestination, $testArchiveEntryFullName - { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw $errorMessage + { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -4850,7 +4850,7 @@ Describe 'Archive Unit Tests' { It 'Should throw an error for attempting to overwrite an existing item without specifying the Force parameter' { $errorMessage = $script:localizedData.ForceNotSpecifiedToOverwriteItem -f $testItemPathAtDestination, $testArchiveEntryFullName - { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw $errorMessage + { Expand-ArchiveToDestination @expandArchiveToDestinationParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -4954,7 +4954,7 @@ Describe 'Archive Unit Tests' { return $fileParameterCorrect -and $archiveEntryParameterCorrect -and $checksumParameterCorrect } - Assert-MockCalled -CommandName 'Test-FileMatchesArchiveEntryByChecksum' -Exactly 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Test-FileMatchesArchiveEntryByChecksum' -ParameterFilter $testFileMatchesArchiveEntryByChecksumParameterFilter -Exactly 1 -Scope 'Context' } It 'Should remove the existing item at the desired path of the archive entry at the destination' { @@ -6459,7 +6459,7 @@ Describe 'Archive Unit Tests' { return $fileParameterCorrect -and $archiveEntryParameterCorrect -and $checksumParameterCorrect } - Assert-MockCalled -CommandName 'Test-FileMatchesArchiveEntryByChecksum' -Exactly 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Test-FileMatchesArchiveEntryByChecksum' -ParameterFilter $testFileMatchesArchiveEntryByChecksumParameterFilter -Exactly 1 -Scope 'Context' } It 'Should not attempt to remove an existing file at the desired path of the archive entry at the destination' { @@ -6566,7 +6566,7 @@ Describe 'Archive Unit Tests' { return $fileParameterCorrect -and $archiveEntryParameterCorrect -and $checksumParameterCorrect } - Assert-MockCalled -CommandName 'Test-FileMatchesArchiveEntryByChecksum' -Exactly 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Test-FileMatchesArchiveEntryByChecksum' -ParameterFilter $testFileMatchesArchiveEntryByChecksumParameterFilter -Exactly 1 -Scope 'Context' } It 'Should remove the file at the desired path of the archive entry at the destination' { diff --git a/Tests/Unit/MSFT_EnvironmentResource.Tests.ps1 b/Tests/Unit/MSFT_EnvironmentResource.Tests.ps1 index 2c78453..2fea6e7 100644 --- a/Tests/Unit/MSFT_EnvironmentResource.Tests.ps1 +++ b/Tests/Unit/MSFT_EnvironmentResource.Tests.ps1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' # Import CommonTestHelper for Enter-DscResourceTestEnvironment, Exit-DscResourceTestEnvironment @@ -53,7 +53,7 @@ try } It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return the environment variable name' { @@ -77,7 +77,7 @@ try } It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return the environment variable name' { @@ -101,7 +101,7 @@ try } It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return the environment variable name' { @@ -125,7 +125,7 @@ try } It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return the environment variable name' { @@ -149,7 +149,7 @@ try } It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return the environment variable name' { @@ -173,7 +173,7 @@ try } It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return the environment variable name' { @@ -1176,7 +1176,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $script:mockEnvironmentVarName ` -Ensure 'Present' ` -Path $true - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1194,7 +1194,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $script:mockEnvironmentVarName ` -Ensure 'Present' ` -Path $true - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1212,7 +1212,7 @@ try -Value $expectedValue ` -Ensure 'Present' ` -Path $false - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1230,7 +1230,7 @@ try -Value $expectedValue ` -Ensure 'Present' ` -Path $false - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1248,7 +1248,7 @@ try -Value $expectedValue ` -Ensure 'Present' ` -Path $true - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1267,7 +1267,7 @@ try -Value $expectedValue ` -Ensure 'Present' ` -Path $true - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1298,7 +1298,7 @@ try -Value $expectedValue ` -Ensure 'Present' ` -Path $true - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1320,7 +1320,7 @@ try -Value $expectedValue ` -Ensure 'Present' ` -Path $true - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1338,7 +1338,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $script:mockEnvironmentVarName ` -Ensure 'Absent' ` -Path $true - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1356,7 +1356,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $script:mockEnvironmentVarName ` -Ensure 'Absent' ` -Path $true - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1374,7 +1374,7 @@ try -Value $expectedValue ` -Ensure 'Absent' ` -Path $false - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1392,7 +1392,7 @@ try -Value $expectedValue ` -Ensure 'Absent' ` -Path $false - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1424,7 +1424,7 @@ try -Value $expectedValue ` -Ensure 'Absent' ` -Path $true - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1446,7 +1446,7 @@ try -Value $expectedValue ` -Ensure 'Absent' ` -Path $true - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1464,7 +1464,7 @@ try -Value 'nonExistentValue' ` -Ensure 'Absent' ` -Path $true - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1486,7 +1486,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1503,7 +1503,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1523,7 +1523,7 @@ try -Ensure 'Present' ` -Path $false ` -Target @('Process') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1542,7 +1542,7 @@ try -Ensure 'Present' ` -Path $false ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1561,7 +1561,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1580,7 +1580,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1611,7 +1611,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1629,7 +1629,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1646,7 +1646,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1663,7 +1663,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1681,7 +1681,7 @@ try -Ensure 'Absent' ` -Path $false ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1700,7 +1700,7 @@ try -Ensure 'Absent' ` -Path $false ` -Target @('Process') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1731,7 +1731,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1752,7 +1752,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1772,7 +1772,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Process') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1794,7 +1794,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1813,7 +1813,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1832,7 +1832,7 @@ try -Ensure 'Present' ` -Path $false ` -Target @('Machine') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1851,7 +1851,7 @@ try -Ensure 'Present' ` -Path $false ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1870,7 +1870,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1892,7 +1892,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1924,7 +1924,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -1947,7 +1947,7 @@ try -Ensure 'Present' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1965,7 +1965,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -1983,7 +1983,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -2002,7 +2002,7 @@ try -Ensure 'Absent' ` -Path $false ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -2021,7 +2021,7 @@ try -Ensure 'Absent' ` -Path $false ` -Target @('Machine') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -2054,7 +2054,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should have called the correct mocks' { @@ -2077,7 +2077,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -2096,7 +2096,7 @@ try -Ensure 'Absent' ` -Path $true ` -Target @('Machine') - $testTargetResourceResult | Should -Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should have called the correct mocks' { @@ -2257,7 +2257,7 @@ try really really really long name that will not be accepted by the machine. ` really really really long name that will not be accepted by the machine.' ` -Target @('Machine') - } | Should -Throw $script:localizedData.ArgumentTooLong + } | Should -Throw -ExpectedMessage $script:localizedData.ArgumentTooLong } It 'Should throw exception when environment variable cannot be found to remove' { @@ -2298,7 +2298,7 @@ try $value = 'mockValue' { Set-EnvironmentVariable -Name $name -Value $value -Target @('Process') - } | Should -Throw $errorRecord + } | Should -Throw -ExpectedMessage $errorRecord } } } @@ -2311,21 +2311,21 @@ try $testPathInPathListWithCriteriaResult = Test-PathsInValue -ExistingPaths $existingPaths ` -QueryPaths 'path3' ` -FindCriteria 'Any' - $testPathInPathListWithCriteriaResult | Should -Be $true + $testPathInPathListWithCriteriaResult | Should -BeTrue } It 'Should return true when one of many paths is contained in path list' { $testPathInPathListWithCriteriaResult = Test-PathsInValue -ExistingPaths $existingPaths ` -QueryPaths 'path0;path7;path3;path8'` -FindCriteria 'Any' - $testPathInPathListWithCriteriaResult | Should -Be $true + $testPathInPathListWithCriteriaResult | Should -BeTrue } It 'Should return false when no path is contained in path list' { $testPathInPathListWithCriteriaResult = Test-PathsInValue -ExistingPaths $existingPaths ` -QueryPaths 'path0;path7;path8;path9' ` -FindCriteria 'Any' - $testPathInPathListWithCriteriaResult | Should -Be $false + $testPathInPathListWithCriteriaResult | Should -BeFalse } } @@ -2334,21 +2334,21 @@ try $testPathInPathListWithCriteriaResult = Test-PathsInValue -ExistingPaths $existingPaths ` -QueryPaths 'path3' ` -FindCriteria 'All' - $testPathInPathListWithCriteriaResult | Should -Be $true + $testPathInPathListWithCriteriaResult | Should -BeTrue } It 'Should return false when path is not contained in path list' { $testPathInPathListWithCriteriaResult = Test-PathsInValue -ExistingPaths $existingPaths ` -QueryPaths 'path4' ` -FindCriteria 'All' - $testPathInPathListWithCriteriaResult | Should -Be $false + $testPathInPathListWithCriteriaResult | Should -BeFalse } It 'Should return false when one of many paths is not contained in path list' { $testPathInPathListWithCriteriaResult = Test-PathsInValue -ExistingPaths $existingPaths ` -QueryPaths 'path1;path2;path3;path4' ` -FindCriteria 'All' - $testPathInPathListWithCriteriaResult | Should -Be $false + $testPathInPathListWithCriteriaResult | Should -BeFalse } } } diff --git a/Tests/Unit/MSFT_GroupResource.Tests.ps1 b/Tests/Unit/MSFT_GroupResource.Tests.ps1 index 5578b2d..31522be 100644 --- a/Tests/Unit/MSFT_GroupResource.Tests.ps1 +++ b/Tests/Unit/MSFT_GroupResource.Tests.ps1 @@ -119,7 +119,7 @@ Describe 'GroupResource Unit Tests' { } <# - Get-Group, Add-GroupMember, Remove-GroupMember, Clear-GroupMembers, Save-Group, + Get-Group, Add-GroupMember, Remove-GroupMember, Clear-GroupMember, Save-Group, Remove-Group, Find-Principal, and Remove-DisposableObject cannot be unit tested because they are wrapper functions for .NET class function calls. #> @@ -208,14 +208,14 @@ Describe 'GroupResource Unit Tests' { Context 'When called with the given group name' { It 'Should call Assert-GroupNameValid' { - $testTargetResourceResult = Test-TargetResource -GroupName $script:testGroupName + $null = Test-TargetResource -GroupName $script:testGroupName Assert-MockCalled -CommandName 'Assert-GroupNameValid' -ParameterFilter { $GroupName -eq $script:testGroupName } } } Context 'When called with all parameters when not on Nano Server' { It 'Should call Test-TargetResourceOnFullSKU' { - $testTargetResourceResult = Test-TargetResource -GroupName $script:testGroupName -Credential $script:testCredential + $null = Test-TargetResource -GroupName $script:testGroupName -Credential $script:testCredential Assert-MockCalled -CommandName 'Test-IsNanoServer' Assert-MockCalled -CommandName 'Test-TargetResourceOnFullSKU' -ParameterFilter { $GroupName -eq $script:testGroupName -and $Credential -eq $script:testCredential } @@ -226,7 +226,7 @@ Describe 'GroupResource Unit Tests' { It 'Should call Test-TargetResourceOnNanoServer' { Mock -CommandName 'Test-IsNanoServer' -MockWith { return $true } - $testTargetResourceResult = Test-TargetResource -GroupName $script:testGroupName -Credential $script:testCredential + $null = Test-TargetResource -GroupName $script:testGroupName -Credential $script:testCredential Assert-MockCalled -CommandName 'Test-IsNanoServer' Assert-MockCalled -CommandName 'Test-TargetResourceOnNanoServer' -ParameterFilter { $GroupName -eq $script:testGroupName -and $Credential -eq $script:testCredential } @@ -311,7 +311,7 @@ Describe 'GroupResource Unit Tests' { $LocalMachineScope ) - Test-IsLocalMachine -Scope $LocalMachineScope | Should -Be $true + Test-IsLocalMachine -Scope $LocalMachineScope | Should -BeTrue } $customLocalIPAddress = '123.4.5.6' @@ -319,7 +319,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true if custom local IP address provided and Get-CimInstance contains matching IP address' { Mock -CommandName 'Get-CimInstance' -MockWith { return @{ IPAddress = @($customLocalIPAddress, '789.1.2.3')} } - Test-IsLocalMachine -Scope $customLocalIPAddress | Should -Be $true + Test-IsLocalMachine -Scope $customLocalIPAddress | Should -BeTrue } } @@ -327,13 +327,13 @@ Describe 'GroupResource Unit Tests' { $customLocalIPAddress = '123.4.5.6' It 'Should return false if custom local IP address provided and Get-CimInstance returns null' { - Test-IsLocalMachine -Scope $customLocalIPAddress | Should -Be $false + Test-IsLocalMachine -Scope $customLocalIPAddress | Should -BeFalse } It 'Should return false if custom local IP address provided and Get-CimInstance do not contain matching IP addresses' { Mock -CommandName 'Get-CimInstance' -MockWith { return @{ IPAddress = @('789.1.2.3')} } - Test-IsLocalMachine -Scope $customLocalIPAddress | Should -Be $false + Test-IsLocalMachine -Scope $customLocalIPAddress | Should -BeFalse } } } @@ -429,7 +429,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue $getTargetResourceResult.Keys.Count | Should -Be 2 $getTargetResourceResult.GroupName | Should -Be $script:testGroupName $getTargetResourceResult.Ensure | Should -Be 'Absent' @@ -440,7 +440,7 @@ Describe 'GroupResource Unit Tests' { It 'Should throw expected exception' { Mock -CommandName 'Get-LocalGroup' -MockWith { Write-Error -Message $script:testErrorMessage -CategoryReason 'OtherException' } - { $getTargetResourceResult = Get-TargetResourceOnNanoServer -GroupName $script:testGroupName } | Should -Throw $script:testErrorMessage + { $null = Get-TargetResourceOnNanoServer -GroupName $script:testGroupName } | Should -Throw -ExpectedMessage $script:testErrorMessage Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } } @@ -457,7 +457,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group -eq $script:testLocalGroup } - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue $getTargetResourceResult.Keys.Count | Should -Be 4 $getTargetResourceResult.GroupName | Should -Be $script:testGroupName $getTargetResourceResult.Ensure | Should -Be 'Present' @@ -478,7 +478,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group -eq $script:testLocalGroup } - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue $getTargetResourceResult.Keys.Count | Should -Be 4 $getTargetResourceResult.GroupName | Should -Be $script:testGroupName $getTargetResourceResult.Ensure | Should -Be 'Present' @@ -767,7 +767,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { return @( $script:testMemberName1, $script:testMemberName2 ) } - { Set-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -MembersToInclude $testMembersToInclude -Ensure 'Present' } | Should -Throw $errorMessage + { Set-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -MembersToInclude $testMembersToInclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -780,7 +780,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { return @( $script:testMemberName1, $script:testMemberName2 ) } - { Set-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw $errorMessage + { Set-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -793,7 +793,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { return @( $script:testMemberName1, $script:testMemberName2 ) } - { Set-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToInclude $testMembersToInclude -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw $errorMessage + { Set-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToInclude $testMembersToInclude -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -903,7 +903,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true and expected mocks are called' { Mock -CommandName 'Get-LocalGroup' -MockWith { Write-Error -Message 'Test error message' -CategoryReason 'GroupNotFoundException' } - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Absent' | Should -Be $true + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Absent' | Should -BeTrue Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } } @@ -911,7 +911,7 @@ Describe 'GroupResource Unit Tests' { Context 'When Ensure is absent and the group exists' { It 'Should return false and expected mocks are called' { - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Absent' | Should -Be $false + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Absent' | Should -BeFalse Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } } @@ -921,7 +921,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return false and expected mocks are called' { Mock -CommandName 'Get-LocalGroup' -MockWith { Write-Error -Message 'Test error message' -CategoryReason 'GroupNotFoundException' } - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } } @@ -931,13 +931,13 @@ Describe 'GroupResource Unit Tests' { It 'Should throw expected exception' { Mock -CommandName 'Get-LocalGroup' -MockWith { Write-Error -Message $script:testErrorMessage -CategoryReason 'OtherException' } - { Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Present' } | Should -Throw $script:testErrorMessage + { Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Present' } | Should -Throw -ExpectedMessage $script:testErrorMessage } } Context 'When Ensure is present and the group exists' { It 'Should return true and expected mocks are called' { - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } } @@ -947,7 +947,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true and expected mocks are called' { $script:testLocalGroup.Description = $script:testGroupDescription - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Description $script:testGroupDescription -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Description $script:testGroupDescription -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } } @@ -957,7 +957,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return false and expected mocks are called' { $script:testLocalGroup.Description = $script:testGroupDescription - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Description 'Wrong description' -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Description 'Wrong description' -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } } @@ -967,7 +967,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true and expected mocks are called' { $testMembers = @( ) - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group.Name -eq $script:testGroupName } @@ -978,7 +978,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return false and expected mocks are called' { $testMembers = @( $script:testMemberName1 ) - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group.Name -eq $script:testGroupName } @@ -989,7 +989,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return false and expected mocks are called' { $testMembers = @( $script:testMemberName1 ) - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToInclude $testMembers -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToInclude $testMembers -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group.Name -eq $script:testGroupName } @@ -1000,7 +1000,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true and expected mocks are called' { $testMembers = @( $script:testMemberName1 ) - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToExclude $testMembers -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToExclude $testMembers -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group.Name -eq $script:testGroupName } @@ -1013,7 +1013,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { @( $script:testMemberName1, $script:testMemberName2 ) } - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToExclude $testMembers -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToExclude $testMembers -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group.Name -eq $script:testGroupName } @@ -1026,7 +1026,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { @( $script:testMemberName1, $script:testMemberName2 ) } - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToInclude $testMembers -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToInclude $testMembers -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group.Name -eq $script:testGroupName } @@ -1039,7 +1039,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { @( $script:testMemberName1, $script:testMemberName2 ) } - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group.Name -eq $script:testGroupName } @@ -1053,7 +1053,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-LocalGroup' -MockWith { return $script:testLocalGroup } Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { @( $script:testMemberName1, $script:testMemberName2 ) } - Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-LocalGroup' -ParameterFilter { $Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersOnNanoServer' -ParameterFilter { $Group.Name -eq $script:testGroupName } @@ -1070,7 +1070,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-LocalGroup' -MockWith { return $script:testLocalGroup } Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { @( $script:testMemberName1, $script:testMemberName2 ) } - { Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -MembersToInclude $testMembersToInclude -Ensure 'Present' } | Should -Throw $errorMessage + { Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -MembersToInclude $testMembersToInclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -1084,7 +1084,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-LocalGroup' -MockWith { return $script:testLocalGroup } Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { @( $script:testMemberName1, $script:testMemberName2 ) } - { Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw $errorMessage + { Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -Members $testMembers -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -1098,7 +1098,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Get-LocalGroup' -MockWith { return $script:testLocalGroup } Mock -CommandName 'Get-MembersOnNanoServer' -MockWith { @( $script:testMemberName1, $script:testMemberName2 ) } - { Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToInclude $testMembersToInclude -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw $errorMessage + { Test-TargetResourceOnNanoServer -GroupName $script:testGroupName -MembersToInclude $testMembersToInclude -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -1158,7 +1158,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } Assert-MockCalled -CommandName 'Remove-DisposableObject' - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue $getTargetResourceResult.Keys.Count | Should -Be 2 $getTargetResourceResult.GroupName | Should -Be $script:testGroupName $getTargetResourceResult.Ensure | Should -Be 'Absent' @@ -1177,7 +1177,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'Get-MembersOnFullSKU' -ParameterFilter { $Group -eq $script:testGroup } Assert-MockCalled -CommandName 'Remove-DisposableObject' - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue $getTargetResourceResult.Keys.Count | Should -Be 4 $getTargetResourceResult.GroupName | Should -Be $script:testGroupName $getTargetResourceResult.Ensure | Should -Be 'Present' @@ -1199,7 +1199,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'Get-MembersOnFullSKU' -ParameterFilter { $Group -eq $script:testGroup } Assert-MockCalled -CommandName 'Remove-DisposableObject' - $getTargetResourceResult -is [Hashtable] | Should -Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue $getTargetResourceResult.Keys.Count | Should -Be 4 $getTargetResourceResult.GroupName | Should -Be $script:testGroupName $getTargetResourceResult.Ensure | Should -Be 'Present' @@ -1225,7 +1225,7 @@ Describe 'GroupResource Unit Tests' { ( ) - Assert-MockCalled -CommandName 'Clear-GroupMembers' -Times 0 -Scope 'It' + Assert-MockCalled -CommandName 'Clear-GroupMember' -Times 0 -Scope 'It' Assert-MockCalled -CommandName 'Add-GroupMember' -Times 0 -Scope 'It' Assert-MockCalled -CommandName 'Remove-GroupMember' -Times 0 -Scope 'It' Assert-MockCalled -CommandName 'Save-Group' -Times 0 -Scope 'It' @@ -1258,7 +1258,7 @@ Describe 'GroupResource Unit Tests' { return $memberPrincipals } - Mock -CommandName 'Clear-GroupMembers' -MockWith { } + Mock -CommandName 'Clear-GroupMember' -MockWith { } Mock -CommandName 'Add-GroupMember' -MockWith { } Mock -CommandName 'Remove-GroupMember' -MockWith { } Mock -CommandName 'Remove-Group' -MockWith { } @@ -1495,7 +1495,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } Assert-MockCalled -CommandName 'Get-MembersAsPrincipalsList' -ParameterFilter { $Group.Name -eq $script:testGroupName } - Assert-MockCalled -CommandName 'Clear-GroupMembers' -ParameterFilter { $Group.Name -eq $script:testGroupName } + Assert-MockCalled -CommandName 'Clear-GroupMember' -ParameterFilter { $Group.Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Save-Group' -ParameterFilter { $Group.Name -eq $script:testGroupName } Assert-MockCalled -CommandName 'Remove-DisposableObject' } @@ -1569,7 +1569,7 @@ Describe 'GroupResource Unit Tests' { $errorMessage = $script:localizedData.MembersAndIncludeExcludeConflict -f 'Members', 'MembersToInclude' - { Set-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -MembersToInclude $testMembersToInclude -Ensure 'Present' } | Should -Throw $errorMessage + { Set-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -MembersToInclude $testMembersToInclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -1580,7 +1580,7 @@ Describe 'GroupResource Unit Tests' { $errorMessage = $script:localizedData.MembersAndIncludeExcludeConflict -f 'Members', 'MembersToExclude' - { Set-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw $errorMessage + { Set-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -1591,7 +1591,7 @@ Describe 'GroupResource Unit Tests' { $errorMessage = $script:localizedData.IncludeAndExcludeConflict -f $script:testUserPrincipal1.Name, 'MembersToInclude', 'MembersToExclude' - { Set-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToInclude $testMembersToInclude -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw $errorMessage + { Set-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToInclude $testMembersToInclude -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -1770,7 +1770,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true and expected mocks are called' { Mock -CommandName 'Get-Group' -MockWith { } - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Ensure 'Absent' | Should -Be $true + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Ensure 'Absent' | Should -BeTrue Assert-MockCalled -CommandName 'Get-PrincipalContext' -Scope 'It' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } -Scope 'It' @@ -1780,7 +1780,7 @@ Describe 'GroupResource Unit Tests' { Context 'When Ensure is absent and the group exists' { It 'Should return false and expected mocks are called' { - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Ensure 'Absent' | Should -Be $false + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Ensure 'Absent' | Should -BeFalse Assert-MockCalled -CommandName 'Get-PrincipalContext' -Scope 'It' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } -Scope 'It' @@ -1792,7 +1792,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return false and expected mocks are called' { Mock -CommandName 'Get-Group' -MockWith { } - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1802,7 +1802,7 @@ Describe 'GroupResource Unit Tests' { Context 'When Ensure is present and the group exists' { It 'Should return true and expected mocks are called' { - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1814,7 +1814,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true and expected mocks are called' { $script:testGroup.Description = $script:testGroupDescription - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Description $script:testGroupDescription -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Description $script:testGroupDescription -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1826,7 +1826,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return false and expected mocks are called' { $script:testGroup.Description = $script:testGroupDescription - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Description 'Wrong description' -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Description 'Wrong description' -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1838,7 +1838,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true and expected mocks are called' { $testMembers = @( ) - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1851,7 +1851,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return false and expected mocks are called' { $testMembers = @( $script:testUserPrincipal1.Name ) - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1864,7 +1864,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return false and expected mocks are called' { $testMembers = @( $script:testUserPrincipal1.Name ) - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToInclude $testMembers -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToInclude $testMembers -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1877,7 +1877,7 @@ Describe 'GroupResource Unit Tests' { It 'Should return true and expected mocks are called' { $testMembers = @( $script:testUserPrincipal1.Name ) - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToExclude $testMembers -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToExclude $testMembers -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1892,7 +1892,7 @@ Describe 'GroupResource Unit Tests' { $testMembers = @( $script:testUserPrincipal1.Name ) - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToExclude $testMembers -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToExclude $testMembers -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1907,7 +1907,7 @@ Describe 'GroupResource Unit Tests' { $testMembers = @( $script:testUserPrincipal1.Name ) - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToInclude $testMembers -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToInclude $testMembers -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1922,7 +1922,7 @@ Describe 'GroupResource Unit Tests' { $testMembers = @( $script:testUserPrincipal1, $script:testUserPrincipal2 ) - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -Be $true + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1937,7 +1937,7 @@ Describe 'GroupResource Unit Tests' { $testMembers = @( $script:testUserPrincipal1, $script:testUserPrincipal3 ) - Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -Be $false + Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-PrincipalContext' Assert-MockCalled -CommandName 'Get-Group' -ParameterFilter { $GroupName -eq $script:testGroupName } @@ -1994,7 +1994,7 @@ Describe 'GroupResource Unit Tests' { $errorMessage = $script:localizedData.MembersAndIncludeExcludeConflict -f 'Members', 'MembersToInclude' - { Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -MembersToInclude $testMembersToInclude -Ensure 'Present' } | Should -Throw $errorMessage + { Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -MembersToInclude $testMembersToInclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2007,7 +2007,7 @@ Describe 'GroupResource Unit Tests' { $errorMessage = $script:localizedData.MembersAndIncludeExcludeConflict -f 'Members', 'MembersToExclude' - { Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw $errorMessage + { Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -Members $testMembers -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2020,7 +2020,7 @@ Describe 'GroupResource Unit Tests' { $errorMessage = $script:localizedData.IncludeAndExcludeConflict -f $script:testUserPrincipal1.Name, 'MembersToInclude', 'MembersToExclude' - { Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToInclude $testMembersToInclude -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw $errorMessage + { Test-TargetResourceOnFullSKU -GroupName $script:testGroupName -MembersToInclude $testMembersToInclude -MembersToExclude $testMembersToExclude -Ensure 'Present' } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -2197,7 +2197,7 @@ Describe 'GroupResource Unit Tests' { Mock -CommandName 'Test-IsLocalMachine' -MockWith { return $false } Mock -CommandName 'Get-GroupMembersFromDirectoryEntry' -MockWith { return @( $memberDirectoryEntry1, $memberDirectoryEntry2 ) } - $getMembersResult = Get-MembersAsPrincipalsList -Group $script:testGroup -Credential $script:testCredential -PrincipalContextCache $principalContextCache -Disposables $disposables + $null = Get-MembersAsPrincipalsList -Group $script:testGroup -Credential $script:testCredential -PrincipalContextCache $principalContextCache -Disposables $disposables Assert-MockCalled -CommandName 'Get-PrincipalContext' -ParameterFilter { $Credential -eq $script:testCredential } Assert-MockCalled -CommandName 'Get-PrincipalContext' -ParameterFilter { $Credential -eq $script:testCredential} @@ -2212,7 +2212,7 @@ Describe 'GroupResource Unit Tests' { $errorMessage = ($script:localizedData.DomainCredentialsRequired -f 'accountname') - { Get-MembersAsPrincipalsList -Group $script:testGroup -PrincipalContextCache $principalContextCache -Disposables $disposables } | Should -Throw $errorMessage + { Get-MembersAsPrincipalsList -Group $script:testGroup -PrincipalContextCache $principalContextCache -Disposables $disposables } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -2347,10 +2347,10 @@ Describe 'GroupResource Unit Tests' { $errorMessage = ($script:localizedData.CouldNotFindPrincipal -f $script:testUserPrincipal1.Name) - { $convertToPrincipalResult = ConvertTo-Principal ` + { $null = ConvertTo-Principal ` -MemberName $script:testUserPrincipal1.Name ` -PrincipalContextCache $principalContextCache ` - -Disposables $disposables } | Should -Throw $errorMessage + -Disposables $disposables } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -2422,9 +2422,9 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'Test-IsLocalMachine' -ParameterFilter { $Scope -eq $localScope } Assert-MockCalled -CommandName 'New-Object' -ParameterFilter { $TypeName -eq 'System.DirectoryServices.AccountManagement.PrincipalContext' -and $ArgumentList.Contains($localMachineContext) } - $principalContextCache.ContainsKey($localScope) | Should -Be $false + $principalContextCache.ContainsKey($localScope) | Should -BeFalse $principalContextCache.$script:localDomain | Should -Be $fakePrincipalContext - $disposables.Contains($fakePrincipalContext) | Should -Be $true + $disposables.Contains($fakePrincipalContext) | Should -BeTrue } } @@ -2441,7 +2441,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'New-Object' -ParameterFilter { $TypeName -eq 'System.DirectoryServices.AccountManagement.PrincipalContext' } -Times 0 -Scope 'It' $principalContextCache.$script:localDomain | Should -Not -Be $fakePrincipalContext - $disposables.Contains($fakePrincipalContext) | Should -Be $false + $disposables.Contains($fakePrincipalContext) | Should -BeFalse } } @@ -2462,7 +2462,7 @@ Describe 'GroupResource Unit Tests' { (Compare-Object -ReferenceObject $principalContextArgumentList -DifferenceObject $ArgumentList) -eq $null } $principalContextCache.$customDomain | Should -Be $fakePrincipalContext - $disposables.Contains($fakePrincipalContext) | Should -Be $true + $disposables.Contains($fakePrincipalContext) | Should -BeTrue } } @@ -2483,12 +2483,12 @@ Describe 'GroupResource Unit Tests' { (Compare-Object -ReferenceObject $principalContextArgumentList -DifferenceObject $ArgumentList) -eq $null } $principalContextCache.$customDomain | Should -Be $fakePrincipalContext - $disposables.Contains($fakePrincipalContext) | Should -Be $true + $disposables.Contains($fakePrincipalContext) | Should -BeTrue } } Context 'When called with a domain principal that does not exist in the principal cache and with a Credential with a domain' { - It 'Should create a new custom principal context with a credential with a domain' { + It 'Should create a new custom principal context with a Credential with a domain' { $principalContextCache = @{} $disposables = New-Object -TypeName 'System.Collections.ArrayList' @@ -2510,7 +2510,7 @@ Describe 'GroupResource Unit Tests' { (Compare-Object -ReferenceObject $principalContextArgumentList -DifferenceObject $ArgumentList) -eq $null } $principalContextCache.$customDomain | Should -Be $fakePrincipalContext - $disposables.Contains($fakePrincipalContext) | Should -Be $true + $disposables.Contains($fakePrincipalContext) | Should -BeTrue } } @@ -2527,7 +2527,7 @@ Describe 'GroupResource Unit Tests' { Assert-MockCalled -CommandName 'New-Object' -ParameterFilter { $TypeName -eq 'System.DirectoryServices.AccountManagement.PrincipalContext' } -Times 0 -Scope 'It' $principalContextCache.$customDomain | Should -Not -Be $fakePrincipalContext - $disposables.Contains($fakePrincipalContext) | Should -Be $false + $disposables.Contains($fakePrincipalContext) | Should -BeFalse } } } diff --git a/Tests/Unit/MSFT_MsiPackage.Tests.ps1 b/Tests/Unit/MSFT_MsiPackage.Tests.ps1 index 8516b3c..b6b2def 100644 --- a/Tests/Unit/MSFT_MsiPackage.Tests.ps1 +++ b/Tests/Unit/MSFT_MsiPackage.Tests.ps1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' Describe 'MsiPackage Unit Tests' { @@ -37,12 +37,12 @@ Describe 'MsiPackage Unit Tests' { $script:testWrongProductId = 'wrongId' $script:testPath = 'file://test.msi' $script:destinationPath = Join-Path -Path $script:packageCacheLocation -ChildPath 'C:\' - $script:testUriHttp = [Uri] 'http://test.msi' - $script:testUriHttps = [Uri] 'https://test.msi' - $script:testUriFile = [Uri] 'file://test.msi' - $script:testUriNonUnc = [Uri] 'file:///C:/test.msi' - $script:testUriQuery = [Uri] 'http://C:/directory/test/test.msi?sv=2017-01-31&spr=https' - $script:testUriOnlyFile = [Uri] 'test.msi' + $script:testUriHttp = [System.Uri] 'http://test.msi' + $script:testUriHttps = [System.Uri] 'https://test.msi' + $script:testUriFile = [System.Uri] 'file://test.msi' + $script:testUriNonUnc = [System.Uri] 'file:///C:/test.msi' + $script:testUriQuery = [System.Uri] 'http://C:/directory/test/test.msi?sv=2017-01-31&spr=https' + $script:testUriOnlyFile = [System.Uri] 'test.msi' $script:mockStream = New-MockObject -Type 'System.IO.FileStream' $script:mockWebRequest = New-MockObject -Type 'System.Net.HttpWebRequest' @@ -123,7 +123,7 @@ Describe 'MsiPackage Unit Tests' { -ExpectedReturnValue $expectedReturnValue } } - + Describe 'Set-TargetResource' { $setTargetResourceParameters = @{ ProductId = 'TestProductId' @@ -138,7 +138,7 @@ Describe 'MsiPackage Unit Tests' { ServerCertificateValidationCallback = 'TestValidationCallback' RunAsCredential = $script:testCredential } - + Mock -CommandName 'Convert-PathToUri' -MockWith { return $script:testUriNonUnc } Mock -CommandName 'Convert-ProductIdToIdentifyingNumber' -MockWith { return $script:testIdentifyingNumber } Mock -CommandName 'Assert-PathExtensionValid' -MockWith {} @@ -146,19 +146,22 @@ Describe 'MsiPackage Unit Tests' { Mock -CommandName 'New-PSDrive' -MockWith { return $script:mockPSDrive } Mock -CommandName 'Test-Path' -MockWith { return $true } Mock -CommandName 'New-Item' -MockWith {} - Mock -CommandName 'New-Object' -MockWith { return $script:mockStream } #-ParameterFilter { $TypeName -eq 'System.IO.FileStream' } + Mock -CommandName 'New-Object' -MockWith { return $script:mockStream } Mock -CommandName 'Get-WebRequestResponse' -MockWith { return $script:mockStream } Mock -CommandName 'Copy-ResponseStreamToFileStream' -MockWith {} Mock -CommandName 'Close-Stream' -MockWith {} Mock -CommandName 'Assert-FileValid' -MockWith {} Mock -CommandName 'Get-MsiProductCode' -MockWith { return $script:testIdentifyingNumber } - Mock -CommandName 'Start-MsiProcess' -MockWith { return 0 } # returns the exit code + Mock -CommandName 'Start-MsiProcess' -MockWith { + # Returns the exit code + return 0 + } Mock -CommandName 'Remove-PSDrive' -MockWith {} Mock -CommandName 'Remove-Item' -MockWith {} Mock -CommandName 'Invoke-CimMethod' -MockWith {} Mock -CommandName 'Get-ItemProperty' -MockWith { return $null } Mock -CommandName 'Get-ProductEntry' -MockWith { return $script:mockProductEntry } - + Context 'Uri scheme is non-UNC file and installation succeeds' { $mocksCalled = @( @{ Command = 'Convert-PathToUri'; Times = 1 } @@ -219,13 +222,13 @@ Describe 'MsiPackage Unit Tests' { @{ Command = 'Assert-PathExtensionValid'; Times = 1 } @{ Command = 'New-LogFile'; Times = 1 } @{ Command = 'New-PSDrive'; Times = 0 } - @{ Command = 'Test-Path'; Times = 2; Custom = 'to the package cache' } + @{ Command = 'Test-Path'; Times = 3; Custom = 'to the package cache' } @{ Command = 'New-Item'; Times = 0; Custom = 'directory for the package cache' } @{ Command = 'New-Object'; Times = 1; Custom = 'file stream to copy the response to' } @{ Command = 'Get-WebRequestResponse'; Times = 1 } @{ Command = 'Copy-ResponseStreamToFileStream'; Times = 1 } @{ Command = 'Close-Stream'; Times = 2 } - @{ Command = 'Test-Path'; Times = 2; Custom = 'to the MSI file' } + @{ Command = 'Test-Path'; Times = 3; Custom = 'to the MSI file' } @{ Command = 'Assert-FileValid'; Times = 1 } @{ Command = 'Get-MsiProductCode'; Times = 1 } @{ Command = 'Start-MsiProcess'; Times = 1 } @@ -250,13 +253,13 @@ Describe 'MsiPackage Unit Tests' { @{ Command = 'Assert-PathExtensionValid'; Times = 1 } @{ Command = 'New-LogFile'; Times = 1 } @{ Command = 'New-PSDrive'; Times = 0 } - @{ Command = 'Test-Path'; Times = 2; Custom = 'to the package cache' } + @{ Command = 'Test-Path'; Times = 3; Custom = 'to the package cache' } @{ Command = 'New-Item'; Times = 0; Custom = 'directory for the package cache' } @{ Command = 'New-Object'; Times = 1; Custom = 'file stream to copy the response to' } @{ Command = 'Get-WebRequestResponse'; Times = 1 } @{ Command = 'Copy-ResponseStreamToFileStream'; Times = 1 } @{ Command = 'Close-Stream'; Times = 2 } - @{ Command = 'Test-Path'; Times = 2; Custom = 'to the MSI file' } + @{ Command = 'Test-Path'; Times = 3; Custom = 'to the MSI file' } @{ Command = 'Assert-FileValid'; Times = 1 } @{ Command = 'Get-MsiProductCode'; Times = 1 } @{ Command = 'Start-MsiProcess'; Times = 1 } @@ -349,7 +352,7 @@ Describe 'MsiPackage Unit Tests' { -ErrorMessage ($script:localizedData.PostValidationError -f $setTargetResourceParameters.Path) ` -ErrorTestName $script:errorMessageTitles.PostValidationError } - + Mock -CommandName 'Get-MsiProductCode' -MockWith { return $script:testWrongProductId } Context 'Product code from downloaded MSI package does not match specified ID' { @@ -462,7 +465,7 @@ Describe 'MsiPackage Unit Tests' { Describe 'Assert-PathExtensionValid' { Context 'Path is a valid .msi path' { It 'Should not throw' { - { Assert-PathExtensionValid -Path 'testMsiFile.msi' } | Should Not Throw + { Assert-PathExtensionValid -Path 'testMsiFile.msi' } | Should -Not -Throw } } @@ -471,14 +474,14 @@ Describe 'MsiPackage Unit Tests' { $invalidPath = 'testMsiFile.exe' $expectedErrorMessage = ($script:localizedData.InvalidBinaryType -f $invalidPath) - { Assert-PathExtensionValid -Path $invalidPath } | Should Throw $expectedErrorMessage + { Assert-PathExtensionValid -Path $invalidPath } | Should -Throw -ExpectedMessage $expectedErrorMessage } It 'Should throw an invalid argument exception when an invalid file type is passed in' { $invalidPath = 'testMsiFilemsi' $expectedErrorMessage = ($script:localizedData.InvalidBinaryType -f $invalidPath) - { Assert-PathExtensionValid -Path $invalidPath } | Should Throw $expectedErrorMessage + { Assert-PathExtensionValid -Path $invalidPath } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } @@ -487,39 +490,41 @@ Describe 'MsiPackage Unit Tests' { Context 'Path has a valid URI scheme' { It 'Should return the expected URI when scheme is a file' { $filePath = (Join-Path -Path $PSScriptRoot -ChildPath 'testMsi.msi') - $expectedReturnValue = [Uri] $filePath + $expectedReturnValue = [System.Uri] $filePath - Convert-PathToUri -Path $filePath | Should Be $expectedReturnValue + Convert-PathToUri -Path $filePath | Should -Be $expectedReturnValue } - - It 'Should return the expected URI when scheme is http' { - $filePath = 'http://localhost:1242/testMsi.msi' - $expectedReturnValue = [Uri] $filePath - Convert-PathToUri -Path $filePath | Should Be $expectedReturnValue + It 'Should return the expected URI when scheme is http' { + $uriBuilder = [System.UriBuilder]::new('http', 'localhost') + $uriBuilder.Path = 'testMsi.msi' + $filePath = $uriBuilder.Uri.AbsoluteUri + + Convert-PathToUri -Path $filePath | Should -Be $uriBuilder.Uri } It 'Should return the expected URI when scheme is https' { - $filePath = 'https://localhost:1243/testMsi.msi' - $expectedReturnValue = [Uri] $filePath + $uriBuilder = [System.UriBuilder]::new('https', 'localhost') + $uriBuilder.Path = 'testMsi.msi' + $filePath = $uriBuilder.Uri.AbsoluteUri - Convert-PathToUri -Path $filePath | Should Be $expectedReturnValue + Convert-PathToUri -Path $filePath | Should -Be $uriBuilder.Uri } } Context 'Invalid path passed in' { It 'Should throw an error when uri scheme is invalid' { - $filePath = 'ht://localhost:1243/testMsi.msi' + $filePath = 'ht://localhost/testMsi.msi' $expectedErrorMessage = ($script:localizedData.InvalidPath -f $filePath) - { Convert-PathToUri -Path $filePath } | Should Throw $expectedErrorMessage + { Convert-PathToUri -Path $filePath } | Should -Throw -ExpectedMessage $expectedErrorMessage } It 'Should throw an error when path is not in valid format' { $filePath = 'mri' $expectedErrorMessage = ($script:localizedData.InvalidPath -f $filePath) - { Convert-PathToUri -Path $filePath } | Should Throw $expectedErrorMessage + { Convert-PathToUri -Path $filePath } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } @@ -527,18 +532,18 @@ Describe 'MsiPackage Unit Tests' { Describe 'Convert-ProductIdToIdentifyingNumber' { Context 'Valid Product ID is passed in' { It 'Should return the same value that is passed in when the Product ID is already in the correct format' { - Convert-ProductIdToIdentifyingNumber -ProductId $script:testIdentifyingNumber | Should Be $script:testIdentifyingNumber + Convert-ProductIdToIdentifyingNumber -ProductId $script:testIdentifyingNumber | Should -Be $script:testIdentifyingNumber } It 'Should convert a valid poduct ID to the identifying number format' { - Convert-ProductIdToIdentifyingNumber -ProductId $script:testProductId | Should Be $script:testIdentifyingNumber + Convert-ProductIdToIdentifyingNumber -ProductId $script:testProductId | Should -Be $script:testIdentifyingNumber } } Context 'Invalid Product ID is passed in' { It 'Should throw an exception when an invalid product ID is passed in' { $expectedErrorMessage = ($script:localizedData.InvalidIdentifyingNumber -f $script:testWrongProductId) - { Convert-ProductIdToIdentifyingNumber -ProductId $script:testWrongProductId } | Should Throw $expectedErrorMessage + { Convert-ProductIdToIdentifyingNumber -ProductId $script:testWrongProductId } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } @@ -552,7 +557,7 @@ Describe 'MsiPackage Unit Tests' { Context 'Product entry is found in the expected location' { It 'Should return the expected product entry' { - Get-ProductEntry -IdentifyingNumber $script:testIdentifyingNumber | Should Be $script:mockProductEntry + Get-ProductEntry -IdentifyingNumber $script:testIdentifyingNumber | Should -Be $script:mockProductEntry } It 'Should retrieve the item' { @@ -564,7 +569,7 @@ Describe 'MsiPackage Unit Tests' { Context 'Product entry is found under Wow6432Node' { It 'Should return the expected product entry' { - Get-ProductEntry -IdentifyingNumber $script:testIdentifyingNumber | Should Be $script:mockProductEntry + Get-ProductEntry -IdentifyingNumber $script:testIdentifyingNumber | Should -Be $script:mockProductEntry } It 'Should attempt to retrieve the item twice' { @@ -576,7 +581,7 @@ Describe 'MsiPackage Unit Tests' { Context 'Product entry is not found' { It 'Should return $null' { - Get-ProductEntry -IdentifyingNumber $script:testIdentifyingNumber | Should Be $null + Get-ProductEntry -IdentifyingNumber $script:testIdentifyingNumber | Should -Be $null } It 'Should attempt to retrieve the item twice' { @@ -599,31 +604,31 @@ Describe 'MsiPackage Unit Tests' { $getProductEntryInfoResult = Get-ProductEntryInfo -ProductEntry $script:mockProductEntry It 'Should return the expected installed date' { - $getProductEntryInfoResult.InstalledOn | Should Be $script:mockProductEntryInfo.InstalledOn + $getProductEntryInfoResult.InstalledOn | Should -Be $script:mockProductEntryInfo.InstalledOn } It 'Should return the expected publisher' { - $getProductEntryInfoResult.Publisher | Should Be $script:mockProductEntryInfo.Publisher + $getProductEntryInfoResult.Publisher | Should -Be $script:mockProductEntryInfo.Publisher } It 'Should return the expected size' { - $getProductEntryInfoResult.Size | Should Be ($script:mockProductEntryInfo.Size / 1024) + $getProductEntryInfoResult.Size | Should -Be ($script:mockProductEntryInfo.Size / 1024) } It 'Should return the expected Version' { - $getProductEntryInfoResult.Version | Should Be $script:mockProductEntryInfo.Version + $getProductEntryInfoResult.Version | Should -Be $script:mockProductEntryInfo.Version } It 'Should return the expected package description' { - $getProductEntryInfoResult.PackageDescription | Should Be $script:mockProductEntryInfo.PackageDescription + $getProductEntryInfoResult.PackageDescription | Should -Be $script:mockProductEntryInfo.PackageDescription } It 'Should return the expected name' { - $getProductEntryInfoResult.Name | Should Be $script:mockProductEntryInfo.Name + $getProductEntryInfoResult.Name | Should -Be $script:mockProductEntryInfo.Name } It 'Should return the expected install source' { - $getProductEntryInfoResult.InstallSource | Should Be $script:mockProductEntryInfo.InstallSource + $getProductEntryInfoResult.InstallSource | Should -Be $script:mockProductEntryInfo.InstallSource } It 'Should retrieve 7 product entry values' { @@ -638,7 +643,7 @@ Describe 'MsiPackage Unit Tests' { $getProductEntryInfoResult = Get-ProductEntryInfo -ProductEntry $script:mockProductEntry It 'Should return $null for InstalledOn' { - $getProductEntryInfoResult.InstalledOn | Should Be $null + $getProductEntryInfoResult.InstalledOn | Should -Be $null } } } @@ -686,7 +691,7 @@ Describe 'MsiPackage Unit Tests' { -ErrorTestName $script:errorMessageTitles.CouldNotOpenLog } } - + Describe 'Get-WebRequestResponse' { Mock -CommandName 'Get-WebRequest' -MockWith { return $script:mockWebRequest } Mock -CommandName 'Get-ScriptBlock' -MockWith { return { Write-Verbose 'Hello World' } } @@ -700,9 +705,9 @@ Describe 'MsiPackage Unit Tests' { ) It 'Should return the expected response stream' { - Get-WebRequestResponse -Uri $script:testUriHttp | Should Be $script:mockStream + Get-WebRequestResponse -Uri $script:testUriHttp | Should -Be $script:mockStream } - + Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled } @@ -714,9 +719,9 @@ Describe 'MsiPackage Unit Tests' { ) It 'Should return the expected response stream' { - Get-WebRequestResponse -Uri $script:testUriHttps | Should Be $script:mockStream + Get-WebRequestResponse -Uri $script:testUriHttps | Should -Be $script:mockStream } - + Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled } @@ -728,7 +733,7 @@ Describe 'MsiPackage Unit Tests' { ) It 'Should return the expected response stream' { - Get-WebRequestResponse -Uri $script:testUriHttps -ServerCertificateValidationCallback 'TestCallbackFunction' | Should Be $script:mockStream + Get-WebRequestResponse -Uri $script:testUriHttps -ServerCertificateValidationCallback 'TestCallbackFunction' | Should -Be $script:mockStream } Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled @@ -739,7 +744,7 @@ Describe 'MsiPackage Unit Tests' { Context 'Error occurred during while retrieving the response' { It 'Should throw the expected exception' { $expectedErrorMessage = ($script:localizedData.CouldNotGetResponseFromWebRequest -f $script:testUriHttp.Scheme, $script:testUriHttp.OriginalString) - { Get-WebRequestResponse -Uri $script:testUriHttp } | Should Throw $expectedErrorMessage + { Get-WebRequestResponse -Uri $script:testUriHttp } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } @@ -755,7 +760,7 @@ Describe 'MsiPackage Unit Tests' { ) It 'Should not throw' { - { Assert-FileValid -Path $script:testPath -FileHash 'mockFileHash' } | Should Not Throw + { Assert-FileValid -Path $script:testPath -FileHash 'mockFileHash' } | Should -Not -Throw } Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled @@ -768,7 +773,7 @@ Describe 'MsiPackage Unit Tests' { ) It 'Should not throw' { - { Assert-FileValid -Path $script:testPath -FileHash 'mockFileHash' -SignerThumbprint 'mockSignerThumbprint' } | Should Not Throw + { Assert-FileValid -Path $script:testPath -FileHash 'mockFileHash' -SignerThumbprint 'mockSignerThumbprint' } | Should -Not -Throw } Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled @@ -781,7 +786,7 @@ Describe 'MsiPackage Unit Tests' { ) It 'Should not throw' { - { Assert-FileValid -Path $script:testPath -SignerSubject 'mockSignerSubject' } | Should Not Throw + { Assert-FileValid -Path $script:testPath -SignerSubject 'mockSignerSubject' } | Should -Not -Throw } Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled @@ -797,7 +802,7 @@ Describe 'MsiPackage Unit Tests' { { Assert-FileValid -Path $script:testPath -FileHash 'mockFileHash' ` -SignerThumbprint 'mockSignerThumbprint' ` -SignerSubject 'mockSignerSubject' - } | Should Not Throw + } | Should -Not -Throw } Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled @@ -812,7 +817,7 @@ Describe 'MsiPackage Unit Tests' { It 'Should not throw' { { Assert-FileValid -Path $script:testPath -SignerThumbprint 'mockSignerThumbprint' ` -SignerSubject 'mockSignerSubject' - } | Should Not Throw + } | Should -Not -Throw } Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled @@ -825,7 +830,7 @@ Describe 'MsiPackage Unit Tests' { ) It 'Should not throw' { - { Assert-FileValid -Path $script:testPath } | Should Not Throw + { Assert-FileValid -Path $script:testPath } | Should -Not -Throw } Invoke-ExpectedMocksAreCalledTest -MocksCalled $mocksCalled @@ -838,7 +843,7 @@ Describe 'MsiPackage Unit Tests' { Context 'File hash is valid' { It 'Should not throw when hashes match' { - { Assert-FileHashValid -Path $script:testPath -Hash $mockHash.Hash -Algorithm 'SHA256' } | Should Not Throw + { Assert-FileHashValid -Path $script:testPath -Hash $mockHash.Hash -Algorithm 'SHA256' } | Should -Not -Throw } It 'Should fetch the file hash' { @@ -851,7 +856,7 @@ Describe 'MsiPackage Unit Tests' { $expectedErrorMessage = ($script:localizedData.InvalidFileHash -f $script:testPath, $badHash, 'SHA256') It 'Should throw when hashes do not match' { - { Assert-FileHashValid -Path $script:testPath -Hash $badHash -Algorithm 'SHA256' } | Should Throw $expectedErrorMessage + { Assert-FileHashValid -Path $script:testPath -Hash $badHash -Algorithm 'SHA256' } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } @@ -859,7 +864,7 @@ Describe 'MsiPackage Unit Tests' { Describe 'Assert-FileSignatureValid' { $mockThumbprint = 'mockThumbprint' $mockSubject = 'mockSubject' - $mockSignature = @{ + $mockSignature = @{ Status = [System.Management.Automation.SignatureStatus]::Valid SignerCertificate = @{ Thumbprint = $mockThumbprint; Subject = $mockSubject } } @@ -868,25 +873,25 @@ Describe 'MsiPackage Unit Tests' { Context 'File signature status, thumbprint and subject are valid' { It 'Should not throw' { - { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $mockThumbprint -Subject $mockSubject } | Should Not Throw + { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $mockThumbprint -Subject $mockSubject } | Should -Not -Throw } } Context 'File signature status and thumbprint are valid and Subject not passed in' { It 'Should not throw' { - { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $mockThumbprint } | Should Not Throw + { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $mockThumbprint } | Should -Not -Throw } } Context 'File signature status and subject are valid and Thumbprint not passed in' { It 'Should not throw' { - { Assert-FileSignatureValid -Path $script:testPath -Subject $mockSubject } | Should Not Throw + { Assert-FileSignatureValid -Path $script:testPath -Subject $mockSubject } | Should -Not -Throw } } Context 'Only Path is passed in' { It 'Should not throw' { - { Assert-FileSignatureValid -Path $script:testPath } | Should Not Throw + { Assert-FileSignatureValid -Path $script:testPath } | Should -Not -Throw } } @@ -895,7 +900,7 @@ Describe 'MsiPackage Unit Tests' { $expectedErrorMessage = ($script:localizedData.WrongSignerSubject -f $script:testPath, $badSubject) It 'Should throw expected error message' { - { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $mockThumbprint -Subject $badSubject } | Should Throw $expectedErrorMessage + { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $mockThumbprint -Subject $badSubject } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -904,7 +909,7 @@ Describe 'MsiPackage Unit Tests' { $expectedErrorMessage = ($script:localizedData.WrongSignerThumbprint -f $script:testPath, $badThumbprint) It 'Should throw expected error message' { - { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $badThumbprint -Subject $mockSubject } | Should Throw $expectedErrorMessage + { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $badThumbprint -Subject $mockSubject } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -913,7 +918,7 @@ Describe 'MsiPackage Unit Tests' { $expectedErrorMessage = ($script:localizedData.InvalidFileSignature -f $script:testPath, $mockSignature.Status) It 'Should throw expected error message' { - { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $mockThumbprint -Subject $mockSubject } | Should Throw $expectedErrorMessage + { Assert-FileSignatureValid -Path $script:testPath -Thumbprint $mockThumbprint -Subject $mockSubject } | Should -Throw -ExpectedMessage $expectedErrorMessage } } } diff --git a/Tests/Unit/MSFT_RegistryResource.Tests.ps1 b/Tests/Unit/MSFT_RegistryResource.Tests.ps1 index e3dbdbb..a390b1b 100644 --- a/Tests/Unit/MSFT_RegistryResource.Tests.ps1 +++ b/Tests/Unit/MSFT_RegistryResource.Tests.ps1 @@ -18,7 +18,7 @@ try $script:validRegistryDriveRoots = @( 'HKEY_CLASSES_ROOT', 'HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE', 'HKEY_USERS', 'HKEY_CURRENT_CONFIG' ) $script:validRegistryDriveNames = @( 'HKCR', 'HKCU', 'HKLM', 'HKUS', 'HKCC' ) - + # This registry key is used ONLY for its type (Microsoft.Win32.RegistryKey). It is not actually accessed in any way during these tests. $script:testRegistryKey = [Microsoft.Win32.Registry]::CurrentConfig @@ -37,9 +37,9 @@ try Key = 'TestRegistryKey' ValueName = '' } - + It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -70,34 +70,34 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return 5 hashtable properties' { - $getTargetResourceResult.Keys.Count | Should Be 5 + $getTargetResourceResult.Keys.Count | Should -Be 5 } It 'Should return the Key property as the given registry key path' { - $getTargetResourceResult.Key | Should Be $getTargetResourceParameters.Key + $getTargetResourceResult.Key | Should -Be $getTargetResourceParameters.Key } It 'Should return the Ensure property as Absent' { - $getTargetResourceResult.Ensure | Should Be 'Absent' + $getTargetResourceResult.Ensure | Should -Be 'Absent' } It 'Should return the ValueName property as null' { - $getTargetResourceResult.ValueName | Should Be $null + $getTargetResourceResult.ValueName | Should -Be $null } It 'Should return the ValueType property as null' { - $getTargetResourceResult.ValueType | Should Be $null + $getTargetResourceResult.ValueType | Should -Be $null } It 'Should return the ValueData property as null' { - $getTargetResourceResult.ValueData | Should Be $null + $getTargetResourceResult.ValueData | Should -Be $null } } - + Mock -CommandName 'Get-RegistryKey' -MockWith { return $script:testRegistryKey } Context 'Specified registry key exists, registry key value name specified as an empty string, and registry key value data and type not specified' { @@ -105,9 +105,9 @@ try Key = 'TestRegistryKey' ValueName = '' } - + It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -138,31 +138,31 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return 5 hashtable properties' { - $getTargetResourceResult.Keys.Count | Should Be 5 + $getTargetResourceResult.Keys.Count | Should -Be 5 } It 'Should return the Key property as the given registry key path' { - $getTargetResourceResult.Key | Should Be $getTargetResourceParameters.Key + $getTargetResourceResult.Key | Should -Be $getTargetResourceParameters.Key } It 'Should return the Ensure property as Present' { - $getTargetResourceResult.Ensure | Should Be 'Present' + $getTargetResourceResult.Ensure | Should -Be 'Present' } It 'Should return the ValueName property as null' { - $getTargetResourceResult.ValueName | Should Be $null + $getTargetResourceResult.ValueName | Should -Be $null } It 'Should return the ValueType property as null' { - $getTargetResourceResult.ValueType | Should Be $null + $getTargetResourceResult.ValueType | Should -Be $null } It 'Should return the ValueData property as null' { - $getTargetResourceResult.ValueData | Should Be $null + $getTargetResourceResult.ValueData | Should -Be $null } } @@ -171,9 +171,9 @@ try Key = 'TestRegistryKey' ValueName = 'TestValueName' } - + It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -216,31 +216,31 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return 5 hashtable properties' { - $getTargetResourceResult.Keys.Count | Should Be 5 + $getTargetResourceResult.Keys.Count | Should -Be 5 } It 'Should return the Key property as the given registry key path' { - $getTargetResourceResult.Key | Should Be $getTargetResourceParameters.Key + $getTargetResourceResult.Key | Should -Be $getTargetResourceParameters.Key } It 'Should return the Ensure property as Absent' { - $getTargetResourceResult.Ensure | Should Be 'Absent' + $getTargetResourceResult.Ensure | Should -Be 'Absent' } It 'Should return the ValueName property as the specified value name' { - $getTargetResourceResult.ValueName | Should Be $getTargetResourceParameters.ValueName + $getTargetResourceResult.ValueName | Should -Be $getTargetResourceParameters.ValueName } It 'Should return the ValueType property as null' { - $getTargetResourceResult.ValueType | Should Be $null + $getTargetResourceResult.ValueType | Should -Be $null } It 'Should return the ValueData property as null' { - $getTargetResourceResult.ValueData | Should Be $null + $getTargetResourceResult.ValueData | Should -Be $null } } @@ -254,9 +254,9 @@ try Key = 'TestRegistryKey' ValueName = 'TestValueName' } - + It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -312,31 +312,31 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return 5 hashtable properties' { - $getTargetResourceResult.Keys.Count | Should Be 5 + $getTargetResourceResult.Keys.Count | Should -Be 5 } It 'Should return the Key property as the given registry key path' { - $getTargetResourceResult.Key | Should Be $getTargetResourceParameters.Key + $getTargetResourceResult.Key | Should -Be $getTargetResourceParameters.Key } It 'Should return the Ensure property as Present' { - $getTargetResourceResult.Ensure | Should Be 'Present' + $getTargetResourceResult.Ensure | Should -Be 'Present' } It 'Should return the ValueName property as specified value display name' { - $getTargetResourceResult.ValueName | Should Be $getTargetResourceParameters.ValueName + $getTargetResourceResult.ValueName | Should -Be $getTargetResourceParameters.ValueName } It 'Should return the ValueType property as the retrieved value type' { - $getTargetResourceResult.ValueType | Should Be $testRegistryValueType + $getTargetResourceResult.ValueType | Should -Be $testRegistryValueType } It 'Should return the ValueData property as the retrieved value' { - $getTargetResourceResult.ValueData | Should Be $testRegistryKeyValue + $getTargetResourceResult.ValueData | Should -Be $testRegistryKeyValue } } @@ -347,9 +347,9 @@ try ValueType = 'String' ValueData = 'TestValueData' } - + It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -405,31 +405,31 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return 5 hashtable properties' { - $getTargetResourceResult.Keys.Count | Should Be 5 + $getTargetResourceResult.Keys.Count | Should -Be 5 } It 'Should return the Key property as the given registry key path' { - $getTargetResourceResult.Key | Should Be $getTargetResourceParameters.Key + $getTargetResourceResult.Key | Should -Be $getTargetResourceParameters.Key } It 'Should return the Ensure property as Present' { - $getTargetResourceResult.Ensure | Should Be 'Present' + $getTargetResourceResult.Ensure | Should -Be 'Present' } It 'Should return the ValueName property as specified value display name' { - $getTargetResourceResult.ValueName | Should Be $getTargetResourceParameters.ValueName + $getTargetResourceResult.ValueName | Should -Be $getTargetResourceParameters.ValueName } It 'Should return the ValueType property as the retrieved value type' { - $getTargetResourceResult.ValueType | Should Be $testRegistryValueType + $getTargetResourceResult.ValueType | Should -Be $testRegistryValueType } It 'Should return the ValueData property as the retrieved value' { - $getTargetResourceResult.ValueData | Should Be $testRegistryKeyValue + $getTargetResourceResult.ValueData | Should -Be $testRegistryKeyValue } } } @@ -451,7 +451,7 @@ try Mock -CommandName 'Remove-DefaultRegistryKeyValue' -MockWith { } Mock -CommandName 'Get-RegistryKeySubKeyCount' -MockWith { return 0 } Mock -CommandName 'Remove-Item' -MockWith { } - + Context 'Registry key does not exist and Ensure specified as Absent' { $setTargetResourceParameters = @{ @@ -461,7 +461,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -546,7 +546,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -624,7 +624,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -638,7 +638,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -724,7 +724,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -740,7 +740,7 @@ try It 'Should throw error for removal of registry key with subkeys without specifying Force as True' { $errorMessage = $script:localizedData.CannotRemoveExistingRegistryKeyWithSubKeysWithoutForce -f $setTargetResourceParameters.Key - { Set-TargetResource @setTargetResourceParameters } | Should Throw $errorMessage + { Set-TargetResource @setTargetResourceParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -753,7 +753,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -839,7 +839,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -851,7 +851,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -934,7 +934,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -946,7 +946,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -1019,10 +1019,10 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } - + Context 'Registry key exists, Ensure specified as Present, specified registry value does not exist, and registry value type and data not specified' { $setTargetResourceParameters = @{ Key = 'TestRegistryKey' @@ -1031,7 +1031,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -1067,7 +1067,7 @@ try It 'Should convert the specified registry key value to a string' { $convertToStringParameterFilter = { - $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $script:defaultValueData -DifferenceObject $RegistryKeyValue) + $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $script:defaultValueData -DifferenceObject $RegistryKeyValue) return $registryKeyValueParameterCorrect } @@ -1133,7 +1133,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -1142,12 +1142,12 @@ try Key = 'TestRegistryKey' ValueName = '' ValueType = 'Binary' - ValueData = @( [Byte]::MinValue.ToString(), [Byte]::MaxValue.ToString() ) + ValueData = @( [System.Byte]::MinValue.ToString(), [System.Byte]::MaxValue.ToString() ) Ensure = 'Present' } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -1187,7 +1187,7 @@ try It 'Should convert the specified registry key value to binary data' { $convertToBinaryParameterFilter = { - $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.ValueData -DifferenceObject $RegistryKeyValue) + $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.ValueData -DifferenceObject $RegistryKeyValue) return $registryKeyValueParameterCorrect } @@ -1249,7 +1249,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -1265,7 +1265,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -1317,7 +1317,7 @@ try It 'Should convert the specified registry key value to a multi-string' { $convertToMultiStringParameterFilter = { - $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.ValueData -DifferenceObject $RegistryKeyValue) + $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.ValueData -DifferenceObject $RegistryKeyValue) return $registryKeyValueParameterCorrect } @@ -1366,7 +1366,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -1384,7 +1384,7 @@ try It 'Should throw error for trying to overwrite existing registry key value without specifying Force as True' { $errorMessage = $script:localizedData.CannotOverwriteExistingRegistryKeyValueWithoutForce -f $setTargetResourceParameters.Key, $setTargetResourceParameters.ValueName - { Set-TargetResource @setTargetResourceParameters } | Should Throw $errorMessage + { Set-TargetResource @setTargetResourceParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -1400,7 +1400,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -1444,9 +1444,9 @@ try It 'Should convert the specified registry key value to a dword' { $convertToDwordParameterFilter = { - $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.ValueData -DifferenceObject $RegistryKeyValue) + $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.ValueData -DifferenceObject $RegistryKeyValue) $hexParameterCorrect = $Hex -eq $setTargetResourceParameters.Hex - + return $registryKeyValueParameterCorrect -and $hexParameterCorrect } @@ -1512,7 +1512,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -1528,7 +1528,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -1576,9 +1576,9 @@ try It 'Should convert the specified registry key value to a qword' { $convertToQwordParameterFilter = { - $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.ValueData -DifferenceObject $RegistryKeyValue) + $registryKeyValueParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.ValueData -DifferenceObject $RegistryKeyValue) $hexParameterCorrect = $Hex -eq $setTargetResourceParameters.Hex - + return $registryKeyValueParameterCorrect -and $hexParameterCorrect } @@ -1640,7 +1640,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -1655,7 +1655,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -1746,7 +1746,7 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } @@ -1761,7 +1761,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key' { @@ -1849,11 +1849,11 @@ try } It 'Should not return' { - Set-TargetResource @setTargetResourceParameters | Should Be $null + Set-TargetResource @setTargetResourceParameters | Should -Be $null } } } - + Describe 'Registry\Test-TargetResource' { Mock -CommandName 'Get-RegistryKeyValueDisplayName' -MockWith { return $RegistryKeyValueName } Mock -CommandName 'Test-RegistryKeyValuesMatch' -MockWith { return $true } @@ -1877,7 +1877,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -1902,11 +1902,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return True' { - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } } @@ -1918,7 +1918,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -1943,16 +1943,16 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return False' { - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } Mock -CommandName 'Get-TargetResource' -MockWith { - if ([String]::IsNullOrEmpty($ValueName)) + if ([System.String]::IsNullOrEmpty($ValueName)) { return @{ Ensure = 'Present' @@ -1974,7 +1974,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry key value display name' { @@ -2004,11 +2004,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return True' { - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } } @@ -2020,7 +2020,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -2050,11 +2050,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return False' { - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } @@ -2072,7 +2072,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -2097,11 +2097,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return False' { - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } @@ -2113,7 +2113,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -2138,11 +2138,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return True' { - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } } @@ -2154,7 +2154,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -2184,11 +2184,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return False' { - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } @@ -2201,7 +2201,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -2231,11 +2231,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return False' { - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } @@ -2248,7 +2248,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -2278,11 +2278,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return False' { - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } @@ -2294,7 +2294,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key and value name' { @@ -2324,11 +2324,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return True' { - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } } @@ -2348,7 +2348,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key, value name, and value type' { @@ -2379,11 +2379,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return True' { - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } } @@ -2404,7 +2404,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key, value name, and value data' { @@ -2443,11 +2443,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return True' { - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } } @@ -2467,7 +2467,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key, value name, and value type' { @@ -2498,11 +2498,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return False' { - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } @@ -2527,7 +2527,7 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve the registry resource with the specified reigstry key, value name, and value data' { @@ -2566,11 +2566,11 @@ try $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters It 'Should return a boolean' { - $testTargetResourceResult -is [Boolean] | Should Be $true + $testTargetResourceResult -is [System.Boolean] | Should -BeTrue } It 'Should return False' { - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } } @@ -2582,13 +2582,13 @@ try } It 'Should not throw' { - { $null = Get-PathRoot @getPathRootParameters } | Should Not Throw + { $null = Get-PathRoot @getPathRootParameters } | Should -Not -Throw } $getPathRootResult = Get-PathRoot @getPathRootParameters It 'Should return the given path' { - $getPathRootResult | Should Be $getPathRootParameters.Path + $getPathRootResult | Should -Be $getPathRootParameters.Path } } @@ -2600,13 +2600,13 @@ try } It 'Should not throw' { - { $null = Get-PathRoot @getPathRootParameters } | Should Not Throw + { $null = Get-PathRoot @getPathRootParameters } | Should -Not -Throw } $getPathRootResult = Get-PathRoot @getPathRootParameters It 'Should return the root of the given path' { - $getPathRootResult | Should Be $pathRoot + $getPathRootResult | Should -Be $pathRoot } } @@ -2620,13 +2620,13 @@ try } It 'Should not throw' { - { $null = Get-PathRoot @getPathRootParameters } | Should Not Throw + { $null = Get-PathRoot @getPathRootParameters } | Should -Not -Throw } $getPathRootResult = Get-PathRoot @getPathRootParameters It 'Should return the root of the given path' { - $getPathRootResult | Should Be $pathRoot + $getPathRootResult | Should -Be $pathRoot } } } @@ -2640,7 +2640,7 @@ try } It 'Should not throw' { - { $null = ConvertTo-RegistryDriveName @convertToRegistryDriveNameParameters } | Should Not Throw + { $null = ConvertTo-RegistryDriveName @convertToRegistryDriveNameParameters } | Should -Not -Throw } $expcetedRegistryDriveName = switch ($validRegistryDriveRoot) @@ -2655,7 +2655,7 @@ try $convertToRegistryDriveNameResult = ConvertTo-RegistryDriveName @convertToRegistryDriveNameParameters It "Should return correct registry drive name $expcetedRegistryDriveName" { - $convertToRegistryDriveNameResult | Should Be $expcetedRegistryDriveName + $convertToRegistryDriveNameResult | Should -Be $expcetedRegistryDriveName } } } @@ -2666,13 +2666,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-RegistryDriveName @convertToRegistryDriveNameParameters } | Should Not Throw + { $null = ConvertTo-RegistryDriveName @convertToRegistryDriveNameParameters } | Should -Not -Throw } $convertToRegistryDriveNameResult = ConvertTo-RegistryDriveName @convertToRegistryDriveNameParameters It 'Should return null' { - $convertToRegistryDriveNameResult | Should Be $null + $convertToRegistryDriveNameResult | Should -Be $null } } } @@ -2691,7 +2691,7 @@ try It 'Should throw an error for invalid registry drive' { $errorMessage = $script:localizedData.InvalidRegistryDrive -f $invalidRegistryDriveRoot - { $null = Get-RegistryDriveName @getRegistryDriveNameParameters } | Should Throw $errorMessage + { $null = Get-RegistryDriveName @getRegistryDriveNameParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2705,7 +2705,7 @@ try } It 'Should not throw' { - { $null = Get-RegistryDriveName @getRegistryDriveNameParameters } | Should Not Throw + { $null = Get-RegistryDriveName @getRegistryDriveNameParameters } | Should -Not -Throw } It 'Should retrieve the path root' { @@ -2729,7 +2729,7 @@ try $getDriveNameResult = Get-RegistryDriveName @getRegistryDriveNameParameters It 'Should return the retrieved registry drive name' { - $getDriveNameResult | Should Be $script:validRegistryDriveNames[0] + $getDriveNameResult | Should -Be $script:validRegistryDriveNames[0] } } @@ -2744,7 +2744,7 @@ try It 'Should throw an error for invalid registry drive' { $errorMessage = $script:localizedData.InvalidRegistryDrive -f $invalidRegistryDriveName - { $null = Get-RegistryDriveName @getRegistryDriveNameParameters } | Should Throw $errorMessage + { $null = Get-RegistryDriveName @getRegistryDriveNameParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2757,7 +2757,7 @@ try } It 'Should not throw' { - { $null = Get-RegistryDriveName @getRegistryDriveNameParameters } | Should Not Throw + { $null = Get-RegistryDriveName @getRegistryDriveNameParameters } | Should -Not -Throw } It 'Should retrieve the path root' { @@ -2776,7 +2776,7 @@ try $getDriveNameResult = Get-RegistryDriveName @getRegistryDriveNameParameters It 'Should return the retrieved registry drive name' { - $getDriveNameResult | Should Be $validRegistryDriveName + $getDriveNameResult | Should -Be $validRegistryDriveName } } } @@ -2790,11 +2790,11 @@ try $mountRegistryDriveParameters = @{ RegistryDriveName = 'TestRegistryDriveName' } - + It 'Should throw error for unmountable registry drive' { $errorMessage = $script:localizedData.RegistryDriveCouldNotBeMounted -f $mountRegistryDriveParameters.RegistryDriveName - { Mount-RegistryDrive @mountRegistryDriveParameters } | Should Throw $errorMessage + { Mount-RegistryDrive @mountRegistryDriveParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2804,11 +2804,11 @@ try $mountRegistryDriveParameters = @{ RegistryDriveName = 'TestRegistryDriveName' } - + It 'Should throw error for unmountable registry drive' { $errorMessage = $script:localizedData.RegistryDriveCouldNotBeMounted -f $mountRegistryDriveParameters.RegistryDriveName - { Mount-RegistryDrive @mountRegistryDriveParameters } | Should Throw $errorMessage + { Mount-RegistryDrive @mountRegistryDriveParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2818,11 +2818,11 @@ try $mountRegistryDriveParameters = @{ RegistryDriveName = 'TestRegistryDriveName' } - + It 'Should throw error for unmountable registry drive' { $errorMessage = $script:localizedData.RegistryDriveCouldNotBeMounted -f $mountRegistryDriveParameters.RegistryDriveName - { Mount-RegistryDrive @mountRegistryDriveParameters } | Should Throw $errorMessage + { Mount-RegistryDrive @mountRegistryDriveParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2832,11 +2832,11 @@ try $mountRegistryDriveParameters = @{ RegistryDriveName = 'HKCR' } - + $expectedRegistryDriveRoot = 'HKEY_CLASSES_ROOT' It 'Should not throw' { - { Mount-RegistryDrive @mountRegistryDriveParameters } | Should Not Throw + { Mount-RegistryDrive @mountRegistryDriveParameters } | Should -Not -Throw } It 'Should retrieve the registry drive with specified name' { @@ -2854,7 +2854,7 @@ try $rootParameterCorrect = $Root -eq $expectedRegistryDriveRoot $psProviderParameterCorrect = $PSProvider -eq 'Registry' $scopeParameterCorrect = $Scope -eq 'Script' - + return $nameParameterCorrect -and $rootParameterCorrect -and $psProviderParameterCorrect -and $scopeParameterCorrect } @@ -2862,7 +2862,7 @@ try } It 'Should not return anything' { - Mount-RegistryDrive @mountRegistryDriveParameters | Should Be $null + Mount-RegistryDrive @mountRegistryDriveParameters | Should -Be $null } } @@ -2872,11 +2872,11 @@ try $mountRegistryDriveParameters = @{ RegistryDriveName = 'TestRegistryDriveName' } - + It 'Should throw error for unmountable registry drive' { $errorMessage = $script:localizedData.RegistryDriveCouldNotBeMounted -f $mountRegistryDriveParameters.RegistryDriveName - { Mount-RegistryDrive @mountRegistryDriveParameters } | Should Throw $errorMessage + { Mount-RegistryDrive @mountRegistryDriveParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2886,11 +2886,11 @@ try $mountRegistryDriveParameters = @{ RegistryDriveName = 'TestRegistryDriveName' } - + It 'Should throw error for unmountable registry drive' { $errorMessage = $script:localizedData.RegistryDriveCouldNotBeMounted -f $mountRegistryDriveParameters.RegistryDriveName - { Mount-RegistryDrive @mountRegistryDriveParameters } | Should Throw $errorMessage + { Mount-RegistryDrive @mountRegistryDriveParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2900,11 +2900,9 @@ try $mountRegistryDriveParameters = @{ RegistryDriveName = 'HKCR' } - - $expectedRegistryDriveRoot = 'HKEY_CLASSES_ROOT' It 'Should not throw' { - { Mount-RegistryDrive @mountRegistryDriveParameters } | Should Not Throw + { Mount-RegistryDrive @mountRegistryDriveParameters } | Should -Not -Throw } It 'Should retrieve the registry drive with specified name' { @@ -2921,7 +2919,7 @@ try } It 'Should not return anything' { - Mount-RegistryDrive @mountRegistryDriveParameters | Should Be $null + Mount-RegistryDrive @mountRegistryDriveParameters | Should -Be $null } } } @@ -2942,7 +2940,7 @@ try } It 'Should not throw' { - { $null = Get-RegistryKey @getRegistryKeyParameters } | Should Not Throw + { $null = Get-RegistryKey @getRegistryKeyParameters } | Should -Not -Throw } It 'Should retrieve the registry drive name of the specified registry key path' { @@ -2987,7 +2985,7 @@ try $getRegistryKeyResult = Get-RegistryKey @getRegistryKeyParameters It 'Should return the retrieved registry key' { - $getRegistryKeyResult | Should Be $expectedGetRegistryKeyResult + $getRegistryKeyResult | Should -Be $expectedGetRegistryKeyResult } } @@ -2999,7 +2997,7 @@ try } It 'Should not throw' { - { $null = Get-RegistryKey @getRegistryKeyParameters } | Should Not Throw + { $null = Get-RegistryKey @getRegistryKeyParameters } | Should -Not -Throw } It 'Should retrieve the registry drive name of the specified registry key path' { @@ -3044,7 +3042,7 @@ try $getRegistryKeyResult = Get-RegistryKey @getRegistryKeyParameters It 'Should return the retrieved registry key' { - $getRegistryKeyResult | Should Be $expectedGetRegistryKeyResult + $getRegistryKeyResult | Should -Be $expectedGetRegistryKeyResult } } @@ -3055,7 +3053,7 @@ try } It 'Should not throw' { - { $null = Get-RegistryKey @getRegistryKeyParameters } | Should Not Throw + { $null = Get-RegistryKey @getRegistryKeyParameters } | Should -Not -Throw } It 'Should retrieve the registry drive name of the specified registry key path' { @@ -3100,7 +3098,7 @@ try $getRegistryKeyResult = Get-RegistryKey @getRegistryKeyParameters It 'Should return the retrieved registry key' { - $getRegistryKeyResult | Should Be $expectedGetRegistryKeyResult + $getRegistryKeyResult | Should -Be $expectedGetRegistryKeyResult } } } @@ -3112,29 +3110,29 @@ try } It 'Should not throw' { - { $null = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters } | Should Not Throw + { $null = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters } | Should -Not -Throw } $getRegistryKeyValueDisplayNameResult = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters It 'Should return default registry key value name' { - $getRegistryKeyValueDisplayNameResult | Should Be $localizedData.DefaultValueDisplayName + $getRegistryKeyValueDisplayNameResult | Should -Be $localizedData.DefaultValueDisplayName } } Context 'Specified registry key value name is an empty string' { $getRegistryKeyValueDisplayNameParameters = @{ - RegistryKeyValue = [String]::Empty + RegistryKeyValue = [System.String]::Empty } It 'Should not throw' { - { $null = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters } | Should Not Throw + { $null = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters } | Should -Not -Throw } $getRegistryKeyValueDisplayNameResult = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters It 'Should return default registry key value name' { - $getRegistryKeyValueDisplayNameResult | Should Be $localizedData.DefaultValueDisplayName + $getRegistryKeyValueDisplayNameResult | Should -Be $localizedData.DefaultValueDisplayName } } @@ -3144,13 +3142,13 @@ try } It 'Should not throw' { - { $null = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters } | Should Not Throw + { $null = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters } | Should -Not -Throw } $getRegistryKeyValueDisplayNameResult = Get-RegistryKeyValueDisplayName @getRegistryKeyValueDisplayNameParameters It 'Should return given registry key value name' { - $getRegistryKeyValueDisplayNameResult | Should Be $getRegistryKeyValueDisplayNameParameters.RegistryKeyValue + $getRegistryKeyValueDisplayNameResult | Should -Be $getRegistryKeyValueDisplayNameParameters.RegistryKeyValue } } } @@ -3162,19 +3160,19 @@ try } It 'Should not throw' { - { $null = Convert-ByteArrayToHexString @convertByteArrayToHexStringParameters } | Should Not Throw + { $null = Convert-ByteArrayToHexString @convertByteArrayToHexStringParameters } | Should -Not -Throw } $convertByteArrayToHexStringResult = Convert-ByteArrayToHexString @convertByteArrayToHexStringParameters It 'Should return an empty string' { - $convertByteArrayToHexStringResult | Should Be ([String]::Empty) + $convertByteArrayToHexStringResult | Should -Be ([System.String]::Empty) } } Context 'Specified byte array has one element' { $convertByteArrayToHexStringParameters = @{ - ByteArray = @( [Byte]'1' ) + ByteArray = @( [System.Byte] '1' ) } It 'Should not throw' { @@ -3184,23 +3182,23 @@ try $convertByteArrayToHexStringResult = Convert-ByteArrayToHexString @convertByteArrayToHexStringParameters It 'Should return the byte array as a single hex string' { - $convertByteArrayToHexStringResult | Should Be '01' + $convertByteArrayToHexStringResult | Should -Be '01' } } Context 'Specified byte array has multiple elements' { $convertByteArrayToHexStringParameters = @{ - ByteArray = @( 0, [Byte]::MaxValue ) + ByteArray = @( 0, [System.Byte]::MaxValue ) } It 'Should not throw' { - { $null = Convert-ByteArrayToHexString @convertByteArrayToHexStringParameters } | Should Not Throw + { $null = Convert-ByteArrayToHexString @convertByteArrayToHexStringParameters } | Should -Not -Throw } $convertByteArrayToHexStringResult = Convert-ByteArrayToHexString @convertByteArrayToHexStringParameters It 'Should return the byte array as a single hex string' { - $convertByteArrayToHexStringResult | Should Be '00ff' + $convertByteArrayToHexStringResult | Should -Be '00ff' } } } @@ -3217,7 +3215,7 @@ try } It 'Should not throw' { - { $null = ConvertTo-ReadableString @convertToReadableStringParameters } | Should Not Throw + { $null = ConvertTo-ReadableString @convertToReadableStringParameters } | Should -Not -Throw } It 'Should not attempt to convert registry key value to a hex string' { @@ -3227,10 +3225,10 @@ try $convertToReadableStringResult = ConvertTo-ReadableString @convertToReadableStringParameters It 'Should return an empty string' { - $convertToReadableStringResult | Should Be ([String]::Empty) + $convertToReadableStringResult | Should -Be ([System.String]::Empty) } } - + Context "Registry key value specified as an empty array and registry key type specified as $registryKeyValueType" { $convertToReadableStringParameters = @{ RegistryKeyValue = @() @@ -3238,7 +3236,7 @@ try } It 'Should not throw' { - { $null = ConvertTo-ReadableString @convertToReadableStringParameters } | Should Not Throw + { $null = ConvertTo-ReadableString @convertToReadableStringParameters } | Should -Not -Throw } if ($registryKeyValueType -eq 'Binary') @@ -3262,7 +3260,7 @@ try $convertToReadableStringResult = ConvertTo-ReadableString @convertToReadableStringParameters It 'Should return an empty string' { - $convertToReadableStringResult | Should Be ([String]::Empty) + $convertToReadableStringResult | Should -Be ([System.String]::Empty) } } @@ -3273,7 +3271,7 @@ try } It 'Should not throw' { - { $null = ConvertTo-ReadableString @convertToReadableStringParameters } | Should Not Throw + { $null = ConvertTo-ReadableString @convertToReadableStringParameters } | Should -Not -Throw } if ($registryKeyValueType -eq 'Binary') @@ -3297,7 +3295,7 @@ try $convertToReadableStringResult = ConvertTo-ReadableString @convertToReadableStringParameters It 'Should return the specified string' { - $convertToReadableStringResult | Should Be $convertToReadableStringParameters.RegistryKeyValue[0] + $convertToReadableStringResult | Should -Be $convertToReadableStringParameters.RegistryKeyValue[0] } } @@ -3308,7 +3306,7 @@ try } It 'Should not throw' { - { $null = ConvertTo-ReadableString @convertToReadableStringParameters } | Should Not Throw + { $null = ConvertTo-ReadableString @convertToReadableStringParameters } | Should -Not -Throw } if ($registryKeyValueType -eq 'Binary') @@ -3333,7 +3331,7 @@ try $convertToReadableStringResult = ConvertTo-ReadableString @convertToReadableStringParameters It 'Should return the specified strings inside one string' { - $convertToReadableStringResult | Should Be $expectedReadProperty + $convertToReadableStringResult | Should -Be $expectedReadProperty } } } @@ -3352,7 +3350,7 @@ try } It 'Should not throw' { - { $null = New-RegistryKey @newRegistryKeyParameters } | Should Not Throw + { $null = New-RegistryKey @newRegistryKeyParameters } | Should -Not -Throw } It 'Should retrieve the parent registry key' { @@ -3382,7 +3380,7 @@ try $newRegistryKeyResult = New-RegistryKey @newRegistryKeyParameters It 'Should return the created subkey' { - $newRegistryKeyResult | Should Be $script:testRegistryKey + $newRegistryKeyResult | Should -Be $script:testRegistryKey } } @@ -3406,7 +3404,7 @@ try } It 'Should not throw' { - { $null = New-RegistryKey @newRegistryKeyParameters } | Should Not Throw + { $null = New-RegistryKey @newRegistryKeyParameters } | Should -Not -Throw } It 'Should retrieve the parent registry key' { @@ -3451,7 +3449,7 @@ try $newRegistryKeyResult = New-RegistryKey @newRegistryKeyParameters It 'Should return the created subkey' { - $newRegistryKeyResult | Should Be $script:testRegistryKey + $newRegistryKeyResult | Should -Be $script:testRegistryKey } } } @@ -3462,7 +3460,7 @@ try $expectedRegistryKeyValue = switch ($registryKeyValueType) { 'String' { 'String1' } - 'Binary' { [Byte[]]@( 12, 172, 17, 17 ) } + 'Binary' { [System.Byte[]] @( 12, 172, 17, 17 ) } 'DWord' { 169 } 'QWord' { 92 } 'MultiString' { @( 'String1', 'String2' ) } @@ -3472,7 +3470,7 @@ try $mismatchingActualRegistryKeyValue = switch ($registryKeyValueType) { 'String' { 'String2' } - 'Binary' { [Byte[]]@( 11, 172, 17, 1 ) } + 'Binary' { [System.Byte[]] @( 11, 172, 17, 1 ) } 'DWord' { 12 } 'QWord' { 64 } 'MultiString' { @( 'String3', 'String2' ) } @@ -3487,13 +3485,13 @@ try } It 'Should not throw' { - { $null = Test-RegistryKeyValuesMatch @testRegistryKeyValuesMatchParameters } | Should Not Throw + { $null = Test-RegistryKeyValuesMatch @testRegistryKeyValuesMatchParameters } | Should -Not -Throw } $testRegistryKeyValuesMatchResult = Test-RegistryKeyValuesMatch @testRegistryKeyValuesMatchParameters It 'Should return true' { - $testRegistryKeyValuesMatchResult | Should Be $true + $testRegistryKeyValuesMatchResult | Should -BeTrue } } @@ -3505,13 +3503,13 @@ try } It 'Should not throw' { - { $null = Test-RegistryKeyValuesMatch @testRegistryKeyValuesMatchParameters } | Should Not Throw + { $null = Test-RegistryKeyValuesMatch @testRegistryKeyValuesMatchParameters } | Should -Not -Throw } $testRegistryKeyValuesMatchResult = Test-RegistryKeyValuesMatch @testRegistryKeyValuesMatchParameters It 'Should return false' { - $testRegistryKeyValuesMatchResult | Should Be $false + $testRegistryKeyValuesMatchResult | Should -BeFalse } } } @@ -3524,13 +3522,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Not Throw + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Not -Throw } $convertToBinaryResult = ConvertTo-Binary @convertToBinaryParameters It 'Should return null' { - $convertToBinaryResult | Should Be $null + $convertToBinaryResult | Should -Be $null } } @@ -3540,13 +3538,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Not Throw + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Not -Throw } $convertToBinaryResult = ConvertTo-Binary @convertToBinaryParameters It 'Should return null' { - $convertToBinaryResult | Should Be $null + $convertToBinaryResult | Should -Be $null } } @@ -3556,89 +3554,89 @@ try } It 'Should not throw' { - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Not Throw + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Not -Throw } $convertToBinaryResult = ConvertTo-Binary @convertToBinaryParameters It 'Should return null' { - $convertToBinaryResult | Should Be $null + $convertToBinaryResult | Should -Be $null } } Context 'Specified registry key value is an array containing a valid single string of an odd length' { $validBinaryString = '0xCAC1111' - $expectedByteArray = [Byte[]]@( 12, 172, 17, 17 ) + $expectedByteArray = [System.Byte[]] @( 12, 172, 17, 17 ) $convertToBinaryParameters = @{ RegistryKeyValue = @( $validBinaryString ) } It 'Should not throw' { - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Not Throw + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Not -Throw } $convertToBinaryResult = ConvertTo-Binary @convertToBinaryParameters It 'Should return the specified single string' { - Compare-Object -ReferenceObject $expectedByteArray -DifferenceObject $convertToBinaryResult | Should Be $null + Compare-Object -ReferenceObject $expectedByteArray -DifferenceObject $convertToBinaryResult | Should -Be $null } } Context 'Specified registry key value is an array containing a valid single string of an even length' { $validBinaryString = '0x0CAC1111' - $expectedByteArray = [Byte[]]@( 12, 172, 17, 17 ) + $expectedByteArray = [System.Byte[]] @( 12, 172, 17, 17 ) $convertToBinaryParameters = @{ RegistryKeyValue = @( $validBinaryString ) } It 'Should not throw' { - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Not Throw + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Not -Throw } $convertToBinaryResult = ConvertTo-Binary @convertToBinaryParameters It 'Should return the specified single string' { - Compare-Object -ReferenceObject $expectedByteArray -DifferenceObject $convertToBinaryResult | Should Be $null + Compare-Object -ReferenceObject $expectedByteArray -DifferenceObject $convertToBinaryResult | Should -Be $null } } Context 'Specified registry key value is an array containing a valid single string of an even length not starting with 0x' { $validBinaryString = '0CAC1111' - $expectedByteArray = [Byte[]]@( 12, 172, 17, 17 ) + $expectedByteArray = [System.Byte[]] @( 12, 172, 17, 17 ) $convertToBinaryParameters = @{ RegistryKeyValue = @( $validBinaryString ) } It 'Should not throw' { - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Not Throw + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Not -Throw } $convertToBinaryResult = ConvertTo-Binary @convertToBinaryParameters It 'Should return the specified single string' { - Compare-Object -ReferenceObject $expectedByteArray -DifferenceObject $convertToBinaryResult | Should Be $null + Compare-Object -ReferenceObject $expectedByteArray -DifferenceObject $convertToBinaryResult | Should -Be $null } } Context 'Specified registry key value is an array containing a valid single string of 0x00' { $validBinaryString = '0x00' - $expectedByteArray = [Byte[]]@( 0 ) + $expectedByteArray = [System.Byte[]] @( 0 ) $convertToBinaryParameters = @{ RegistryKeyValue = @( $validBinaryString ) } It 'Should not throw' { - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Not Throw + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Not -Throw } $convertToBinaryResult = ConvertTo-Binary @convertToBinaryParameters It 'Should return the specified single string' { - Compare-Object -ReferenceObject $expectedByteArray -DifferenceObject $convertToBinaryResult | Should Be $null + Compare-Object -ReferenceObject $expectedByteArray -DifferenceObject $convertToBinaryResult | Should -Be $null } } @@ -3652,7 +3650,7 @@ try It 'Should not throw' { $errorMessage = $script:localizedData.BinaryDataNotInHexFormat -f $invalidBinaryString - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Throw $errorMessage + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -3664,7 +3662,7 @@ try It 'Should throw an error for unexpected array' { $errorMessage = $script:localizedData.ArrayNotAllowedForExpectedType -f 'Binary' - { $null = ConvertTo-Binary @convertToBinaryParameters } | Should Throw $errorMessage + { $null = ConvertTo-Binary @convertToBinaryParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -3676,13 +3674,14 @@ try } It 'Should not throw' { - { $null = ConvertTo-DWord @convertToDWordParameters } | Should Not Throw + { $null = ConvertTo-DWord @convertToDWordParameters } | Should -Not -Throw } $convertToDWordResult = ConvertTo-DWord @convertToDWordParameters It 'Should return 0 as an Int32' { - $convertToDWordResult | Should Be ([System.Int32] 0) + $convertToDWordResult | Should -BeOfType Int32 + $convertToDWordResult | Should -BeExactly 0 } } @@ -3692,13 +3691,14 @@ try } It 'Should not throw' { - { $null = ConvertTo-DWord @convertToDWordParameters } | Should Not Throw + { $null = ConvertTo-DWord @convertToDWordParameters } | Should -Not -Throw } $convertToDWordResult = ConvertTo-DWord @convertToDWordParameters It 'Should return 0 as an Int32' { - $convertToDWordResult | Should Be ([System.Int32] 0) + $convertToDWordResult | Should -BeOfType Int32 + $convertToDWordResult | Should -BeExactly 0 } } @@ -3708,13 +3708,14 @@ try } It 'Should not throw' { - { $null = ConvertTo-DWord @convertToDWordParameters } | Should Not Throw + { $null = ConvertTo-DWord @convertToDWordParameters } | Should -Not -Throw } $convertToDWordResult = ConvertTo-DWord @convertToDWordParameters It 'Should return 0 as an Int32' { - $convertToDWordResult | Should Be ([System.Int32] 0) + $convertToDWordResult | Should -BeOfType Int32 + $convertToDWordResult | Should -BeExactly 0 } } @@ -3726,13 +3727,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-DWord @convertToDWordParameters } | Should Not Throw + { $null = ConvertTo-DWord @convertToDWordParameters } | Should -Not -Throw } $convertToDWordResult = ConvertTo-DWord @convertToDWordParameters It 'Should return the specified double word' { - $convertToDWordResult | Should Be $testDWord1 + $convertToDWordResult | Should -Be $testDWord1 } } @@ -3746,7 +3747,7 @@ try It 'Should throw an error for the invalid dword string' { $errorMessage = $script:localizedData.DWordDataNotInHexFormat -f $invalidHexDWord - { $null = ConvertTo-DWord @convertToDWordParameters } | Should Throw $errorMessage + { $null = ConvertTo-DWord @convertToDWordParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -3760,13 +3761,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-DWord @convertToDWordParameters } | Should Not Throw + { $null = ConvertTo-DWord @convertToDWordParameters } | Should -Not -Throw } $convertToDWordResult = ConvertTo-DWord @convertToDWordParameters It 'Should return the specified double word converted from a Hex value' { - $convertToDWordResult | Should Be $expectedInt32Value + $convertToDWordResult | Should -Be $expectedInt32Value } } @@ -3780,13 +3781,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-DWord @convertToDWordParameters } | Should Not Throw + { $null = ConvertTo-DWord @convertToDWordParameters } | Should -Not -Throw } $convertToDWordResult = ConvertTo-DWord @convertToDWordParameters It 'Should return the specified double word converted from a Hex value' { - $convertToDWordResult | Should Be $expectedInt32Value + $convertToDWordResult | Should -Be $expectedInt32Value } } @@ -3800,7 +3801,7 @@ try It 'Should throw an error for unexpected array' { $errorMessage = $script:localizedData.ArrayNotAllowedForExpectedType -f 'Dword' - { $null = ConvertTo-DWord @convertToDWordParameters } | Should Throw $errorMessage + { $null = ConvertTo-DWord @convertToDWordParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -3812,13 +3813,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should Not Throw + { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should -Not -Throw } $convertToMultiStringResult = ConvertTo-MultiString @convertToMultiStringParameters It 'Should return null' { - $convertToMultiStringResult | Should Be $null + $convertToMultiStringResult | Should -Be $null } } @@ -3828,13 +3829,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should Not Throw + { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should -Not -Throw } $convertToMultiStringResult = ConvertTo-MultiString @convertToMultiStringParameters It 'Should return null' { - $convertToMultiStringResult | Should Be $null + $convertToMultiStringResult | Should -Be $null } } @@ -3844,13 +3845,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should Not Throw + { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should -Not -Throw } $convertToMultiStringResult = ConvertTo-MultiString @convertToMultiStringParameters It 'Should return an array containing null' { - Compare-Object -ReferenceObject ([String[]]@($null)) -DifferenceObject $convertToMultiStringResult | Should Be $null + Compare-Object -ReferenceObject ([System.String[]] @($null)) -DifferenceObject $convertToMultiStringResult | Should -Be $null } } @@ -3860,13 +3861,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should Not Throw + { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should -Not -Throw } $convertToMultiStringResult = ConvertTo-MultiString @convertToMultiStringParameters It 'Should return an array containing the specified single string' { - Compare-Object -ReferenceObject $convertToMultiStringParameters.RegistryKeyValue -DifferenceObject $convertToMultiStringResult | Should Be $null + Compare-Object -ReferenceObject $convertToMultiStringParameters.RegistryKeyValue -DifferenceObject $convertToMultiStringResult | Should -Be $null } } @@ -3876,13 +3877,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should Not Throw + { $null = ConvertTo-MultiString @convertToMultiStringParameters } | Should -Not -Throw } $convertToMultiStringResult = ConvertTo-MultiString @convertToMultiStringParameters It 'Should return an array containing the specified single string' { - Compare-Object -ReferenceObject $convertToMultiStringParameters.RegistryKeyValue -DifferenceObject $convertToMultiStringResult | Should Be $null + Compare-Object -ReferenceObject $convertToMultiStringParameters.RegistryKeyValue -DifferenceObject $convertToMultiStringResult | Should -Be $null } } } @@ -3894,13 +3895,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-QWord @convertToQWordParameters } | Should Not Throw + { $null = ConvertTo-QWord @convertToQWordParameters } | Should -Not -Throw } $convertToQWordResult = ConvertTo-QWord @convertToQWordParameters It 'Should return 0 as an Int64' { - $convertToQWordResult | Should Be ([System.Int64] 0) + $convertToQWordResult | Should -Be ([System.Int64] 0) } } @@ -3910,13 +3911,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-QWord @convertToQWordParameters } | Should Not Throw + { $null = ConvertTo-QWord @convertToQWordParameters } | Should -Not -Throw } $convertToQWordResult = ConvertTo-QWord @convertToQWordParameters It 'Should return 0 as an Int64' { - $convertToQWordResult | Should Be ([System.Int64] 0) + $convertToQWordResult | Should -Be ([System.Int64] 0) } } @@ -3926,13 +3927,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-QWord @convertToQWordParameters } | Should Not Throw + { $null = ConvertTo-QWord @convertToQWordParameters } | Should -Not -Throw } $convertToQWordResult = ConvertTo-QWord @convertToQWordParameters It 'Should return 0 as an Int64' { - $convertToQWordResult | Should Be ([System.Int64] 0) + $convertToQWordResult | Should -Be ([System.Int64] 0) } } @@ -3944,13 +3945,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-QWord @convertToQWordParameters } | Should Not Throw + { $null = ConvertTo-QWord @convertToQWordParameters } | Should -Not -Throw } $convertToQWordResult = ConvertTo-QWord @convertToQWordParameters It 'Should return the specified quad word' { - $convertToQWordResult | Should Be $testDWord1 + $convertToQWordResult | Should -Be $testDWord1 } } @@ -3964,7 +3965,7 @@ try It 'Should throw an error for the invalid qword string' { $errorMessage = $script:localizedData.QWordDataNotInHexFormat -f $invalidHexDWord - { $null = ConvertTo-QWord @convertToQWordParameters } | Should Throw $errorMessage + { $null = ConvertTo-QWord @convertToQWordParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -3978,13 +3979,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-QWord @convertToQWordParameters } | Should Not Throw + { $null = ConvertTo-QWord @convertToQWordParameters } | Should -Not -Throw } $convertToQWordResult = ConvertTo-QWord @convertToQWordParameters It 'Should return the specified quad word converted from a Hex value' { - $convertToQWordResult | Should Be $expectedInt64Value + $convertToQWordResult | Should -Be $expectedInt64Value } } @@ -3998,13 +3999,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-QWord @convertToQWordParameters } | Should Not Throw + { $null = ConvertTo-QWord @convertToQWordParameters } | Should -Not -Throw } $convertToQWordResult = ConvertTo-QWord @convertToQWordParameters It 'Should return the specified quad word converted from a Hex value' { - $convertToQWordResult | Should Be $expectedInt64Value + $convertToQWordResult | Should -Be $expectedInt64Value } } @@ -4018,7 +4019,7 @@ try It 'Should throw an error for unexpected array' { $errorMessage = $script:localizedData.ArrayNotAllowedForExpectedType -f 'Qword' - { $null = ConvertTo-QWord @convertToQWordParameters } | Should Throw $errorMessage + { $null = ConvertTo-QWord @convertToQWordParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -4030,13 +4031,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-String @convertToStringParameters } | Should Not Throw + { $null = ConvertTo-String @convertToStringParameters } | Should -Not -Throw } $convertToStringResult = ConvertTo-String @convertToStringParameters It 'Should return an empty string' { - $convertToStringResult | Should Be ([String]::Empty) + $convertToStringResult | Should -Be ([System.String]::Empty) } } @@ -4046,13 +4047,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-String @convertToStringParameters } | Should Not Throw + { $null = ConvertTo-String @convertToStringParameters } | Should -Not -Throw } $convertToStringResult = ConvertTo-String @convertToStringParameters It 'Should return an empty string' { - $convertToStringResult | Should Be ([String]::Empty) + $convertToStringResult | Should -Be ([System.String]::Empty) } } @@ -4062,13 +4063,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-String @convertToStringParameters } | Should Not Throw + { $null = ConvertTo-String @convertToStringParameters } | Should -Not -Throw } $convertToStringResult = ConvertTo-String @convertToStringParameters It 'Should return an empty string' { - $convertToStringResult | Should Be ([String]::Empty) + $convertToStringResult | Should -Be ([System.String]::Empty) } } @@ -4078,13 +4079,13 @@ try } It 'Should not throw' { - { $null = ConvertTo-String @convertToStringParameters } | Should Not Throw + { $null = ConvertTo-String @convertToStringParameters } | Should -Not -Throw } $convertToStringResult = ConvertTo-String @convertToStringParameters It 'Should return the specified single string' { - $convertToStringResult | Should Be $convertToStringParameters.RegistryKeyValue[0] + $convertToStringResult | Should -Be $convertToStringParameters.RegistryKeyValue[0] } } @@ -4096,7 +4097,7 @@ try It 'Should throw an error for unexpected array' { $errorMessage = $script:localizedData.ArrayNotAllowedForExpectedType -f 'String or ExpandString' - { $null = ConvertTo-String @convertToStringParameters } | Should Throw $errorMessage + { $null = ConvertTo-String @convertToStringParameters } | Should -Throw -ExpectedMessage $errorMessage } } } diff --git a/Tests/Unit/MSFT_ScriptResource.Tests.ps1 b/Tests/Unit/MSFT_ScriptResource.Tests.ps1 index 741b112..a5d2c54 100644 --- a/Tests/Unit/MSFT_ScriptResource.Tests.ps1 +++ b/Tests/Unit/MSFT_ScriptResource.Tests.ps1 @@ -32,7 +32,7 @@ try It 'Should throw an error for malformed get script' { $errorMessage = $script:localizedData.GetScriptDidNotReturnHashtable - { $null = Get-TargetResource @getTargetResourceParameters } | Should Throw $errorMessage + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -47,7 +47,7 @@ try It 'Should throw an error for malformed get script' { $errorMessage = $script:localizedData.GetScriptDidNotReturnHashtable - { $null = Get-TargetResource @getTargetResourceParameters } | Should Throw $errorMessage + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -65,7 +65,7 @@ try } It 'Should throw error from get script' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Throw $testErrorRecord + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Throw -ExpectedMessage $testErrorRecord } } @@ -78,13 +78,13 @@ try TestScript = 'NotUsed' SetScript = 'NotUsed' } - + It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should use script execution helper to run script' { - $expectedScriptBlock = [ScriptBlock]::Create($getTargetResourceParameters.GetScript) + $expectedScriptBlock = [System.Management.Automation.ScriptBlock]::Create($getTargetResourceParameters.GetScript) $null = Get-TargetResource @getTargetResourceParameters @@ -95,15 +95,15 @@ try Assert-MockCalled -CommandName 'Invoke-Script' -ParameterFilter $invokeScriptParameterFilter -Times 1 -Scope 'It' } - + It 'Should return a hashtable' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return the output from the specified get script' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters - Compare-Object -ReferenceObject $testScriptResult -DifferenceObject $getTargetResourceResult | Should Be $null + Compare-Object -ReferenceObject $testScriptResult -DifferenceObject $getTargetResourceResult | Should -Be $null } } @@ -114,34 +114,34 @@ try SetScript = 'NotUsed' Credential = $script:testCredenital } - + It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should use script execution helper to run script with the specified Credential' { - $expectedScriptBlock = [ScriptBlock]::Create($getTargetResourceParameters.GetScript) + $expectedScriptBlock = [System.Management.Automation.ScriptBlock]::Create($getTargetResourceParameters.GetScript) $null = Get-TargetResource @getTargetResourceParameters $invokeScriptParameterFilter = { $scriptBlockParameterCorrect = $null -eq (Compare-Object -ReferenceObject $expectedScriptBlock.Ast -DifferenceObject $ScriptBlock.Ast) $credentialParameterCorrect = $null -eq (Compare-Object -ReferenceObject $getTargetResourceParameters.Credential -DifferenceObject $Credential) - - return $scriptBlockParameterCorrect -and $credentialParameterCorrect + + return $scriptBlockParameterCorrect -and $credentialParameterCorrect } Assert-MockCalled -CommandName 'Invoke-Script' -ParameterFilter $invokeScriptParameterFilter -Times 1 -Scope 'It' } - + It 'Should return a hashtable' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should return the output from the specified get script' { $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters - Compare-Object -ReferenceObject $testScriptResult -DifferenceObject $getTargetResourceResult | Should Be $null + Compare-Object -ReferenceObject $testScriptResult -DifferenceObject $getTargetResourceResult | Should -Be $null } } } @@ -157,11 +157,11 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should use script execution helper to run script' { - $expectedScriptBlock = [ScriptBlock]::Create($setTargetResourceParameters.SetScript) + $expectedScriptBlock = [System.Management.Automation.ScriptBlock]::Create($setTargetResourceParameters.SetScript) Set-TargetResource @setTargetResourceParameters @@ -183,19 +183,19 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should use script execution helper to run script with specified Credential' { - $expectedScriptBlock = [ScriptBlock]::Create($setTargetResourceParameters.SetScript) + $expectedScriptBlock = [System.Management.Automation.ScriptBlock]::Create($setTargetResourceParameters.SetScript) Set-TargetResource @setTargetResourceParameters $invokeScriptParameterFilter = { $scriptBlockParameterCorrect = $null -eq (Compare-Object -ReferenceObject $expectedScriptBlock.Ast -DifferenceObject $ScriptBlock.Ast) $credentialParameterCorrect = $null -eq (Compare-Object -ReferenceObject $setTargetResourceParameters.Credential -DifferenceObject $Credential) - - return $scriptBlockParameterCorrect -and $credentialParameterCorrect + + return $scriptBlockParameterCorrect -and $credentialParameterCorrect } Assert-MockCalled -CommandName 'Invoke-Script' -ParameterFilter $invokeScriptParameterFilter -Times 1 -Scope 'It' @@ -216,7 +216,7 @@ try } It 'Should throw error from set script' { - { Set-TargetResource @setTargetResourceParameters } | Should Throw $testErrorRecord + { Set-TargetResource @setTargetResourceParameters } | Should -Throw -ExpectedMessage $testErrorRecord } } } @@ -233,7 +233,7 @@ try It 'Should throw an error for malformed test script' { $errorMessage = $script:localizedData.TestScriptDidNotReturnBoolean - { $null = Test-TargetResource @testTargetResourceParameters } | Should Throw $errorMessage + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -251,7 +251,7 @@ try } It 'Should throw error from test script' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Throw $testErrorRecord + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Throw -ExpectedMessage $testErrorRecord } } @@ -266,11 +266,11 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should use script execution helper to run script' { - $expectedScriptBlock = [ScriptBlock]::Create($testTargetResourceParameters.TestScript) + $expectedScriptBlock = [System.Management.Automation.ScriptBlock]::Create($testTargetResourceParameters.TestScript) $null = Test-TargetResource @testTargetResourceParameters @@ -281,10 +281,10 @@ try Assert-MockCalled -CommandName 'Invoke-Script' -ParameterFilter $invokeScriptParameterFilter -Times 1 -Scope 'It' } - + It 'Should return the expected boolean' { $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters - $testTargetResourceResult | Should Be $expectedBoolean + $testTargetResourceResult | Should -Be $expectedBoolean } } @@ -297,27 +297,27 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should use script execution helper to run script with specified Credential' { - $expectedScriptBlock = [ScriptBlock]::Create($testTargetResourceParameters.TestScript) + $expectedScriptBlock = [System.Management.Automation.ScriptBlock]::Create($testTargetResourceParameters.TestScript) $null = Test-TargetResource @testTargetResourceParameters $invokeScriptParameterFilter = { $scriptBlockParameterCorrect = $null -eq (Compare-Object -ReferenceObject $expectedScriptBlock.Ast -DifferenceObject $ScriptBlock.Ast) $credentialParameterCorrect = $null -eq (Compare-Object -ReferenceObject $testTargetResourceParameters.Credential -DifferenceObject $Credential) - - return $scriptBlockParameterCorrect -and $credentialParameterCorrect + + return $scriptBlockParameterCorrect -and $credentialParameterCorrect } Assert-MockCalled -CommandName 'Invoke-Script' -ParameterFilter $invokeScriptParameterFilter -Times 1 -Scope 'It' } - + It 'Should return the expected boolean' { $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters - $testTargetResourceResult | Should Be $expectedBoolean + $testTargetResourceResult | Should -Be $expectedBoolean } } @@ -332,11 +332,11 @@ try } It 'Should not throw' { - { $null = Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should use script execution helper to run script' { - $expectedScriptBlock = [ScriptBlock]::Create($testTargetResourceParameters.TestScript) + $expectedScriptBlock = [System.Management.Automation.ScriptBlock]::Create($testTargetResourceParameters.TestScript) $null = Test-TargetResource @testTargetResourceParameters @@ -347,10 +347,10 @@ try Assert-MockCalled -CommandName 'Invoke-Script' -ParameterFilter $invokeScriptParameterFilter -Times 1 -Scope 'It' } - + It 'Should return the expected boolean' { $testTargetResourceResult = Test-TargetResource @testTargetResourceParameters - $testTargetResourceResult | Should Be $expectedBoolean + $testTargetResourceResult | Should -Be $expectedBoolean } } @@ -365,7 +365,7 @@ try It 'Should throw an error for malformed test script' { $errorMessage = $script:localizedData.TestScriptDidNotReturnBoolean - { $null = Test-TargetResource @testTargetResourceParameters } | Should Throw $errorMessage + { $null = Test-TargetResource @testTargetResourceParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -381,22 +381,22 @@ try } It 'Should not throw' { - { $null = Invoke-Script @scriptExecutionHelperParameters } | Should Not Throw + { $null = Invoke-Script @scriptExecutionHelperParameters } | Should -Not -Throw } It 'Should return an error record' { $scriptExecutionHelperResult = Invoke-Script @scriptExecutionHelperParameters - $scriptExecutionHelperResult -is [System.Management.Automation.ErrorRecord] | Should Be $true + $scriptExecutionHelperResult -is [System.Management.Automation.ErrorRecord] | Should -BeTrue } It 'Should return an error record' { $scriptExecutionHelperResult = Invoke-Script @scriptExecutionHelperParameters - $scriptExecutionHelperResult -is [System.Management.Automation.ErrorRecord] | Should Be $true + $scriptExecutionHelperResult -is [System.Management.Automation.ErrorRecord] | Should -BeTrue } It 'Should return error with expected message from script' { $scriptExecutionHelperResult = Invoke-Script @scriptExecutionHelperParameters - $scriptExecutionHelperResult.Exception.Message | Should Be $testErrorMessage + $scriptExecutionHelperResult.Exception.Message | Should -Be $testErrorMessage } } @@ -407,7 +407,7 @@ try } It 'Should not throw' { - { $null = Invoke-Script @scriptExecutionHelperParameters } | Should Not Throw + { $null = Invoke-Script @scriptExecutionHelperParameters } | Should -Not -Throw } It 'Should run script through Invoke-Command using the specified Credential' { @@ -425,7 +425,7 @@ try It 'Should return nothing' { $scriptExecutionHelperResult = Invoke-Script @scriptExecutionHelperParameters - $scriptExecutionHelperResult | Should Be $null + $scriptExecutionHelperResult | Should -Be $null } } @@ -443,8 +443,8 @@ try It 'Should return result of script' { $scriptExecutionHelperResult = Invoke-Script @scriptExecutionHelperParameters - $scriptExecutionHelperResult | Should Be $testScriptResult - } + $scriptExecutionHelperResult | Should -Be $testScriptResult + } } } } diff --git a/Tests/Unit/MSFT_ServiceResource.Tests.ps1 b/Tests/Unit/MSFT_ServiceResource.Tests.ps1 index 78c7a5c..7c83880 100644 --- a/Tests/Unit/MSFT_ServiceResource.Tests.ps1 +++ b/Tests/Unit/MSFT_ServiceResource.Tests.ps1 @@ -22,7 +22,7 @@ try InModuleScope 'MSFT_ServiceResource' { $script:testServiceName = 'DscTestService' - + $script:testUsername1 = 'TestUser1' $script:testUsername2 = 'TestUser2' @@ -43,7 +43,7 @@ try Context 'Service does not exist' { It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @GetTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve service' { @@ -61,7 +61,7 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [Hashtable] | Should -BeTrue } It 'Should return the service name' { @@ -99,13 +99,13 @@ try } $convertToStartupTypeStringResult = 'TestStartupTypeString' - + Mock -CommandName 'Get-Service' -MockWith { return $testService } Mock -CommandName 'Get-ServiceCimInstance' -MockWith { return $testServiceCimInstance } Mock -CommandName 'ConvertTo-StartupTypeString' -MockWith { return $convertToStartupTypeStringResult } It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve service' { @@ -123,7 +123,7 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [Hashtable] | Should -BeTrue } It 'Should return the service name' { @@ -188,13 +188,13 @@ try } $convertToStartupTypeStringResult = 'TestStartupTypeString' - + Mock -CommandName 'Get-Service' -MockWith { return $testService } Mock -CommandName 'Get-ServiceCimInstance' -MockWith { return $testServiceCimInstance } Mock -CommandName 'ConvertTo-StartupTypeString' -MockWith { return $convertToStartupTypeStringResult } It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve service' { @@ -212,7 +212,7 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [Hashtable] | Should -BeTrue } It 'Should return the service name' { @@ -284,13 +284,13 @@ try } $convertToStartupTypeStringResult = 'TestStartupTypeString' - + Mock -CommandName 'Get-Service' -MockWith { return $testService } Mock -CommandName 'Get-ServiceCimInstance' -MockWith { return $testServiceCimInstance } Mock -CommandName 'ConvertTo-StartupTypeString' -MockWith { return $convertToStartupTypeStringResult } It 'Should not throw' { - { $null = Get-TargetResource @getTargetResourceParameters } | Should Not Throw + { $null = Get-TargetResource @getTargetResourceParameters } | Should -Not -Throw } It 'Should retrieve service' { @@ -308,7 +308,7 @@ try $getTargetResourceResult = Get-TargetResource @getTargetResourceParameters It 'Should return a hashtable' { - $getTargetResourceResult -is [Hashtable] | Should Be $true + $getTargetResourceResult -is [Hashtable] | Should -BeTrue } It 'Should return the service name' { @@ -375,7 +375,7 @@ try It 'Should throw an error for BuiltInAccount and Credential conflict' { $expectedErrorMessage = $script:localizedData.BuiltInAccountAndCredentialSpecified -f $setTargetResourceParameters.Name - { Set-TargetResource @setTargetResourceParameters } | Should Throw $expectedErrorMessage + { Set-TargetResource @setTargetResourceParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -386,7 +386,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -430,7 +430,7 @@ try It 'Should throw an error for the missing path' { $expectedErrorMessage = $script:localizedData.ServiceDoesNotExistPathMissingError -f $script:testServiceName - { Set-TargetResource @setTargetResourceParameters } | Should Throw $expectedErrorMessage + { Set-TargetResource @setTargetResourceParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -442,7 +442,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -493,7 +493,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should check for a startup type and state conflict' { @@ -544,7 +544,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should check for a startup type and state conflict' { @@ -604,7 +604,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -647,7 +647,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -677,7 +677,7 @@ try It 'Should start the service' { Assert-MockCalled -CommandName 'Start-ServiceWithTimeout' -ParameterFilter { $ServiceName -eq $setTargetResourceParameters.Name } -Times 1 -Scope 'Context' } - + It 'Should not attempt to stop or restart the service' { Assert-MockCalled -CommandName 'Stop-ServiceWithTimeout' -Times 0 -Scope 'Context' } @@ -691,7 +691,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -742,7 +742,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should check for a startup type and state conflict' { @@ -792,7 +792,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should check for a startup type and state conflict' { @@ -836,7 +836,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -873,7 +873,7 @@ try } Mock -CommandName 'Set-ServicePath' -MockWith { return $false } - + Context 'Service exists, Ensure set to Present, and matching Path to service path specified' { $setTargetResourceParameters = @{ Name = $script:testServiceName @@ -882,7 +882,7 @@ try } It 'Should not throw' { - { Set-TargetResource @setTargetResourceParameters } | Should Not Throw + { Set-TargetResource @setTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -939,7 +939,7 @@ try It 'Should throw an error for BuiltInAccount and Credential conflict' { $expectedErrorMessage = $script:localizedData.BuiltInAccountAndCredentialSpecified -f $testTargetResourceParameters.Name - { Test-TargetResource @testTargetResourceParameters } | Should Throw $expectedErrorMessage + { Test-TargetResource @testTargetResourceParameters } | Should -Throw -ExpectedMessage $expectedErrorMessage } } @@ -948,9 +948,9 @@ try Name = $script:testServiceName Ensure = 'Absent' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -970,7 +970,7 @@ try } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } @@ -979,9 +979,9 @@ try Name = $script:testServiceName Ensure = 'Present' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1001,7 +1001,7 @@ try } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } @@ -1025,9 +1025,9 @@ try Name = $script:testServiceName Ensure = 'Absent' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1047,7 +1047,7 @@ try } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } @@ -1056,9 +1056,9 @@ try Name = $script:testServiceName Ensure = 'Present' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1078,15 +1078,15 @@ try } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } Context 'Service exists, Ensure set to Present, and all matching parameters specified except Credential' { $testTargetResourceParameters = $serviceResourceWithAllProperties - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should check for a startup type and state conflict' { @@ -1106,7 +1106,7 @@ try } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } @@ -1128,12 +1128,10 @@ try Ensure = 'Present' $mismatchingParameterName = $mismatchingParameters[$mismatchingParameterName] } - - It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw - } - + It 'Should not throw' { + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw + } if ($mismatchingParameterName -eq 'StartupType') { @@ -1161,7 +1159,7 @@ try } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } } @@ -1172,9 +1170,9 @@ try Ensure = 'Present' State = 'Ignore' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1194,7 +1192,7 @@ try } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } @@ -1216,9 +1214,9 @@ try Ensure = 'Present' Credential = $script:testCredential1 } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1238,7 +1236,7 @@ try } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } @@ -1248,9 +1246,9 @@ try Ensure = 'Present' Credential = $script:testCredential2 } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1270,7 +1268,7 @@ try } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } @@ -1292,9 +1290,9 @@ try { $testTargetResourceParameters[$allowedEmptyPropertyName] = '' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1314,7 +1312,7 @@ try } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } } @@ -1330,7 +1328,7 @@ try { $serviceResourceWithNullProperties[$nullPropertyName] = $null } - + Mock -CommandName 'Get-TargetResource' -MockWith { return $serviceResourceWithNullProperties } foreach ($nullPropertyName in $allowedEmptyPropertyNames) @@ -1341,9 +1339,9 @@ try Ensure = 'Present' $nullPropertyName = 'Something' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1363,7 +1361,7 @@ try } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } @@ -1372,9 +1370,9 @@ try Name = $serviceResourceWithNullProperties.Name Ensure = 'Present' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1394,7 +1392,7 @@ try } It 'Should return true' { - Test-TargetResource @testTargetResourceParameters | Should Be $true + Test-TargetResource @testTargetResourceParameters | Should -BeTrue } } } @@ -1407,9 +1405,9 @@ try Ensure = 'Present' Path = 'Mismatching path' } - + It 'Should not throw' { - { Test-TargetResource @testTargetResourceParameters } | Should Not Throw + { Test-TargetResource @testTargetResourceParameters } | Should -Not -Throw } It 'Should not check for a startup type and state conflict' { @@ -1429,7 +1427,7 @@ try } It 'Should return false' { - Test-TargetResource @testTargetResourceParameters | Should Be $false + Test-TargetResource @testTargetResourceParameters | Should -BeFalse } } } @@ -1439,7 +1437,7 @@ try Context 'Service does not exist' { It 'Should not throw' { - { Get-ServiceCimInstance -ServiceName $script:testServiceName } | Should Not Throw + { Get-ServiceCimInstance -ServiceName $script:testServiceName } | Should -Not -Throw } It 'Should retrieve the CIM instance of the service with the given name' { @@ -1447,7 +1445,7 @@ try } It 'Should return null' { - Get-ServiceCimInstance -ServiceName $script:testServiceName | Should Be $null + Get-ServiceCimInstance -ServiceName $script:testServiceName | Should -Be $null } } @@ -1457,7 +1455,7 @@ try Context 'Service exists' { It 'Should not throw' { - { Get-ServiceCimInstance -ServiceName $script:testServiceName } | Should Not Throw + { Get-ServiceCimInstance -ServiceName $script:testServiceName } | Should -Not -Throw } It 'Should retrieve the CIM instance of the service with the given name' { @@ -1465,7 +1463,7 @@ try } It 'Should return the retrieved CIM instance' { - Get-ServiceCimInstance -ServiceName $script:testServiceName | Should Be $testCimInstance + Get-ServiceCimInstance -ServiceName $script:testServiceName | Should -Be $testCimInstance } } } @@ -1473,19 +1471,19 @@ try Describe 'Service\ConvertTo-StartupTypeString' { Context 'StartupType specifed as Auto' { It 'Should return Automatic' { - ConvertTo-StartupTypeString -StartMode 'Auto' | Should Be 'Automatic' + ConvertTo-StartupTypeString -StartMode 'Auto' | Should -Be 'Automatic' } } Context 'StartupType specifed as Manual' { It 'Should return Manual' { - ConvertTo-StartupTypeString -StartMode 'Manual' | Should Be 'Manual' + ConvertTo-StartupTypeString -StartMode 'Manual' | Should -Be 'Manual' } } Context 'StartupType specifed as Disabled' { It 'Should return Disabled' { - ConvertTo-StartupTypeString -StartMode 'Disabled' | Should Be 'Disabled' + ConvertTo-StartupTypeString -StartMode 'Disabled' | Should -Be 'Disabled' } } } @@ -1509,20 +1507,20 @@ try { It 'Should throw error for conflicting state and startup type' { $errorMessage = $script:localizedData.StartupTypeStateConflict -f $assertNoStartupTypeStateConflictParameters.ServiceName, $startupTypeValue, $stateValue - { Assert-NoStartupTypeStateConflict @assertNoStartupTypeStateConflictParameters } | Should Throw $errorMessage - } + { Assert-NoStartupTypeStateConflict @assertNoStartupTypeStateConflictParameters } | Should -Throw -ExpectedMessage $errorMessage + } } elseif ($stateValue -eq 'Stopped' -and $startupTypeValue -eq 'Automatic') { It 'Should throw error for conflicting state and startup type' { $errorMessage = $script:localizedData.StartupTypeStateConflict -f $assertNoStartupTypeStateConflictParameters.ServiceName, $startupTypeValue, $stateValue - { Assert-NoStartupTypeStateConflict @assertNoStartupTypeStateConflictParameters } | Should Throw $errorMessage + { Assert-NoStartupTypeStateConflict @assertNoStartupTypeStateConflictParameters } | Should -Throw -ExpectedMessage $errorMessage } } else { It 'Should not throw' { - { Assert-NoStartupTypeStateConflict @assertNoStartupTypeStateConflictParameters } | Should Not Throw + { Assert-NoStartupTypeStateConflict @assertNoStartupTypeStateConflictParameters } | Should -Not -Throw } } } @@ -1534,13 +1532,13 @@ try Context 'Specified paths match' { It 'Should return true' { $matchingPath = 'MatchingPath' - Test-PathsMatch -ExpectedPath $matchingPath -ActualPath $matchingPath | Should Be $true + Test-PathsMatch -ExpectedPath $matchingPath -ActualPath $matchingPath | Should -BeTrue } } Context 'Specified paths do not match' { It 'Should return false' { - Test-PathsMatch -ExpectedPath 'Path1' -ActualPath 'Path2' | Should Be $false + Test-PathsMatch -ExpectedPath 'Path1' -ActualPath 'Path2' | Should -BeFalse } } } @@ -1548,26 +1546,26 @@ try Describe 'Service\ConvertTo-StartName' { Context 'Username specified as LocalSystem' { It 'Should return .\LocalSystem' { - ConvertTo-StartName -Username 'LocalSystem' | Should Be '.\LocalSystem' + ConvertTo-StartName -Username 'LocalSystem' | Should -Be '.\LocalSystem' } } Context 'Username specified as LocalService' { It 'Should return NT Authority\LocalService' { - ConvertTo-StartName -Username 'LocalService' | Should Be 'NT Authority\LocalService' + ConvertTo-StartName -Username 'LocalService' | Should -Be 'NT Authority\LocalService' } } Context 'Username specified as NetworkService' { It 'Should return NT Authority\NetworkService' { - ConvertTo-StartName -Username 'NetworkService' | Should Be 'NT Authority\NetworkService' + ConvertTo-StartName -Username 'NetworkService' | Should -Be 'NT Authority\NetworkService' } } Context 'Custom username specified without any \ or @ characters' { It 'Should return custom username prefixed with .\' { $customUsername = 'TestUsername' - ConvertTo-StartName -Username $customUsername | Should Be ".\$customUsername" + ConvertTo-StartName -Username $customUsername | Should -Be ".\$customUsername" } } @@ -1575,21 +1573,21 @@ try It 'Should return custom username prefixed with .\ instead of the local computer name' { $customUsername = 'TestUsername' $customUsernameWithComputerNamePrefix = "$env:computerName\$customUsername" - ConvertTo-StartName -Username $customUsernameWithComputerNamePrefix | Should Be ".\$customUsername" + ConvertTo-StartName -Username $customUsernameWithComputerNamePrefix | Should -Be ".\$customUsername" } } Context 'Custom username specified with a \ character and a custom domain' { It 'Should return the custom username with no changes' { $customUsername = 'TestDomain\TestUsername' - ConvertTo-StartName -Username $customUsername | Should Be $customUsername + ConvertTo-StartName -Username $customUsername | Should -Be $customUsername } } Context 'Custom username specified with an @ character' { It 'Should return the custom username with no changes' { $customUsername = 'TestUsername@TestDomain' - ConvertTo-StartName -Username $customUsername | Should Be $customUsername + ConvertTo-StartName -Username $customUsername | Should -Be $customUsername } } } @@ -1615,7 +1613,7 @@ try } It 'Should not throw' { - { Set-ServicePath @setServicePathParameters } | Should Not Throw + { Set-ServicePath @setServicePathParameters } | Should -Not -Throw } It 'Should retrieve the service CIM instance' { @@ -1631,7 +1629,7 @@ try } It 'Should return false' { - Set-ServicePath @setServicePathParameters | Should Be $false + Set-ServicePath @setServicePathParameters | Should -BeFalse } } @@ -1644,7 +1642,7 @@ try } It 'Should not throw' { - { Set-ServicePath @setServicePathParameters } | Should Not Throw + { Set-ServicePath @setServicePathParameters } | Should -Not -Throw } It 'Should retrieve the service CIM instance' { @@ -1660,10 +1658,10 @@ try } It 'Should return true' { - Set-ServicePath @setServicePathParameters | Should Be $true + Set-ServicePath @setServicePathParameters | Should -BeTrue } } - + $invokeCimMethodFailResult = @{ ReturnValue = 1 } @@ -1679,7 +1677,7 @@ try It 'Should throw error for failed service path change' { $errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $setServicePathParameters.ServiceName, 'PathName', $invokeCimMethodFailResult.ReturnValue - { Set-ServicePath @setServicePathParameters } | Should Throw $errorMessage + { Set-ServicePath @setServicePathParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -1692,7 +1690,7 @@ try } } - Describe 'Service\Set-ServiceDependencies' { + Describe 'Service\Set-ServiceDependency' { $testServiceCimInstance = New-CimInstance -ClassName 'Win32_Service' -ClientOnly try { @@ -1716,11 +1714,11 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should -Not -Throw } It 'Should retrieve the service' { - Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' } It 'Should not retrieve the service CIM instance' { @@ -1739,11 +1737,11 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should -Not -Throw } It 'Should retrieve the service' { - Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' } It 'Should retrieve the service CIM instance' { @@ -1762,11 +1760,11 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should -Not -Throw } It 'Should retrieve the service' { - Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' } It 'Should retrieve the service CIM instance' { @@ -1791,11 +1789,11 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should -Not -Throw } It 'Should retrieve the service' { - Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' } It 'Should not retrieve the service CIM instance' { @@ -1814,11 +1812,11 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should -Not -Throw } It 'Should retrieve the service' { - Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Get-Service' -ParameterFilter { $Name -eq $setServiceDependenciesParameters.ServiceName } -Times 1 -Scope 'Context' } It 'Should retrieve the service CIM instance' { @@ -1827,9 +1825,9 @@ try It 'Should change the service' { Assert-MockCalled -CommandName 'Invoke-CimMethod' -ParameterFilter { $InputObject -eq $testServiceCimInstance -and $MethodName -eq 'Change' -and $null -eq (Compare-Object -ReferenceObject $setServiceDependenciesParameters.Dependencies -DifferenceObject $Arguments.ServiceDependencies) } -Times 1 -Scope 'Context' - } + } } - + $invokeCimMethodFailResult = @{ ReturnValue = 1 } @@ -1845,7 +1843,7 @@ try It 'Should throw error for failed service path change' { $errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $setServiceDependenciesParameters.ServiceName, 'ServiceDependencies', $invokeCimMethodFailResult.ReturnValue - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Throw $errorMessage + { Set-ServiceDependency @setServiceDependenciesParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -1862,7 +1860,7 @@ try Mock -CommandName 'Get-ServiceCimInstance' -MockWith { return $testServiceCimInstance } Mock -CommandName 'Grant-LogOnAsServiceRight' -MockWith { } Mock -CommandName 'ConvertTo-StartName' -MockWith { return $Username } - + $invokeCimMethodSuccessResult = @{ ReturnValue = 0 } @@ -1875,7 +1873,7 @@ try } It 'Should not throw' { - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Not Throw + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -1902,7 +1900,7 @@ try } It 'Should not throw' { - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Not Throw + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -1929,7 +1927,7 @@ try } It 'Should not throw' { - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Not Throw + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -1959,7 +1957,7 @@ try } It 'Should not throw' { - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Not Throw + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -1986,7 +1984,7 @@ try } It 'Should not throw' { - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Not Throw + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2013,7 +2011,7 @@ try } It 'Should not throw' { - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Not Throw + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2040,7 +2038,7 @@ try } It 'Should not throw' { - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Not Throw + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2056,7 +2054,7 @@ try } It 'Should change service' { - Assert-MockCalled -CommandName 'Invoke-CimMethod' -ParameterFilter { $InputObject -eq $testServiceCimInstance -and $MethodName -eq 'Change' -and $Arguments.StartName -eq $setServiceAccountPropertyParameters.BuiltInAccount -and $Arguments.StartPassword -eq [String]::Empty } -Times 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Invoke-CimMethod' -ParameterFilter { $InputObject -eq $testServiceCimInstance -and $MethodName -eq 'Change' -and $Arguments.StartName -eq $setServiceAccountPropertyParameters.BuiltInAccount -and $Arguments.StartPassword -eq [System.String]::Empty } -Times 1 -Scope 'Context' } } @@ -2075,7 +2073,7 @@ try It 'Should throw an error for service change failure' { $errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $setServiceAccountPropertyParameters.ServiceName, 'DesktopInteract', $invokeCimMethodFailResult.ReturnValue - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Throw $errorMessage + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2088,7 +2086,7 @@ try It 'Should throw an error for service change failure' { $errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $setServiceAccountPropertyParameters.ServiceName, 'StartName, StartPassword', $invokeCimMethodFailResult.ReturnValue - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Throw $errorMessage + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Throw -ExpectedMessage $errorMessage } } @@ -2101,7 +2099,7 @@ try It 'Should throw an error for service change failure' { $errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $setServiceAccountPropertyParameters.ServiceName, 'StartName, StartPassword', $invokeCimMethodFailResult.ReturnValue - { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should Throw $errorMessage + { Set-ServiceAccountProperty @setServiceAccountPropertyParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -2134,7 +2132,7 @@ try } It 'Should not throw' { - { Set-ServiceStartupType @setServiceStartupTypeParameters } | Should Not Throw + { Set-ServiceStartupType @setServiceStartupTypeParameters } | Should -Not -Throw } It 'Should retrieve the service CIM instance' { @@ -2153,7 +2151,7 @@ try } It 'Should not throw' { - { Set-ServiceStartupType @setServiceStartupTypeParameters } | Should Not Throw + { Set-ServiceStartupType @setServiceStartupTypeParameters } | Should -Not -Throw } It 'Should retrieve the service CIM instance' { @@ -2180,7 +2178,7 @@ try It 'Should throw error for failed service change' { $errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $setServiceStartupTypeParameters.ServiceName, 'StartMode', $invokeCimMethodFailResult.ReturnValue - { Set-ServiceStartupType @setServiceStartupTypeParameters } | Should Throw $errorMessage + { Set-ServiceStartupType @setServiceStartupTypeParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -2201,7 +2199,7 @@ try Mock -CommandName 'Get-ServiceCimInstance' -MockWith { return $testServiceCimInstance } Mock -CommandName 'Set-Service' -MockWith { } - Mock -CommandName 'Set-ServiceDependencies' -MockWith { } + Mock -CommandName 'Set-ServiceDependency' -MockWith { } Mock -CommandName 'Set-ServiceAccountProperty' -MockWith { } Mock -CommandName 'Set-ServiceStartupType' -MockWith { } @@ -2211,7 +2209,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2223,7 +2221,7 @@ try } It 'Should not set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -Times 0 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -Times 0 -Scope 'Context' } It 'Should not set service account properties' { @@ -2242,7 +2240,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2254,7 +2252,7 @@ try } It 'Should not set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -Times 0 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -Times 0 -Scope 'Context' } It 'Should not set service account properties' { @@ -2273,7 +2271,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2285,7 +2283,7 @@ try } It 'Should not set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -Times 0 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -Times 0 -Scope 'Context' } It 'Should not set service account properties' { @@ -2305,7 +2303,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2317,7 +2315,7 @@ try } It 'Should not set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -Times 0 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -Times 0 -Scope 'Context' } It 'Should not set service account properties' { @@ -2336,7 +2334,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2348,7 +2346,7 @@ try } It 'Should set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -ParameterFilter { $ServiceName -eq $setServicePropertyParameters.ServiceName -and $null -eq (Compare-Object -ReferenceObject $setServicePropertyParameters.Dependencies -DifferenceObject $Dependencies) } -Times 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -ParameterFilter { $ServiceName -eq $setServicePropertyParameters.ServiceName -and $null -eq (Compare-Object -ReferenceObject $setServicePropertyParameters.Dependencies -DifferenceObject $Dependencies) } -Times 1 -Scope 'Context' } It 'Should not set service account properties' { @@ -2367,7 +2365,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2379,11 +2377,11 @@ try } It 'Should not set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -Times 0 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -Times 0 -Scope 'Context' } It 'Should set service account properties' { - Assert-MockCalled -CommandName 'Set-ServiceAccountProperty' -ParameterFilter { $ServiceName -eq $setServicePropertyParameters.ServiceName -and [PSCredential]::Equals($setServicePropertyParameters.Credential, $Credential) } -Times 1 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceAccountProperty' -ParameterFilter { $ServiceName -eq $setServicePropertyParameters.ServiceName -and [System.Management.Automation.PSCredential]::Equals($setServicePropertyParameters.Credential, $Credential) } -Times 1 -Scope 'Context' } It 'Should not set service startup type' { @@ -2398,7 +2396,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2410,7 +2408,7 @@ try } It 'Should not set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -Times 0 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -Times 0 -Scope 'Context' } It 'Should set service account properties' { @@ -2429,7 +2427,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2441,7 +2439,7 @@ try } It 'Should not set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -Times 0 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -Times 0 -Scope 'Context' } It 'Should set service account properties' { @@ -2460,7 +2458,7 @@ try } It 'Should not throw' { - { Set-ServiceProperty @setServicePropertyParameters } | Should Not Throw + { Set-ServiceProperty @setServicePropertyParameters } | Should -Not -Throw } It 'Should retrieve service CIM instance' { @@ -2472,7 +2470,7 @@ try } It 'Should not set service dependencies' { - Assert-MockCalled -CommandName 'Set-ServiceDependencies' -Times 0 -Scope 'Context' + Assert-MockCalled -CommandName 'Set-ServiceDependency' -Times 0 -Scope 'Context' } It 'Should not set service account properties' { @@ -2496,7 +2494,7 @@ try } It 'Should not throw' { - { Remove-ServiceWithTimeout @removeServiceWithTimeoutParameters } | Should Not Throw + { Remove-ServiceWithTimeout @removeServiceWithTimeoutParameters } | Should -Not -Throw } It 'Should remove service' { @@ -2518,7 +2516,7 @@ try It 'Should throw error for service removal timeout' { $errorMessage = $script:localizedData.ServiceDeletionFailed -f $removeServiceWithTimeoutParameters.Name - { Remove-ServiceWithTimeout @removeServiceWithTimeoutParameters } | Should Throw $errorMessage + { Remove-ServiceWithTimeout @removeServiceWithTimeoutParameters } | Should -Throw -ExpectedMessage $errorMessage } } } @@ -2532,10 +2530,10 @@ try StartupTimeout = 500 } - $expectedTimeSpan = [TimeSpan]::FromMilliseconds($startServiceWithTimeoutParameters.StartupTimeout) - + $expectedTimeSpan = [System.TimeSpan]::FromMilliseconds($startServiceWithTimeoutParameters.StartupTimeout) + It 'Should not throw' { - { Start-ServiceWithTimeout @startServiceWithTimeoutParameters } | Should Not Throw + { Start-ServiceWithTimeout @startServiceWithTimeoutParameters } | Should -Not -Throw } It 'Should start service' { @@ -2543,7 +2541,7 @@ try } It 'Should wait for service to start' { - Assert-MockCalled -CommandName 'Wait-ServiceStateWithTimeout' -ParameterFilter { $ServiceName -eq $startServiceWithTimeoutParameters.ServiceName -and $State -eq [System.ServiceProcess.ServiceControllerStatus]::Running -and [TimeSpan]::Equals($expectedTimeSpan, $WaitTimeSpan) } -Times 1 -Scope 'Describe' + Assert-MockCalled -CommandName 'Wait-ServiceStateWithTimeout' -ParameterFilter { $ServiceName -eq $startServiceWithTimeoutParameters.ServiceName -and $State -eq [System.ServiceProcess.ServiceControllerStatus]::Running -and [System.TimeSpan]::Equals($expectedTimeSpan, $WaitTimeSpan) } -Times 1 -Scope 'Describe' } } @@ -2556,10 +2554,10 @@ try TerminateTimeout = 500 } - $expectedTimeSpan = [TimeSpan]::FromMilliseconds($stopServiceWithTimeoutParameters.TerminateTimeout) - + $expectedTimeSpan = [System.TimeSpan]::FromMilliseconds($stopServiceWithTimeoutParameters.TerminateTimeout) + It 'Should not throw' { - { Stop-ServiceWithTimeout @stopServiceWithTimeoutParameters } | Should Not Throw + { Stop-ServiceWithTimeout @stopServiceWithTimeoutParameters } | Should -Not -Throw } It 'Should stop service' { @@ -2567,7 +2565,7 @@ try } It 'Should wait for service to stop' { - Assert-MockCalled -CommandName 'Wait-ServiceStateWithTimeout' -ParameterFilter { $ServiceName -eq $stopServiceWithTimeoutParameters.ServiceName -and $State -eq [System.ServiceProcess.ServiceControllerStatus]::Stopped -and [TimeSpan]::Equals($expectedTimeSpan, $WaitTimeSpan) } -Times 1 -Scope 'Describe' + Assert-MockCalled -CommandName 'Wait-ServiceStateWithTimeout' -ParameterFilter { $ServiceName -eq $stopServiceWithTimeoutParameters.ServiceName -and $State -eq [System.ServiceProcess.ServiceControllerStatus]::Stopped -and [System.TimeSpan]::Equals($expectedTimeSpan, $WaitTimeSpan) } -Times 1 -Scope 'Describe' } } } diff --git a/Tests/Unit/MSFT_UserResource.Tests.ps1 b/Tests/Unit/MSFT_UserResource.Tests.ps1 index 952d634..538c31f 100644 --- a/Tests/Unit/MSFT_UserResource.Tests.ps1 +++ b/Tests/Unit/MSFT_UserResource.Tests.ps1 @@ -73,13 +73,13 @@ try { UserMayChangePassword = $false PasswordChangeRequired = $false } - - + + $modifiableUserName = 'newUser1234' $modifiableUserPassword = 'ThisIsAStrongPassword543!' $modifiableUserSecurePassword = ConvertTo-SecureString -String $modifiableUserPassword -AsPlainText -Force $modifiableUserCredential = New-Object PSCredential ($modifiableUserName, $modifiableUserSecurePassword) - + # Mock user object that gets modified by the Set-TargetResourceOnNanoServer tests $modifiableUserValues = @{ Name = $modifiableUserName @@ -119,7 +119,7 @@ try { $script:UserObject.DisplayName = $existingUserValues.DisplayName $script:UserObject.UserCannotChangePassword = $existingUserValues.UserCannotChangePassword $script:UserObject.PasswordNeverExpires = $existingUserValues.PasswordNeverExpires - + } # Properties that are used on both Nano and Full Sku @@ -174,7 +174,7 @@ try { Assert-MockCalled -CommandName New-InvalidOperationException -Exactly 1 -Scope It } } - + Context 'Tests on Nano Server' { Mock -CommandName Test-IsNanoServer -MockWith { return $true } @@ -231,7 +231,7 @@ try { $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList @($exception, 'MachineStateIncorrect', 'InvalidOperation', $null) Mock -CommandName Find-UserByNameOnNanoServer -MockWith { Throw } - { Get-TargetResource -UserName 'DuplicateUser' } | Should Throw $errorRecord + { Get-TargetResource -UserName 'DuplicateUser' } | Should -Throw -ExpectedMessage $errorRecord Assert-MockCalled -CommandName Find-UserByNameOnNanoServer -Exactly 1 -Scope It @@ -251,17 +251,17 @@ try { It 'Should remove the user' { Mock -CommandName Find-UserByNameOnFullSku -MockWith { return $script:UserObject } - + Set-TargetResource -UserName $existingUserValues.Name ` -Ensure 'Absent' Assert-MockCalled -CommandName Add-UserOnFullSku -Exactly 0 -Scope It Assert-MockCalled -CommandName Remove-UserOnFullSku -Exactly 1 -Scope It } - + It 'Should add a new user with a password' { Mock -CommandName Find-UserByNameOnFullSku -MockWith { return $null } - + Set-TargetResource -UserName $existingUserValues.Name ` -Password $existingUserValues.Password ` -Ensure 'Present' @@ -317,7 +317,7 @@ try { $passwordNeverExpires = $false $passwordChangeRequired = $true $passwordChangeNotAllowed = $false - + Set-TargetResource -UserName $existingUserValues.Name ` -Ensure 'Present' ` -FullName $modifiableUserValues.DisplayName ` @@ -326,7 +326,7 @@ try { -PasswordNeverExpires $passwordNeverExpires ` -PasswordChangeRequired $passwordChangeRequired ` -PasswordChangeNotAllowed $passwordChangeNotAllowed - + Assert-MockCalled -CommandName Find-UserByNameOnFullSku -Exactly 1 -Scope It Assert-MockCalled -CommandName Add-UserOnFullSku -Exactly 0 -Scope It Assert-MockCalled -CommandName Remove-UserOnFullSku -Exactly 0 -Scope It @@ -348,7 +348,7 @@ try { Set-TargetResource -UserName $existingUserValues.Name ` -Ensure 'Present' - + Assert-MockCalled -CommandName Find-UserByNameOnFullSku -Exactly 1 -Scope It Assert-MockCalled -CommandName Add-UserOnFullSku -Exactly 0 -Scope It Assert-MockCalled -CommandName Remove-UserOnFullSku -Exactly 0 -Scope It @@ -369,7 +369,7 @@ try { -Ensure 'Present' ` -FullName $modifiableUserValues.DisplayName ` -Description $modifiableUserValues.Description - + Assert-MockCalled -CommandName Find-UserByNameOnFullSku -Exactly 1 -Scope It Assert-MockCalled -CommandName Add-UserOnFullSku -Exactly 0 -Scope It Assert-MockCalled -CommandName Remove-UserOnFullSku -Exactly 0 -Scope It @@ -390,7 +390,7 @@ try { -ArgumentList @($exception, 'MachineStateIncorrect', 'InvalidOperation', $null) Mock -CommandName Find-UserByNameOnFullSku -MockWith { Throw } - { Set-TargetResource -UserName 'DuplicateUser' } | Should Throw $errorRecord + { Set-TargetResource -UserName 'DuplicateUser' } | Should -Throw -ExpectedMessage $errorRecord Assert-MockCalled -CommandName Find-UserByNameOnFullSku -Exactly 1 -Scope It Assert-MockCalled -CommandName Save-UserOnFullSku -Exactly 0 -Scope It @@ -404,7 +404,7 @@ try { # Mock -CommandName Remove-LocalUser -MockWith {} # Mock -CommandName Disable-LocalUser -MockWith {} # Mock -CommandName Enable-LocalUser -MockWith {} - + It 'Should add a new user' -Skip:$true { Mock -CommandName Set-LocalUser -MockWith { $modifiableUserValues.FullName = [String]::Empty} @@ -413,7 +413,7 @@ try { Set-TargetResource -UserName $modifiableUserValues.Name ` -Ensure 'Present' - + # Set-LocalUser only called to set FullName Assert-MockCalled -CommandName Find-UserByNameOnNanoServer -Exactly 1 -Scope It Assert-MockCalled -CommandName New-LocalUser -Exactly 1 -Scope It @@ -426,7 +426,7 @@ try { It 'Should remove the user' -Skip:$true { Mock -CommandName Find-UserByNameOnNanoServer -MockWith { return $script:UserObject } Mock -CommandName Set-LocalUser -MockWith {} - + Set-TargetResource -UserName $existingUserValues.Name ` -Ensure 'Absent' @@ -440,7 +440,7 @@ try { Mock -CommandName Find-UserByNameOnNanoServer ` -MockWith { Write-Error -Message 'Test error message' -ErrorId 'UserNotFound' } Mock -CommandName Set-LocalUser -MockWith {} - + Set-TargetResource -UserName 'NotAUserName' ` -Ensure 'Absent' @@ -463,7 +463,7 @@ try { -PasswordNeverExpires (-not $existingUserValues.PasswordNeverExpires) ` -PasswordChangeRequired (-not $existingUserValues.PasswordChangeRequired) ` -PasswordChangeNotAllowed $existingUserValues.UserMayChangePassword - + <# Set-LocalUser called to: Set the Password Change the FullName @@ -480,7 +480,7 @@ try { Assert-MockCalled -CommandName Enable-LocalUser -Exactly 0 -Scope It } - + It 'Should update the user with different values' -Skip:$true { Mock -CommandName Find-UserByNameOnNanoServer -MockWith { return $modifiableUserValues } $modifiableUserValues.FullName = 'new full name' @@ -518,7 +518,7 @@ try { Set-TargetResource -UserName $existingUserValues.Name ` -Ensure 'Present' - + Assert-MockCalled -CommandName Find-UserByNameOnNanoServer -Exactly 1 -Scope It Assert-MockCalled -CommandName New-LocalUser -Exactly 0 -Scope It Assert-MockCalled -CommandName Remove-LocalUser -Exactly 0 -Scope It @@ -555,7 +555,7 @@ try { -ArgumentList @($exception, 'MachineStateIncorrect', 'InvalidOperation', $null) Mock -CommandName Find-UserByNameOnNanoServer -MockWith { Throw } - { Set-TargetResource -UserName 'DuplicateUser' } | Should Throw $errorRecord + { Set-TargetResource -UserName 'DuplicateUser' } | Should -Throw -ExpectedMessage $errorRecord Assert-MockCalled -CommandName Find-UserByNameOnNanoServer -Exactly 1 -Scope It Assert-MockCalled -CommandName New-LocalUser -Exactly 0 -Scope It @@ -584,71 +584,71 @@ try { -Disabled (-not $existingUserValues.Enabled) ` -PasswordNeverExpires $existingUserValues.PasswordNeverExpires ` -PasswordChangeNotAllowed $existingUserValues.UserCanNotChangePassword - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue Assert-MockCalled -CommandName Find-UserByNameOnFullSku -Exactly 1 -Scope It Assert-MockCalled -CommandName Test-UserPasswordOnFullSku -Exactly 1 -Scope It } - + It 'Should return true when user Absent and Ensure = Absent' { $testTargetResourceResult = Test-TargetResource -UserName $absentUserName ` -Ensure 'Absent' - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return false when user Absent and Ensure = Present' { $testTargetResourceResult = Test-TargetResource -UserName $absentUserName ` -Ensure 'Present' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when user Present and Ensure = Absent' { $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -Ensure 'Absent' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when Password is wrong' { Mock -CommandName Test-UserPasswordOnFullSku -MockWith { return $false } - + $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -Password $newUserValues.Password - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Find-UserByNameOnFullSku -Exactly 1 -Scope It Assert-MockCalled -CommandName Test-UserPasswordOnFullSku -Exactly 1 -Scope It } - + It 'Should return false when user Present and wrong Description' { $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -Description 'Wrong description' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should return false when FullName is incorrect' { $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -FullName 'Wrong FullName' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when Disabled is incorrect' { $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -Disabled $existingUserValues.Enabled - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when PasswordNeverExpires is incorrect' { $testTargetResourceResult = Test-TargetResource ` -UserName $existingUserName ` -PasswordNeverExpires (-not $existingUserValues.PasswordNeverExpires) - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when PasswordChangeNotAllowed is incorrect' { $testTargetResourceResult = Test-TargetResource ` -UserName $existingUserName ` -PasswordChangeNotAllowed $existingUserValues.UserMayChangePassword - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } } @@ -663,81 +663,81 @@ try { $duplicateUserName = 'DuplicateUserName' Mock -CommandName Find-UserByNameOnNanoServer -MockWith { Throw } ` -ParameterFilter { $UserName -eq $duplicateUserName } - + It 'Should return true when user Present and correct values' { Mock -CommandName Test-CredentialsValidOnNanoServer { return $true } - + $testTargetResourceResult = Test-TargetResource -UserName $existingUserValues.Name ` -Description $existingUserValues.Description ` -Password $existingUserValues.Password ` -Disabled (-not $existingUserValues.Enabled) ` -PasswordNeverExpires $existingUserValues.PasswordNeverExpires ` -PasswordChangeNotAllowed $existingUserValues.UserCanNotChangePassword - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue Assert-MockCalled -CommandName Find-UserByNameOnNanoServer -Exactly 1 -Scope It Assert-MockCalled -CommandName Test-CredentialsValidOnNanoServer -Exactly 1 -Scope It } - + It 'Should return true when user Absent and Ensure = Absent' { $testTargetResourceResult = Test-TargetResource -UserName $absentUserName ` -Ensure 'Absent' - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } It 'Should return false when user Absent and Ensure = Present' { $testTargetResourceResult = Test-TargetResource -UserName $absentUserName ` -Ensure 'Present' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when user Present and Ensure = Absent' { $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -Ensure 'Absent' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when Password is wrong' { Mock -CommandName Test-CredentialsValidOnNanoServer { return $false } - + $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -Password $newUserValues.Password - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Find-UserByNameOnNanoServer -Exactly 1 -Scope It Assert-MockCalled -CommandName Test-CredentialsValidOnNanoServer -Exactly 1 -Scope It } - + It 'Should return false when user Present and wrong Description' { $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -Description 'Wrong description' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should return false when FullName is incorrect' { $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -FullName 'Wrong FullName' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when Disabled is incorrect' { $testTargetResourceResult = Test-TargetResource -UserName $existingUserName ` -Disabled $existingUserValues.Enabled - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when PasswordNeverExpires is incorrect' { $testTargetResourceResult = Test-TargetResource ` -UserName $existingUserName ` -PasswordNeverExpires (-not $existingUserValues.PasswordNeverExpires) - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return false when PasswordChangeNotAllowed is incorrect' { $testTargetResourceResult = Test-TargetResource ` -UserName $existingUserName ` -PasswordChangeNotAllowed $existingUserValues.UserMayChangePassword - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } It 'Should throw an Invalid Operation exception when there are multiple users with the given name' { @@ -746,7 +746,7 @@ try { $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord ` -ArgumentList @($exception, 'MachineStateIncorrect', 'InvalidOperation', $null) - { Test-TargetResource -UserName $duplicateUserName } | Should Throw $errorRecord + { Test-TargetResource -UserName $duplicateUserName } | Should -Throw -ExpectedMessage $errorRecord Assert-MockCalled -CommandName Find-UserByNameOnNanoServer -Exactly 1 -Scope It } @@ -757,7 +757,7 @@ try { It 'Should not throw when username contains all valid chars' { { Assert-UserNameValid -UserName 'abc123456!f_t-l098s' } | Should Not Throw } - + It 'Should throw InvalidArgumentError when username contains only whitespace and dots' { $invalidName = ' . .. . ' $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument @@ -765,9 +765,9 @@ try { $errorMessage = "The name $invalidName cannot be used." $exception = New-Object System.ArgumentException $errorMessage; $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $null - { Assert-UserNameValid -UserName $invalidName } | Should Throw $errorRecord + { Assert-UserNameValid -UserName $invalidName } | Should -Throw -ExpectedMessage $errorRecord } - + It 'Should throw InvalidArgumentError when username contains an invalid char' { $invalidName = 'user|name' $errorCategory = [System.Management.Automation.ErrorCategory]::InvalidArgument @@ -775,7 +775,7 @@ try { $errorMessage = "The name $invalidName cannot be used." $exception = New-Object System.ArgumentException $errorMessage; $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $null - { Assert-UserNameValid -UserName $invalidName } | Should Throw $errorRecord + { Assert-UserNameValid -UserName $invalidName } | Should -Throw -ExpectedMessage $errorRecord } } } diff --git a/Tests/Unit/MSFT_WindowsFeature.Tests.ps1 b/Tests/Unit/MSFT_WindowsFeature.Tests.ps1 index 5f47aa2..b2eddf0 100644 --- a/Tests/Unit/MSFT_WindowsFeature.Tests.ps1 +++ b/Tests/Unit/MSFT_WindowsFeature.Tests.ps1 @@ -29,19 +29,19 @@ try $testSubFeatureName3 = 'SubTest3' $mockWindowsFeatures = @{ - Test1 = @{ + Test1 = @{ Name = 'Test1' DisplayName = 'Test Feature 1' Description = 'Test Feature with 3 subfeatures' - Installed = $false - InstallState = 'Available' + Installed = $false + InstallState = 'Available' FeatureType = 'Role Service' Path = 'Test1' Depth = 1 DependsOn = @() Parent = '' ServerComponentDescriptor = 'ServerComponent_Test_Cert_Authority' - Subfeatures = @('SubTest1','SubTest2','SubTest3') + Subfeatures = @('SubTest1', 'SubTest2', 'SubTest3') SystemService = @() Notification = @() BestPracticesModelId = $null @@ -50,7 +50,7 @@ try AdditionalInfo = @('MajorVersion', 'MinorVersion', 'NumericId', 'InstallName') } - SubTest1 = @{ + SubTest1 = @{ Name = 'SubTest1' DisplayName = 'Sub Test Feature 1' Description = 'Sub Test Feature with parent as test1' @@ -71,7 +71,7 @@ try AdditionalInfo = @('MajorVersion', 'MinorVersion', 'NumericId', 'InstallName') } - SubTest2 = @{ + SubTest2 = @{ Name = 'SubTest2' DisplayName = 'Sub Test Feature 2' Description = 'Sub Test Feature with parent as test1' @@ -113,12 +113,12 @@ try AdditionalInfo = @('MajorVersion', 'MinorVersion', 'NumericId', 'InstallName') } - Test2 = @{ + Test2 = @{ Name = 'Test2' DisplayName = 'Test Feature 2' Description = 'Test Feature with 0 subfeatures' - Installed = $true - InstallState = 'Available' + Installed = $true + InstallState = 'Available' FeatureType = 'Role Service' Path = 'Test2' Depth = 1 @@ -143,7 +143,7 @@ try $windowsFeature = $mockWindowsFeatures[$testWindowsFeatureName2] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -151,7 +151,7 @@ try $windowsFeature = $mockWindowsFeatures[$testWindowsFeatureName1] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -159,7 +159,7 @@ try $windowsFeature = $mockWindowsFeatures[$testSubFeatureName1] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -167,7 +167,7 @@ try $windowsFeature = $mockWindowsFeatures[$testSubFeatureName2] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -175,48 +175,48 @@ try $windowsFeature = $mockWindowsFeatures[$testSubFeatureName3] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } - + Context 'Windows Feature exists with no sub features' { - + It 'Should return the correct hashtable when not on a 2008 Server' { Mock -CommandName Test-IsWinServer2008R2SP1 -MockWith { return $false } $getTargetResourceResult = Get-TargetResource -Name $testWindowsFeatureName2 - $getTargetResourceResult.Name | Should Be $testWindowsFeatureName2 - $getTargetResourceResult.DisplayName | Should Be $mockWindowsFeatures[$testWindowsFeatureName2].DisplayName - $getTargetResourceResult.Ensure | Should Be 'Present' - $getTargetResourceResult.IncludeAllSubFeature | Should Be $false + $getTargetResourceResult.Name | Should -Be $testWindowsFeatureName2 + $getTargetResourceResult.DisplayName | Should -Be $mockWindowsFeatures[$testWindowsFeatureName2].DisplayName + $getTargetResourceResult.Ensure | Should -Be 'Present' + $getTargetResourceResult.IncludeAllSubFeature | Should -BeFalse } It 'Should return the correct hashtable when on a 2008 Server' { Mock -CommandName Test-IsWinServer2008R2SP1 -MockWith { return $true } $getTargetResourceResult = Get-TargetResource -Name $testWindowsFeatureName2 - $getTargetResourceResult.Name | Should Be $testWindowsFeatureName2 - $getTargetResourceResult.DisplayName | Should Be $mockWindowsFeatures[$testWindowsFeatureName2].DisplayName - $getTargetResourceResult.Ensure | Should Be 'Present' - $getTargetResourceResult.IncludeAllSubFeature | Should Be $false + $getTargetResourceResult.Name | Should -Be $testWindowsFeatureName2 + $getTargetResourceResult.DisplayName | Should -Be $mockWindowsFeatures[$testWindowsFeatureName2].DisplayName + $getTargetResourceResult.Ensure | Should -Be 'Present' + $getTargetResourceResult.IncludeAllSubFeature | Should -BeFalse } It 'Should return the correct hashtable when on a 2008 Server and Credential is passed' { Mock -CommandName Test-IsWinServer2008R2SP1 -MockWith { return $true } - Mock -CommandName Invoke-Command -MockWith { + Mock -CommandName Invoke-Command -MockWith { $windowsFeature = $mockWindowsFeatures[$testWindowsFeatureName2] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return $windowsFeatureObject } $getTargetResourceResult = Get-TargetResource -Name $testWindowsFeatureName2 -Credential $testCredential - $getTargetResourceResult.Name | Should Be $testWindowsFeatureName2 - $getTargetResourceResult.DisplayName | Should Be $mockWindowsFeatures[$testWindowsFeatureName2].DisplayName - $getTargetResourceResult.Ensure | Should Be 'Present' - $getTargetResourceResult.IncludeAllSubFeature | Should Be $false + $getTargetResourceResult.Name | Should -Be $testWindowsFeatureName2 + $getTargetResourceResult.DisplayName | Should -Be $mockWindowsFeatures[$testWindowsFeatureName2].DisplayName + $getTargetResourceResult.Ensure | Should -Be 'Present' + $getTargetResourceResult.IncludeAllSubFeature | Should -BeFalse Assert-MockCalled -CommandName Invoke-Command -Times 1 -Exactly -Scope It } @@ -228,10 +228,10 @@ try Mock -CommandName Test-IsWinServer2008R2SP1 -MockWith { return $false } $getTargetResourceResult = Get-TargetResource -Name $testWindowsFeatureName1 - $getTargetResourceResult.Name | Should Be $testWindowsFeatureName1 - $getTargetResourceResult.DisplayName | Should Be $mockWindowsFeatures[$testWindowsFeatureName1].DisplayName - $getTargetResourceResult.Ensure | Should Be 'Absent' - $getTargetResourceResult.IncludeAllSubFeature | Should Be $true + $getTargetResourceResult.Name | Should -Be $testWindowsFeatureName1 + $getTargetResourceResult.DisplayName | Should -Be $mockWindowsFeatures[$testWindowsFeatureName1].DisplayName + $getTargetResourceResult.Ensure | Should -Be 'Absent' + $getTargetResourceResult.IncludeAllSubFeature | Should -BeTrue Assert-MockCalled -CommandName Test-IsWinServer2008R2SP1 -Times 1 -Exactly -Scope It } @@ -241,10 +241,10 @@ try $mockWindowsFeatures[$testSubFeatureName3].Installed = $false $getTargetResourceResult = Get-TargetResource -Name $testWindowsFeatureName1 - $getTargetResourceResult.Name | Should Be $testWindowsFeatureName1 - $getTargetResourceResult.DisplayName | Should Be $mockWindowsFeatures[$testWindowsFeatureName1].DisplayName - $getTargetResourceResult.Ensure | Should Be 'Absent' - $getTargetResourceResult.IncludeAllSubFeature | Should Be $false + $getTargetResourceResult.Name | Should -Be $testWindowsFeatureName1 + $getTargetResourceResult.DisplayName | Should -Be $mockWindowsFeatures[$testWindowsFeatureName1].DisplayName + $getTargetResourceResult.Ensure | Should -Be 'Absent' + $getTargetResourceResult.IncludeAllSubFeature | Should -BeFalse Assert-MockCalled -CommandName Test-IsWinServer2008R2SP1 -Times 1 -Exactly -Scope It @@ -257,11 +257,11 @@ try It 'Should throw invalid operation exception' { Mock -CommandName Test-IsWinServer2008R2SP1 -MockWith { return $false } $invalidName = 'InvalidFeature' - { Get-TargetResource -Name $invalidName } | Should Throw ($script:localizedData.FeatureNotFoundError -f $invalidName) + { Get-TargetResource -Name $invalidName } | Should -Throw ($script:localizedData.FeatureNotFoundError -f $invalidName) } } } - + Describe 'WindowsFeature/Set-TargetResource' { Mock -CommandName Import-ServerManager -MockWith {} @@ -277,7 +277,7 @@ try } $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return $windowsFeatureObject } @@ -290,17 +290,17 @@ try } $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return $windowsFeatureObject } It 'Should call Add-WindowsFeature when Ensure set to Present' { - { Set-TargetResource -Name $testWindowsFeatureName2 -Ensure 'Present' } | Should Not Throw + { Set-TargetResource -Name $testWindowsFeatureName2 -Ensure 'Present' } | Should -Not -Throw Assert-MockCalled -CommandName Add-WindowsFeature -Times 1 -Exactly -Scope It } It 'Should call Remove-WindowsFeature when Ensure set to Absent' { - { Set-TargetResource -Name $testWindowsFeatureName2 -Ensure 'Absent' } | Should Not Throw + { Set-TargetResource -Name $testWindowsFeatureName2 -Ensure 'Absent' } | Should -Not -Throw Assert-MockCalled -CommandName Remove-WindowsFeature -Times 1 -Exactly -Scope It } @@ -318,7 +318,7 @@ try } $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return $windowsFeatureObject } @@ -331,18 +331,18 @@ try } $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return $windowsFeatureObject } It 'Should throw invalid operation exception when Ensure set to Present' { - { Set-TargetResource -Name $testWindowsFeatureName2 -Ensure 'Present' } | + { Set-TargetResource -Name $testWindowsFeatureName2 -Ensure 'Present' } | Should Throw ($script:localizedData.FeatureInstallationFailureError -f $testWindowsFeatureName2) Assert-MockCalled -CommandName Add-WindowsFeature -Times 1 -Exactly -Scope It } It 'Should throw invalid operation exception when Ensure set to Absent' { - { Set-TargetResource -Name $testWindowsFeatureName2 -Ensure 'Absent' } | + { Set-TargetResource -Name $testWindowsFeatureName2 -Ensure 'Absent' } | Should Throw ($script:localizedData.FeatureUninstallationFailureError -f $testWindowsFeatureName2) Assert-MockCalled -CommandName Remove-WindowsFeature -Times 1 -Exactly -Scope It } @@ -361,7 +361,7 @@ try } $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return $windowsFeatureObject } @@ -370,22 +370,22 @@ try It 'Should install the feature when Ensure set to Present and Credential passed in' { - { + { Set-TargetResource -Name $testWindowsFeatureName2 ` -Ensure 'Present' ` -Credential $testCredential - } | Should Not Throw + } | Should -Not -Throw Assert-MockCalled -CommandName Invoke-Command -Times 1 -Exactly -Scope It Assert-MockCalled -CommandName Add-WindowsFeature -Times 0 -Scope It } It 'Should uninstall the feature when Ensure set to Absent and Credential passed in' { - { + { Set-TargetResource -Name $testWindowsFeatureName2 ` -Ensure 'Absent' ` -Credential $testCredential - } | Should Not Throw + } | Should -Not -Throw Assert-MockCalled -CommandName Invoke-Command -Times 1 -Exactly -Scope It Assert-MockCalled -CommandName Remove-WindowsFeature -Times 0 -Scope It } @@ -399,7 +399,7 @@ try $windowsFeature = $mockWindowsFeatures[$testWindowsFeatureName1] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -407,7 +407,7 @@ try $windowsFeature = $mockWindowsFeatures[$testSubFeatureName1] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -415,7 +415,7 @@ try $windowsFeature = $mockWindowsFeatures[$testSubFeatureName2] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -423,7 +423,7 @@ try $windowsFeature = $mockWindowsFeatures[$testSubFeatureName3] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -432,7 +432,7 @@ try $windowsFeature = $mockWindowsFeatures[$testWindowsFeatureName1] $windowsFeatureObject = New-Object -TypeName PSObject -Property $windowsFeature $windowsFeatureObject.PSTypeNames[0] = 'Microsoft.Windows.ServerManager.Commands.Feature' - + return @($windowsFeatureObject) } @@ -444,7 +444,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Absent' ` -IncludeAllSubFeature $false - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue Assert-MockCalled -CommandName Get-WindowsFeature -Times 1 -Exactly -Scope It } @@ -455,7 +455,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Present' ` -IncludeAllSubFeature $false - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue Assert-MockCalled -CommandName Get-WindowsFeature -Times 1 -Exactly -Scope It $mockWindowsFeatures[$testWindowsFeatureName1].Installed = $false } @@ -467,7 +467,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Present' ` -IncludeAllSubFeature $true - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue Assert-MockCalled -CommandName Get-WindowsFeature -Times 4 -Exactly -Scope It $mockWindowsFeatures[$testWindowsFeatureName1].Installed = $false } @@ -479,7 +479,7 @@ try -Ensure 'Absent' ` -IncludeAllSubFeature $false ` -Credential $testCredential - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue Assert-MockCalled -CommandName Invoke-Command -Times 1 -Exactly -Scope It } } @@ -491,7 +491,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Present' ` -IncludeAllSubFeature $false - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Get-WindowsFeature -Times 1 -Exactly -Scope It } @@ -500,7 +500,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Absent' ` -IncludeAllSubFeature $false - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Get-WindowsFeature -Times 1 -Exactly -Scope It $mockWindowsFeatures[$testWindowsFeatureName1].Installed = $false } @@ -509,7 +509,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Present' ` -IncludeAllSubFeature $true - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Get-WindowsFeature -Times 1 -Exactly -Scope It } @@ -517,7 +517,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Absent' ` -IncludeAllSubFeature $true - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Get-WindowsFeature -Times 2 -Exactly -Scope It } @@ -526,7 +526,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Absent' ` -IncludeAllSubFeature $true - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Get-WindowsFeature -Times 1 -Exactly -Scope It $mockWindowsFeatures[$testWindowsFeatureName1].Installed = $false } @@ -537,7 +537,7 @@ try $testTargetResourceResult = Test-TargetResource -Name $testWindowsFeatureName1 ` -Ensure 'Present' ` -IncludeAllSubFeature $true - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Get-WindowsFeature -Times 3 -Exactly -Scope It $mockWindowsFeatures[$testWindowsFeatureName1].Installed = $false $mockWindowsFeatures[$testSubFeatureName2].Installed = $true @@ -550,23 +550,23 @@ try -Ensure 'Present' ` -IncludeAllSubFeature $false ` -Credential $testCredential - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse Assert-MockCalled -CommandName Invoke-Command -Times 1 -Exactly -Scope It } } } - Describe 'WindowsFeature/Assert-SingleFeatureExists' { + Describe 'WindowsFeature/Assert-SingleInstanceOfFeature' { $multipleFeature = @(@{Name = 'MultiFeatureName'}, @{ Name = 'MultiFeatureName' }) It 'Should throw invalid operation when feature equals null' { $nonexistentName = 'NonexistentFeatureName' - { Assert-SingleFeatureExists -Feature $null -Name $nonexistentName } | + { Assert-SingleInstanceOfFeature -Feature $null -Name $nonexistentName } | Should Throw ($script:localizedData.FeatureNotFoundError -f $nonexistentName) } It 'Should throw invalid operation when there are multiple features with the given name' { - { Assert-SingleFeatureExists -Feature $multipleFeature -Name $multipleFeature[0].Name } | + { Assert-SingleInstanceOfFeature -Feature $multipleFeature -Name $multipleFeature[0].Name } | Should Throw ($script:localizedData.MultipleFeatureInstancesError -f $multipleFeature.Name) } } @@ -581,27 +581,27 @@ try It 'Should Not Throw' { Mock -CommandName Import-Module -MockWith {} - { Import-ServerManager } | Should Not Throw + { Import-ServerManager } | Should -Not -Throw } It 'Should not throw when exception is Identity Reference Runtime Exception' { $mockIdentityReferenceRuntimeException = New-Object -TypeName System.Management.Automation.RuntimeException -ArgumentList 'Some or all identity references could not be translated' Mock -CommandName Import-Module -MockWith { Throw $mockIdentityReferenceRuntimeException } - { Import-ServerManager } | Should Not Throw + { Import-ServerManager } | Should -Not -Throw } - + It 'Should throw invalid operation exception when exception is not Identity Reference Runtime Exception' { $mockOtherRuntimeException = New-Object -TypeName System.Management.Automation.RuntimeException -ArgumentList 'Other error' Mock -CommandName Import-Module -MockWith { Throw $mockOtherRuntimeException } - { Import-ServerManager } | Should Throw ($script:localizedData.SkuNotSupported) + { Import-ServerManager } | Should -Throw ($script:localizedData.SkuNotSupported) } It 'Should throw invalid operation exception' { Mock -CommandName Import-Module -MockWith { Throw } - { Import-ServerManager } | Should Throw ($script:localizedData.SkuNotSupported) + { Import-ServerManager } | Should -Throw ($script:localizedData.SkuNotSupported) } } } diff --git a/Tests/Unit/MSFT_WindowsOptionalFeature.Tests.ps1 b/Tests/Unit/MSFT_WindowsOptionalFeature.Tests.ps1 index dfef510..2777539 100644 --- a/Tests/Unit/MSFT_WindowsOptionalFeature.Tests.ps1 +++ b/Tests/Unit/MSFT_WindowsOptionalFeature.Tests.ps1 @@ -19,12 +19,12 @@ try $script:testFeatureName = 'TestFeature' - $script:fakeEnabledFeature = [PSCustomObject] @{ + $script:fakeEnabledFeature = [System.Management.Automation.PSObject] @{ Name = $testFeatureName State = 'Enabled' } - $script:fakeDisabledFeature = [PSCustomObject] @{ + $script:fakeDisabledFeature = [System.Management.Automation.PSObject] @{ Name = $testFeatureName State = 'Disabled' } @@ -32,7 +32,7 @@ try <# This context block needs to stay at the top because of a bug in Pester on Nano server. - + Assert-ResourcePrerequisitesValid is mocked in most of the other contexts blocks. This causes errors to throw from the script blocks in this context since this function does not take any parameters, but Pester tries to pipe something into it. @@ -41,58 +41,58 @@ try #> Context 'Assert-ResourcePrerequisitesValid' { $fakeWin32OSObjects = @{ - '7' = [PSCustomObject] @{ + '7' = [System.Management.Automation.PSObject] @{ ProductType = 1 BuildNumber = 7601 } - 'Server2008R2' = [PSCustomObject] @{ + 'Server2008R2' = [System.Management.Automation.PSObject] @{ ProductType = 2 BuildNumber = 7601 } - 'Server2012' = [PSCustomObject] @{ + 'Server2012' = [System.Management.Automation.PSObject] @{ ProductType = 2 BuildNumber = 9200 } - '8.1' = [PSCustomObject] @{ + '8.1' = [System.Management.Automation.PSObject] @{ ProductType = 1 BuildNumber = 9600 } - 'Server2012R2' = [PSCustomObject] @{ + 'Server2012R2' = [System.Management.Automation.PSObject] @{ ProductType = 2 BuildNumber = 9600 } } - + It 'Should throw when the DISM module is not available' { - Mock Import-Module -ParameterFilter { $Name -eq 'Dism' } -MockWith { Write-Error 'Cannot find module' } - { Assert-ResourcePrerequisitesValid } | Should Throw $script:localizedData.DismNotAvailable + Mock -CommandName Import-Module -ParameterFilter { $Name -eq 'Dism' } -MockWith { Write-Error 'Cannot find module' } + { Assert-ResourcePrerequisitesValid } | Should -Throw -ExpectedMessage $script:localizedData.DismNotAvailable } - Mock Import-Module -ParameterFilter { $Name -eq 'Dism' } -MockWith { } + Mock -CommandName Import-Module -ParameterFilter { $Name -eq 'Dism' } -MockWith { } It 'Should throw when operating system is Server 2008 R2' { Mock Get-CimInstance -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' } -MockWith { return $fakeWin32OSObjects['Server2008R2'] } - { Assert-ResourcePrerequisitesValid } | Should Throw $script:localizedData.NotSupportedSku + { Assert-ResourcePrerequisitesValid } | Should -Throw -ExpectedMessage $script:localizedData.NotSupportedSku } It 'Should throw when operating system is Server 2012' { Mock Get-CimInstance -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' } -MockWith { return $fakeWin32OSObjects['Server2012'] } - { Assert-ResourcePrerequisitesValid } | Should Throw $script:localizedData.NotSupportedSku + { Assert-ResourcePrerequisitesValid } | Should -Throw -ExpectedMessage $script:localizedData.NotSupportedSku } It 'Should not throw when operating system is Windows 7' { Mock Get-CimInstance -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' } -MockWith { return $fakeWin32OSObjects['7'] } - { Assert-ResourcePrerequisitesValid } | Should Not Throw + { Assert-ResourcePrerequisitesValid } | Should -Not -Throw } It 'Should not throw when operating system is Windows 8.1' { Mock Get-CimInstance -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' } -MockWith { return $fakeWin32OSObjects['8.1'] } - { Assert-ResourcePrerequisitesValid } | Should Not Throw + { Assert-ResourcePrerequisitesValid } | Should -Not -Throw } It 'Should not throw when operating system is Server 2012 R2' { Mock Get-CimInstance -ParameterFilter { $ClassName -eq 'Win32_OperatingSystem' } -MockWith { return $fakeWin32OSObjects['Server2012R2'] } - { Assert-ResourcePrerequisitesValid } | Should Not Throw + { Assert-ResourcePrerequisitesValid } | Should -Not -Throw } } @@ -102,7 +102,7 @@ try It 'Should return a Hashtable' { $getTargetResourceResult = Get-TargetResource -Name $script:testFeatureName - $getTargetResourceResult -is [System.Collections.Hashtable] | Should Be $true + $getTargetResourceResult -is [System.Collections.Hashtable] | Should -BeTrue } It 'Should call Assert-ResourcePrerequisitesValid with the feature name' { @@ -112,18 +112,18 @@ try It 'Should return Ensure as Present' { $getTargetResourceResult = Get-TargetResource -Name $script:testFeatureName - $getTargetResourceResult.Ensure | Should Be 'Present' + $getTargetResourceResult.Ensure | Should -Be 'Present' } } - + Context 'Get-TargetResource - Feature Disabled' { Mock Assert-ResourcePrerequisitesValid -MockWith { } Mock Dism\Get-WindowsOptionalFeature { $FeatureName -eq $script:testFeatureName } -MockWith { return $script:fakeDisabledFeature } It 'Should return Ensure as Absent' { $getTargetResourceResult = Get-TargetResource -Name $script:testFeatureName - $getTargetResourceResult.Ensure | Should Be 'Absent' + $getTargetResourceResult.Ensure | Should -Be 'Absent' } } @@ -132,11 +132,11 @@ try Mock Dism\Get-WindowsOptionalFeature { $FeatureName -eq $script:testFeatureName } -MockWith { return $script:fakeEnabledFeature } It 'Should return true when Ensure set to Present' { - Test-TargetResource -Name $testFeatureName -Ensure 'Present' | Should Be $true + Test-TargetResource -Name $testFeatureName -Ensure 'Present' | Should -BeTrue } It 'Should return false when Ensure set to Absent' { - Test-TargetResource -Name $testFeatureName -Ensure 'Absent' | Should Be $false + Test-TargetResource -Name $testFeatureName -Ensure 'Absent' | Should -BeFalse } } @@ -146,11 +146,11 @@ try Mock Dism\Get-WindowsOptionalFeature { $FeatureName -eq $script:testFeatureName } -MockWith { return $script:fakeDisabledFeature } It 'Should return false when Ensure set to Present' { - Test-TargetResource -Name $testFeatureName -Ensure 'Present' | Should Be $false + Test-TargetResource -Name $testFeatureName -Ensure 'Present' | Should -BeFalse } It 'Should return true when Ensure set to Absent' { - Test-TargetResource -Name $testFeatureName -Ensure 'Absent' | Should Be $true + Test-TargetResource -Name $testFeatureName -Ensure 'Absent' | Should -BeTrue } } @@ -159,11 +159,11 @@ try Mock Dism\Get-WindowsOptionalFeature { $FeatureName -eq $script:testFeatureName } -MockWith { } It 'Should return false when Ensure set to Present' { - Test-TargetResource -Name $testFeatureName -Ensure 'Present' | Should Be $false + Test-TargetResource -Name $testFeatureName -Ensure 'Present' | Should -BeFalse } It 'Should return true when Ensure set to Absent' { - Test-TargetResource -Name $testFeatureName -Ensure 'Absent' | Should Be $true + Test-TargetResource -Name $testFeatureName -Ensure 'Absent' | Should -BeTrue } } @@ -172,9 +172,9 @@ try It 'Should call Enable-WindowsOptionalFeature with NoRestart set to true by default when Ensure set to Present' { Mock Dism\Enable-WindowsOptionalFeature -ParameterFilter { $NoRestart -eq $true } -MockWith { } - + Set-TargetResource -Name $script:testFeatureName - + Assert-MockCalled Dism\Enable-WindowsOptionalFeature -ParameterFilter { $NoRestart -eq $true } -Scope It } @@ -262,11 +262,11 @@ try Context 'Convert-FeatureStateToEnsure' { It 'Should return Present when state is Enabled' { - Convert-FeatureStateToEnsure -State 'Enabled' | Should Be 'Present' + Convert-FeatureStateToEnsure -State 'Enabled' | Should -Be 'Present' } It 'Should return Absent when state is Disabled' { - Convert-FeatureStateToEnsure -State 'Disabled' | Should Be 'Absent' + Convert-FeatureStateToEnsure -State 'Disabled' | Should -Be 'Absent' } It 'Should return the same state when state is not Enabled or Disabled' { @@ -275,7 +275,7 @@ try try { - Convert-FeatureStateToEnsure -State 'UnknownState' | Should Be 'UnknownState' + Convert-FeatureStateToEnsure -State 'UnknownState' | Should -Be 'UnknownState' } finally { @@ -285,18 +285,18 @@ try } Context 'Convert-CustomPropertyArrayToStringArray' { - [PSCustomObject[]] $psCustomObjects = @( - [PSCustomObject] @{ + [System.Management.Automation.PSObject[]] $psCustomObjects = @( + [System.Management.Automation.PSObject] @{ Name = 'Object 1' Value = 'Value 1' Path = 'Path 1' }, - [PSCustomObject] @{ + [System.Management.Automation.PSObject] @{ Name = 'Object 2' Value = 'Value 2' Path = 'Path 2' }, - [PSCustomObject] @{ + [System.Management.Automation.PSObject] @{ Name = 'Object 3' Value = 'Value 3' Path = 'Path 3' @@ -306,15 +306,15 @@ try It 'Should return 3 strings from 3 PSCustomObjects and a null object' { $propertiesAsStrings = Convert-CustomPropertyArrayToStringArray -CustomProperties $psCustomObjects - $propertiesAsStrings.Length | Should Be 3 + $propertiesAsStrings.Length | Should -Be 3 } It 'Should return the correct string for each object' { $propertiesAsStrings = Convert-CustomPropertyArrayToStringArray -CustomProperties $psCustomObjects - + foreach ($objectNumber in @(1, 2, 3)) { - $propertiesAsStrings.Contains("Name = Object $objectNumber, Value = Value $objectNumber, Path = Path $objectNumber") | Should Be $true + $propertiesAsStrings.Contains("Name = Object $objectNumber, Value = Value $objectNumber, Path = Path $objectNumber") | Should -BeTrue } } } diff --git a/Tests/Unit/MSFT_WindowsPackageCab.Tests.ps1 b/Tests/Unit/MSFT_WindowsPackageCab.Tests.ps1 index 9e899f9..0c773d3 100644 --- a/Tests/Unit/MSFT_WindowsPackageCab.Tests.ps1 +++ b/Tests/Unit/MSFT_WindowsPackageCab.Tests.ps1 @@ -1,4 +1,4 @@ -$errorActionPreference = 'Stop' +$errorActionPreference = 'Stop' Set-StrictMode -Version 'Latest' $script:testFolderPath = Split-Path -Path $PSScriptRoot -Parent @@ -34,8 +34,8 @@ try It 'Should return Ensure as Absent when package is not installed' { $getTargetResourceResult = Get-TargetResource -Name $script:testPackageName @getTargetResourceCommonParams - $getTargetResourceResult.Ensure | Should Be 'Absent' - + $getTargetResourceResult.Ensure | Should -Be 'Absent' + Assert-MockCalled -CommandName 'Dism\Get-WindowsPackage' } @@ -43,17 +43,17 @@ try Mock -CommandName 'Dism\Get-WindowsPackage' -MockWith { return @{ PackageState = 'NotPresent' } } $getTargetResourceResult = Get-TargetResource -Name $script:testPackageName @getTargetResourceCommonParams - $getTargetResourceResult.Ensure | Should Be 'Absent' - + $getTargetResourceResult.Ensure | Should -Be 'Absent' + Assert-MockCalled -CommandName 'Dism\Get-WindowsPackage' } - + It 'Should return Ensure as Present when package is installed' { Mock -CommandName 'Dism\Get-WindowsPackage' -MockWith { return @{ PackageState = 'Installed' } } $getTargetResourceResult = Get-TargetResource -Name $script:testPackageName @getTargetResourceCommonParams - $getTargetResourceResult.Ensure | Should Be 'Present' - + $getTargetResourceResult.Ensure | Should -Be 'Present' + Assert-MockCalled -CommandName 'Dism\Get-WindowsPackage' } @@ -61,8 +61,8 @@ try Mock -CommandName 'Dism\Get-WindowsPackage' -MockWith { return @{ PackageState = 'InstallPending' } } $getTargetResourceResult = Get-TargetResource -Name $script:testPackageName @getTargetResourceCommonParams - $getTargetResourceResult.Ensure | Should Be 'Present' - + $getTargetResourceResult.Ensure | Should -Be 'Present' + Assert-MockCalled -CommandName 'Dism\Get-WindowsPackage' } @@ -107,24 +107,24 @@ try Mock -CommandName 'Get-TargetResource' -MockWith { return @{ Ensure = 'Absent' } } It 'Should return true when Get-TargetResource returns Ensure Absent and Ensure is set to Absent' { - Test-TargetResource -Name $script:testPackageName -SourcePath $script:testSourcePath -Ensure 'Absent' | Should Be $true + Test-TargetResource -Name $script:testPackageName -SourcePath $script:testSourcePath -Ensure 'Absent' | Should -BeTrue Assert-MockCalled -CommandName 'Get-TargetResource' } It 'Should return false when Get-TargetResource returns Ensure Absent and Ensure is set to Present' { - Test-TargetResource -Name $script:testPackageName -SourcePath $script:testSourcePath -Ensure 'Present' | Should Be $false + Test-TargetResource -Name $script:testPackageName -SourcePath $script:testSourcePath -Ensure 'Present' | Should -BeFalse Assert-MockCalled -CommandName 'Get-TargetResource' } Mock -CommandName 'Get-TargetResource' -MockWith { return @{ Ensure = 'Present' } } It 'Should return true when Get-TargetResource returns Ensure Present and Ensure is set to Present' { - Test-TargetResource -Name $script:testPackageName -SourcePath $script:testSourcePath -Ensure 'Present' | Should Be $true + Test-TargetResource -Name $script:testPackageName -SourcePath $script:testSourcePath -Ensure 'Present' | Should -BeTrue Assert-MockCalled -CommandName 'Get-TargetResource' - } + } It 'Should return false when Get-TargetResource returns Ensure Present and Ensure is set to Absent' { - Test-TargetResource -Name $script:testPackageName -SourcePath $script:testSourcePath -Ensure 'Absent' | Should Be $false + Test-TargetResource -Name $script:testPackageName -SourcePath $script:testSourcePath -Ensure 'Absent' | Should -BeFalse Assert-MockCalled -CommandName 'Get-TargetResource' } diff --git a/Tests/Unit/MSFT_WindowsProcess.Tests.ps1 b/Tests/Unit/MSFT_WindowsProcess.Tests.ps1 index 2f88da3..d555e0b 100644 --- a/Tests/Unit/MSFT_WindowsProcess.Tests.ps1 +++ b/Tests/Unit/MSFT_WindowsProcess.Tests.ps1 @@ -1,4 +1,4 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] param () $errorActionPreference = 'Stop' @@ -90,10 +90,10 @@ try Describe 'WindowsProcess\Get-TargetResource' { Mock -CommandName Expand-Path -MockWith { return $Path } - Mock -CommandName Get-ProcessCimInstance -MockWith { + Mock -CommandName Get-ProcessCimInstance -MockWith { if ($Path -eq $script:validPath1) { - return @($script:mockProcess1, $script:mockProcess3) + return @($script:mockProcess1, $script:mockProcess3) } elseif ($Path -eq $script:validPath2) { @@ -111,7 +111,7 @@ try Mock -CommandName Get-Process -MockWith { if ($ID -eq $script:mockProcess1.Id) { - return $script:mockProcess1 + return $script:mockProcess1 } elseif ($script:mockProcess2.Id) { @@ -128,67 +128,67 @@ try } Mock -CommandName New-InvalidOperationException -MockWith { Throw $script:exceptionMessage } Mock -CommandName New-InvalidArgumentException -MockWith { Throw $script:exceptionMessage } - + It 'Should return the correct properties for a process that is Absent' { $processArguments = 'TestGetProperties' - + $getTargetResourceResult = Get-TargetResource -Path $invalidPath ` -Arguments $processArguments - - $getTargetResourceResult.Arguments | Should Be $processArguments - $getTargetResourceResult.Ensure | Should Be 'Absent' - $getTargetResourceResult.Path | Should Be $invalidPath - + + $getTargetResourceResult.Arguments | Should -Be $processArguments + $getTargetResourceResult.Ensure | Should -Be 'Absent' + $getTargetResourceResult.Path | Should -Be $invalidPath + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It } - + It 'Should return the correct properties for one process with a credential' { - + $getTargetResourceResult = Get-TargetResource -Path $script:validPath2 ` -Arguments $script:mockProcess2.Arguments ` -Credential $script:testCredential - - $getTargetResourceResult.VirtualMemorySize | Should Be $script:mockProcess2.VirtualMemorySize64 - $getTargetResourceResult.Arguments | Should Be $script:mockProcess2.Arguments - $getTargetResourceResult.Ensure | Should Be 'Present' - $getTargetResourceResult.PagedMemorySize | Should Be $script:mockProcess2.PagedMemorySize64 - $getTargetResourceResult.Path | Should Be $script:mockProcess2.Path - $getTargetResourceResult.NonPagedMemorySize | Should Be $script:mockProcess2.NonpagedSystemMemorySize64 - $getTargetResourceResult.HandleCount | Should Be $script:mockProcess2.HandleCount - $getTargetResourceResult.ProcessId | Should Be $script:mockProcess2.ProcessId - + + $getTargetResourceResult.VirtualMemorySize | Should -Be $script:mockProcess2.VirtualMemorySize64 + $getTargetResourceResult.Arguments | Should -Be $script:mockProcess2.Arguments + $getTargetResourceResult.Ensure | Should -Be 'Present' + $getTargetResourceResult.PagedMemorySize | Should -Be $script:mockProcess2.PagedMemorySize64 + $getTargetResourceResult.Path | Should -Be $script:mockProcess2.Path + $getTargetResourceResult.NonPagedMemorySize | Should -Be $script:mockProcess2.NonpagedSystemMemorySize64 + $getTargetResourceResult.HandleCount | Should -Be $script:mockProcess2.HandleCount + $getTargetResourceResult.ProcessId | Should -Be $script:mockProcess2.ProcessId + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It } - + It 'Should return the correct properties when there are multiple processes' { - + $getTargetResourceResult = Get-TargetResource -Path $script:validPath1 ` -Arguments $script:mockProcess1.Arguments - - $getTargetResourceResult.VirtualMemorySize | Should Be $script:mockProcess1.VirtualMemorySize64 - $getTargetResourceResult.Arguments | Should Be $script:mockProcess1.Arguments - $getTargetResourceResult.Ensure | Should Be 'Present' - $getTargetResourceResult.PagedMemorySize | Should Be $script:mockProcess1.PagedMemorySize64 - $getTargetResourceResult.Path | Should Be $script:mockProcess1.Path - $getTargetResourceResult.NonPagedMemorySize | Should Be $script:mockProcess1.NonpagedSystemMemorySize64 - $getTargetResourceResult.HandleCount | Should Be $script:mockProcess1.HandleCount - $getTargetResourceResult.ProcessId | Should Be $script:mockProcess1.ProcessId - + + $getTargetResourceResult.VirtualMemorySize | Should -Be $script:mockProcess1.VirtualMemorySize64 + $getTargetResourceResult.Arguments | Should -Be $script:mockProcess1.Arguments + $getTargetResourceResult.Ensure | Should -Be 'Present' + $getTargetResourceResult.PagedMemorySize | Should -Be $script:mockProcess1.PagedMemorySize64 + $getTargetResourceResult.Path | Should -Be $script:mockProcess1.Path + $getTargetResourceResult.NonPagedMemorySize | Should -Be $script:mockProcess1.NonpagedSystemMemorySize64 + $getTargetResourceResult.HandleCount | Should -Be $script:mockProcess1.HandleCount + $getTargetResourceResult.ProcessId | Should -Be $script:mockProcess1.ProcessId + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It } } - + Describe 'WindowsProcess\Set-TargetResource' { Mock -CommandName Expand-Path -MockWith { return $Path } - Mock -CommandName Get-ProcessCimInstance -MockWith { + Mock -CommandName Get-ProcessCimInstance -MockWith { if ($Path -eq $script:validPath1) { - return @($script:mockProcess1, $script:mockProcess3) + return @($script:mockProcess1, $script:mockProcess3) } elseif ($Path -eq $script:validPath2) { @@ -219,54 +219,54 @@ try -Arguments $script:mockProcess1.Arguments ` -Credential $script:testCredential ` -Ensure 'Absent' - } | Should Not Throw - + } | Should -Not -Throw + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Stop-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 1 -Scope It } - + It 'Should not throw when Ensure set to Absent and processes are not running' { { Set-TargetResource -Path $script:invalidPath ` -Arguments '' ` -Ensure 'Absent' - } | Should Not Throw - + } | Should -Not -Throw + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Stop-Process -Exactly 0 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 0 -Scope It } - + It 'Should throw an invalid operation exception when Stop-Process throws an error' { { Set-TargetResource -Path $script:errorProcess.Path ` -Arguments '' ` -Ensure 'Absent' - } | Should Throw $script:exceptionMessage - + } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Stop-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName New-InvalidOperationException -Exactly 1 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 0 -Scope It } - + Mock -CommandName Wait-ProcessCount -MockWith { return $false } It 'Should throw an invalid operation exception when there is a problem waiting for the processes' { { Set-TargetResource -Path $script:validPath1 ` -Arguments $script:mockProcess1.Arguments ` -Ensure 'Absent' - } | Should Throw $script:exceptionMessage - + } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Stop-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 1 -Scope It Assert-MockCalled -CommandName New-InvalidOperationException -Exactly 1 -Scope It } - + Mock -CommandName Wait-ProcessCount -MockWith { return $true } Mock -CommandName Start-ProcessAsLocalSystemUser -MockWith {} @@ -275,15 +275,15 @@ try -Arguments $script:mockProcess1.Arguments ` -Credential $script:testCredential ` -Ensure 'Present' - } | Should Not Throw - + } | Should -Not -Throw + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Test-IsRunFromLocalSystemUser -Exactly 1 -Scope It Assert-MockCalled -CommandName Start-ProcessAsLocalSystemUser -Exactly 1 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 1 -Scope It } - + Mock -CommandName Start-ProcessAsLocalSystemUser -MockWith {} Mock -CommandName Assert-PathArgumentRooted -MockWith {} Mock -CommandName Assert-PathArgumentValid -MockWith {} @@ -294,8 +294,8 @@ try -Credential $script:testCredential ` -WorkingDirectory 'test working directory' ` -Ensure 'Present' - } | Should Throw $script:exceptionMessage - + } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Test-IsRunFromLocalSystemUser -Exactly 1 -Scope It @@ -305,7 +305,7 @@ try Assert-MockCalled -CommandName Assert-PathArgumentValid -Exactly 1 -Scope It Assert-MockCalled -CommandName New-InvalidArgumentException -Exactly 1 -Scope It } - + $testErrorRecord = 'test Start-ProcessAsLocalSystemUser error record' Mock -CommandName Start-ProcessAsLocalSystemUser -MockWith { Throw $testErrorRecord } @@ -314,29 +314,29 @@ try -Arguments $script:mockProcess1.Arguments ` -Credential $script:testCredential ` -Ensure 'Present' - } | Should Throw $testErrorRecord - + } | Should -Throw -ExpectedMessage $testErrorRecord + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Test-IsRunFromLocalSystemUser -Exactly 1 -Scope It Assert-MockCalled -CommandName Start-ProcessAsLocalSystemUser -Exactly 1 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 0 -Scope It } - + Mock -CommandName Start-Process -MockWith {} It 'Should not throw when Ensure set to Present and processes are not running and no credential passed' { { Set-TargetResource -Path $script:invalidPath ` -Arguments $script:mockProcess1.Arguments ` -Ensure 'Present' - } | Should Not Throw - + } | Should -Not -Throw + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Start-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 1 -Scope It } - + $mockStartProcessException = New-Object -TypeName 'InvalidOperationException' ` -ArgumentList @('Start-Process test exception') Mock -CommandName Start-Process -MockWith { Throw $mockStartProcessException } @@ -345,15 +345,15 @@ try { Set-TargetResource -Path $script:invalidPath ` -Arguments $script:mockProcess1.Arguments ` -Ensure 'Present' - } | Should Throw $script:exceptionMessage - + } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Start-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 0 -Scope It Assert-MockCalled -CommandName New-InvalidOperationException -Exactly 1 -Scope It } - + Mock -CommandName Wait-ProcessCount -MockWith { return $false } Mock -CommandName Start-Process -MockWith {} @@ -361,35 +361,35 @@ try { Set-TargetResource -Path $script:invalidPath ` -Arguments $script:mockProcess1.Arguments ` -Ensure 'Present' - } | Should Throw $script:exceptionMessage - + } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Start-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 1 -Scope It } - + Mock -CommandName Wait-ProcessCount -MockWith { return $true } It 'Should not throw when Ensure set to Present and processes are already running' { { Set-TargetResource -Path $script:validPath1 ` -Arguments $script:mockProcess1.Arguments ` -Ensure 'Present' - } | Should Not Throw - + } | Should -Not -Throw + Assert-MockCalled -CommandName Expand-Path -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessCimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Start-Process -Exactly 0 -Scope It Assert-MockCalled -CommandName Wait-ProcessCount -Exactly 0 -Scope It } } - + Describe 'WindowsProcess\Test-TargetResource' { Mock -CommandName Expand-Path -MockWith { return $Path } - Mock -CommandName Get-ProcessCimInstance -MockWith { + Mock -CommandName Get-ProcessCimInstance -MockWith { if ($Path -eq $script:validPath1) { - return @($script:mockProcess1, $script:mockProcess3) + return @($script:mockProcess1, $script:mockProcess3) } elseif ($Path -eq $script:validPath2) { @@ -409,87 +409,87 @@ try $testTargetResourceResult = Test-TargetResource -Path $script:validPath1 ` -Arguments $script:mockProcess1.Arguments ` -Ensure 'Present' - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } - + It 'Should return false when Ensure set to Present and process is not running' { $testTargetResourceResult = Test-TargetResource -Path $script:invalidPath ` -Arguments $script:mockProcess1.Arguments ` -Ensure 'Present' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + It 'Should return true when Ensure set to Absent and process is not running and Credential passed' { $testTargetResourceResult = Test-TargetResource -Path $script:invalidPath ` -Arguments $script:mockProcess1.Arguments ` -Credential $script:testCredential ` -Ensure 'Absent' - $testTargetResourceResult | Should Be $true + $testTargetResourceResult | Should -BeTrue } - + It 'Should return false when Ensure set to Absent and process is running' { $testTargetResourceResult = Test-TargetResource -Path $script:validPath1 ` -Arguments $script:mockProcess1.Arguments ` -Ensure 'Absent' - $testTargetResourceResult | Should Be $false + $testTargetResourceResult | Should -BeFalse } - + } - + Describe 'WindowsProcess\Expand-Path' { Mock -CommandName New-InvalidArgumentException -MockWith { Throw $script:exceptionMessage } Mock -CommandName Test-Path -MockWith { return $true } It 'Should return the original path when path is rooted' { $rootedPath = 'C:\testProcess.exe' - + $expandPathResult = Expand-Path -Path $rootedPath - $expandPathResult | Should Be $rootedPath + $expandPathResult | Should -Be $rootedPath } - + Mock -CommandName Test-Path -MockWith { return $false } It 'Should throw an invalid argument exception when Path is rooted and does not exist' { $rootedPath = 'C:\invalidProcess.exe' - - { Expand-Path -Path $rootedPath} | Should Throw $script:exceptionMessage - + + { Expand-Path -Path $rootedPath} | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName New-InvalidArgumentException -Exactly 1 -Scope It } - + It 'Should throw an invalid argument exception when Path is unrooted and does not exist' { $unrootedPath = 'invalidfile.txt' - - { Expand-Path -Path $unrootedPath} | Should Throw $script:exceptionMessage - + + { Expand-Path -Path $unrootedPath} | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName New-InvalidArgumentException -Exactly 1 -Scope It } } - + Describe 'WindowsProcess\Get-ProcessCimInstance' { Mock -CommandName Get-Process -MockWith { return @($script:mockProcess2) } Mock -CommandName Get-CimInstance -MockWith { return $script:mockProcess2 } It 'Should return the correct process when it exists and no arguments passed' { $resultProcess = Get-ProcessCimInstance -Path $script:mockProcess2.Path - $resultProcess | Should Be @($script:mockProcess2) - + $resultProcess | Should -Be @($script:mockProcess2) + Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-CimInstance -Exactly 1 -Scope It } - + Mock -CommandName Get-Process -MockWith { return @($script:mockProcess1) } Mock -CommandName Get-CimInstance -MockWith { return $script:mockProcess1 } It 'Should return the correct process when it exists and arguments are passed' { $resultProcess = Get-ProcessCimInstance -Path $script:mockProcess1.Path ` -Arguments $script:mockProcess1.Arguments - $resultProcess | Should Be @($script:mockProcess1) - + $resultProcess | Should -Be @($script:mockProcess1) + Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-CimInstance -Exactly 1 -Scope It } - + $expectedProcesses = @($script:mockProcess1, $script:mockProcess1, $script:mockProcess1) Mock -CommandName Get-Process -MockWith { return $expectedProcesses } Mock -CommandName Get-CimInstance -MockWith { return $script:mockProcess1 } @@ -498,12 +498,12 @@ try $resultProcess = Get-ProcessCimInstance -Path $script:mockProcess1.Path ` -Arguments $script:mockProcess1.Arguments - Compare-Object -ReferenceObject $expectedProcesses -DifferenceObject $resultProcess | Should Be $null - + Compare-Object -ReferenceObject $expectedProcesses -DifferenceObject $resultProcess | Should -Be $null + Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-CimInstance -Exactly 3 -Scope It } - + Mock -CommandName Get-Process -MockWith { return @($script:mockProcess2, $script:mockProcess2) } Mock -CommandName Get-CimInstance -MockWith { return @($script:mockProcess2, $script:mockProcess2) } @@ -511,12 +511,12 @@ try $resultProcess = Get-ProcessCimInstance -Path $script:mockProcess2.Path ` -Arguments $script:mockProcess2.Arguments ` -UseGetCimInstanceThreshold 1 - $resultProcess | Should Be @($script:mockProcess2, $script:mockProcess2) - + $resultProcess | Should -Be @($script:mockProcess2, $script:mockProcess2) + Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-CimInstance -Exactly 1 -Scope It } - + Mock -CommandName Get-Process -MockWith { return @($script:mockProcess2) } Mock -CommandName Get-CimInstance -MockWith { return $script:mockProcess2 } Mock -CommandName Get-ProcessOwner -MockWith { return ($env:computerName + '\' + $script:testUsername) } ` @@ -525,13 +525,13 @@ try It 'Should return the correct process when it exists and Credential is passed in' { $resultProcess = Get-ProcessCimInstance -Path $script:mockProcess2.Path ` -Credential $script:testCredential - $resultProcess | Should Be @($script:mockProcess2) - + $resultProcess | Should -Be @($script:mockProcess2) + Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-CimInstance -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-ProcessOwner -Exactly 1 -Scope It } - + Mock -CommandName Get-Process -MockWith { return @($script:mockProcess3, $script:mockProcess3, $script:mockProcess4, $script:mockProcess2) } Mock -CommandName Get-CimInstance -MockWith { return @($script:mockProcess3, $script:mockProcess3, $script:mockProcess4, $script:mockProcess2) } Mock -CommandName Get-ProcessOwner -MockWith { return ($env:computerName + '\' + $script:testUsername) } ` @@ -544,12 +544,12 @@ try -Credential $script:testCredential ` -Arguments $script:mockProcess3.Arguments ` -UseGetCimInstanceThreshold 1 - $resultProcess | Should Be @($script:mockProcess3, $script:mockProcess3) - + $resultProcess | Should -Be @($script:mockProcess3, $script:mockProcess3) + Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-CimInstance -Exactly 1 -Scope It } - + Mock -CommandName Get-ProcessOwner -MockWith { return ($env:computerName + '\' + $script:testUsername) } ` -ParameterFilter { ($Process -eq $script:mockProcess3) -or ($Process -eq $script:mockProcess2) } Mock -CommandName Get-ProcessOwner -MockWith { return ('wrongDomain' + '\' + $script:testUsername) } ` @@ -560,83 +560,83 @@ try -Credential $script:testCredential ` -Arguments $script:mockProcess3.Arguments ` -UseGetCimInstanceThreshold 1 - $resultProcess | Should Be @($script:mockProcess3, $script:mockProcess3) - + $resultProcess | Should -Be @($script:mockProcess3, $script:mockProcess3) + Assert-MockCalled -CommandName Get-Process -Exactly 1 -Scope It Assert-MockCalled -CommandName Get-CimInstance -Exactly 1 -Scope It } } - + Describe 'WindowsProcess\ConvertTo-EscapedStringForWqlFilter' { It 'Should return the same string when there are no escaped characters' { $inputString = 'testString%$.@123' $convertedString = ConvertTo-EscapedStringForWqlFilter -FilterString $inputString - $convertedString | Should Be $inputString + $convertedString | Should -Be $inputString } - + It 'Should return a string with escaped characters: ("\)' { $inputString = '\test"string"\123' $expectedString = '\\test\"string\"\\123' $convertedString = ConvertTo-EscapedStringForWqlFilter -FilterString $inputString - $convertedString | Should Be $expectedString + $convertedString | Should -Be $expectedString } - + It "Should return a string with escaped characters: ('\)" { $inputString = "\test'string'\123" $expectedString = "\\test\'string\'\\123" $convertedString = ConvertTo-EscapedStringForWqlFilter -FilterString $inputString - $convertedString | Should Be $expectedString + $convertedString | Should -Be $expectedString } } - + Describe 'WindowsProcess\Get-ProcessOwner' { $mockOwner = @{ Domain = 'Mock Domain' User = 'Mock User' - } + } Mock -CommandName Get-ProcessOwnerCimInstance -MockWith { return $mockOwner } It 'Should return the correct string with domain\user' { $owner = Get-ProcessOwner -Process $script:mockProcess1 - $owner | Should Be ($mockOwner.Domain + '\' + $mockOwner.User) + $owner | Should -Be ($mockOwner.Domain + '\' + $mockOwner.User) } - + It 'Should return the correct string with default-domain\user when domain is not there' { $mockOwner.Domain = $null $owner = Get-ProcessOwner -Process $script:mockProcess1 - $owner | Should Be ($env:computerName + '\' + $mockOwner.User) + $owner | Should -Be ($env:computerName + '\' + $mockOwner.User) } - + } - - Describe 'WindowsProcess\Get-ArgumentsFromCommandLineInput' { + + Describe 'WindowsProcess\Get-ArgumentsFromCommandLineInput' { It 'Should return the correct arguments when single quotes are used' { $inputString = 'test.txt a b c' $argumentsReturned = Get-ArgumentsFromCommandLineInput -CommandLineInput $inputString - $argumentsReturned | Should Be 'a b c' + $argumentsReturned | Should -Be 'a b c' } - + It 'Should return the correct arguments when double quotes are used' { $inputString = '"test file test" a b c' $argumentsReturned = Get-ArgumentsFromCommandLineInput -CommandLineInput $inputString - $argumentsReturned | Should Be 'a b c' + $argumentsReturned | Should -Be 'a b c' } - + It 'Should return an empty string when an empty string is passed in' { $inputString = $null - $resultString = [String]::Empty + $resultString = [System.String]::Empty $argumentsReturned = Get-ArgumentsFromCommandLineInput -CommandLineInput $inputString - $argumentsReturned | Should Be $resultString + $argumentsReturned | Should -Be $resultString } - + It 'Should return an empty string when there are no arguments' { $inputString = 'test.txt' - $resultString = [String]::Empty + $resultString = [System.String]::Empty $argumentsReturned = Get-ArgumentsFromCommandLineInput -CommandLineInput $inputString - $argumentsReturned | Should Be $resultString + $argumentsReturned | Should -Be $resultString } } - + Describe 'WindowsProcess\Assert-HashtableDoesNotContainKey' { $mockHashtable = @{ Key1 = 'test key1' @@ -644,81 +644,81 @@ try Key3 = 'test key3' } Mock -CommandName New-InvalidArgumentException -MockWith { Throw $script:exceptionMessage } - + It 'Should not throw an exception if the hashtable does not contain a key' { $mockKey = @('k1', 'k2', 'k3', 'k4', 'k5') - { Assert-HashTableDoesNotContainKey -Hashtable $mockHashtable -Key $mockKey } | Should Not Throw + { Assert-HashTableDoesNotContainKey -Hashtable $mockHashtable -Key $mockKey } | Should -Not -Throw } - + It 'Should throw an exception if the hashtable contains a key' { $mockKey = @('k1', 'k2', 'Key3', 'k4', 'k5') - { Assert-HashTableDoesNotContainKey -Hashtable $mockHashtable -Key $mockKey } | Should Throw $script:exceptionMessage - + { Assert-HashTableDoesNotContainKey -Hashtable $mockHashtable -Key $mockKey } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName New-InvalidArgumentException -Exactly 1 -Scope It } } - + Describe 'WindowsProcess\Wait-ProcessCount' { - $mockProcessSettings = @{ - Path = 'mockPath' + $mockProcessSettings = @{ + Path = 'mockPath' Arguments = 'mockArguments' } Mock -CommandName Get-ProcessCimInstance -MockWith { return @($script:mockProcess1, $script:mockProcess3) } It 'Should return true when all processes are returned' { $processCountResult = Wait-ProcessCount -ProcessSettings $mockProcessSettings -ProcessCount 2 - $processCountResult | Should Be $true + $processCountResult | Should -BeTrue } - + It 'Should return false when not all processes are returned' { $processCountResult = Wait-ProcessCount -ProcessSettings $mockProcessSettings ` -ProcessCount 3 ` -WaitTime 10 - $processCountResult | Should Be $false + $processCountResult | Should -BeFalse } } - + Describe 'WindowsProcess\Assert-PathArgumentRooted' { Mock -CommandName New-InvalidArgumentException -MockWith { Throw $script:exceptionMessage } It 'Should not throw when path is rooted' { $rootedPath = 'C:\testProcess.exe' - + { Assert-PathArgumentRooted -PathArgumentName 'mock test name' ` - -PathArgument $rootedPath } | Should Not Throw + -PathArgument $rootedPath } | Should -Not -Throw } - + It 'Should throw an invalid argument exception when Path is unrooted' { $unrootedPath = 'invalidfile.txt' - - + + { Assert-PathArgumentRooted -PathArgumentName 'mock test name' ` - -PathArgument $unrootedPath } | Should Throw $script:exceptionMessage - + -PathArgument $unrootedPath } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName New-InvalidArgumentException -Exactly 1 -Scope It } } - + Describe 'WindowsProcess\Assert-PathArgumentValid' { Mock -CommandName New-InvalidArgumentException -MockWith { Throw $script:exceptionMessage } It 'Should not throw when path is valid' { Mock -CommandName Test-Path -MockWith { return $true } - + { Assert-PathArgumentValid -PathArgumentName 'test name' ` - -PathArgument 'validPath' } | Should Not Throw + -PathArgument 'validPath' } | Should -Not -Throw } - + It 'Should throw an invalid argument exception when Path is not valid' { Mock -CommandName Test-Path -MockWith { return $false } - + { Assert-PathArgumentValid -PathArgumentName 'test name' ` - -PathArgument 'invalidPath' } | Should Throw $script:exceptionMessage - + -PathArgument 'invalidPath' } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName New-InvalidArgumentException -Exactly 1 -Scope It } } - + Describe 'WindowsProcess\Split-Credential' { Mock -CommandName New-InvalidArgumentException -MockWith { Throw $script:exceptionMessage } @@ -726,57 +726,57 @@ try $testUsername = 'user@domain' $testPassword = ConvertTo-SecureString -String 'dummy' -AsPlainText -Force $testCredential = New-Object -TypeName 'PSCredential' -ArgumentList @($testUsername, $testPassword) - + $splitCredentialResult = Split-Credential -Credential $testCredential - - $splitCredentialResult.Domain | Should Be 'domain' - $splitCredentialResult.Username | Should Be 'user' + + $splitCredentialResult.Domain | Should -Be 'domain' + $splitCredentialResult.Username | Should -Be 'user' } - + It 'Should return correct domain and username with \ seperator' { $testUsername = 'domain\user' $testPassword = ConvertTo-SecureString -String 'dummy' -AsPlainText -Force $testCredential = New-Object -TypeName 'PSCredential' -ArgumentList @($testUsername, $testPassword) - + $splitCredentialResult = Split-Credential -Credential $testCredential - - $splitCredentialResult.Domain | Should Be 'domain' - $splitCredentialResult.Username | Should Be 'user' + + $splitCredentialResult.Domain | Should -Be 'domain' + $splitCredentialResult.Username | Should -Be 'user' } - + It 'Should return correct domain and username with a local user' { $testUsername = 'localuser' $testPassword = ConvertTo-SecureString -String 'dummy' -AsPlainText -Force $testCredential = New-Object -TypeName 'PSCredential' -ArgumentList @($testUsername, $testPassword) - + $splitCredentialResult = Split-Credential -Credential $testCredential - - $splitCredentialResult.Domain | Should Be $env:computerName - $splitCredentialResult.Username | Should Be 'localuser' + + $splitCredentialResult.Domain | Should -Be $env:computerName + $splitCredentialResult.Username | Should -Be 'localuser' } - + It 'Should throw an invalid argument exception when more than one \ in username' { $testUsername = 'user\domain\foo' $testPassword = ConvertTo-SecureString -String 'dummy' -AsPlainText -Force $testCredential = New-Object -TypeName 'PSCredential' -ArgumentList @($testUsername, $testPassword) - - { $splitCredentialResult = Split-Credential -Credential $testCredential } | Should Throw $script:exceptionMessage - + + { $null = Split-Credential -Credential $testCredential } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName New-InvalidArgumentException -Exactly 1 -Scope It } - + It 'Should throw an invalid argument exception when more than one @ in username' { $testUsername = 'user@domain@foo' $testPassword = ConvertTo-SecureString -String 'dummy' -AsPlainText -Force $testCredential = New-Object -TypeName 'PSCredential' -ArgumentList @($testUsername, $testPassword) - - { $splitCredentialResult = Split-Credential -Credential $testCredential } | Should Throw $script:exceptionMessage - + + { $null = Split-Credential -Credential $testCredential } | Should -Throw -ExpectedMessage $script:exceptionMessage + Assert-MockCalled -CommandName New-InvalidArgumentException -Exactly 1 -Scope It } } - } -} + } +} finally { Exit-DscResourceTestEnvironment -TestEnvironment $script:testEnvironment diff --git a/Tests/Unit/ResourceSetHelper.Tests.ps1 b/Tests/Unit/ResourceSetHelper.Tests.ps1 index 6459b9c..1e175dd 100644 --- a/Tests/Unit/ResourceSetHelper.Tests.ps1 +++ b/Tests/Unit/ResourceSetHelper.Tests.ps1 @@ -1,4 +1,4 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')] param () $errorActionPreference = 'Stop' @@ -17,7 +17,7 @@ InModuleScope 'ResourceSetHelper' { Name = 'Name' CommonStringParameter1 = 'CommonParameter1' } - + $keyParameterName = 'Name' $commonParameterString = New-ResourceSetCommonParameterString -KeyParameterName $keyParameterName -Parameters $parameters @@ -27,12 +27,12 @@ InModuleScope 'ResourceSetHelper' { It 'Should return string containing one variable reference for one credential common parameter' { $testUserName = 'testUserName' $secureTestPassword = ConvertTo-SecureString -String 'testPassword' -AsPlainText -Force - + $parameters = @{ Name = 'Name' CommonCredentialParameter1 = New-Object -TypeName 'PSCredential' -ArgumentList @( $testUsername, $secureTestPassword ) } - + $keyParameterName = 'Name' $commonParameterString = New-ResourceSetCommonParameterString -KeyParameterName $keyParameterName -Parameters $parameters @@ -51,10 +51,10 @@ InModuleScope 'ResourceSetHelper' { $keyParameterName = 'Name' $commonParameterString = New-ResourceSetCommonParameterString -KeyParameterName $keyParameterName -Parameters $parameters - $commonParameterString.Contains("CommonStringParameter1 = `"CommonParameter1`"`r`n") | Should -Be $true - $commonParameterString.Contains("CommonStringParameter2 = `"CommonParameter2`"`r`n") | Should -Be $true - $commonParameterString.Contains("CommonIntParameter1 = `$CommonIntParameter1`r`n") | Should -Be $true - $commonParameterString.Contains("CommonIntParameter2 = `$CommonIntParameter2`r`n") | Should -Be $true + $commonParameterString.Contains("CommonStringParameter1 = `"CommonParameter1`"`r`n") | Should -BeTrue + $commonParameterString.Contains("CommonStringParameter2 = `"CommonParameter2`"`r`n") | Should -BeTrue + $commonParameterString.Contains("CommonIntParameter1 = `$CommonIntParameter1`r`n") | Should -BeTrue + $commonParameterString.Contains("CommonIntParameter2 = `$CommonIntParameter2`r`n") | Should -BeTrue } } @@ -100,15 +100,15 @@ InModuleScope 'ResourceSetHelper' { CommonParameter2 = 'CommonParameterValue2' } } - + $newResourceSetConfigurationScriptBlock = New-ResourceSetConfigurationScriptBlock @newResourceSetConfigurationParams It 'Should return a ScriptBlock' { - $newResourceSetConfigurationScriptBlock -is [ScriptBlock] | Should -Be $true + $newResourceSetConfigurationScriptBlock -is [System.Management.Automation.ScriptBlock] | Should -BeTrue } It 'Should return ScriptBlock of string returned from New-ResourceSetConfigurationString' { - $newResourceSetConfigurationScriptBlock | Should -Match ([ScriptBlock]::Create($configurationString)) + $newResourceSetConfigurationScriptBlock | Should -Match ([System.Management.Automation.ScriptBlock]::Create($configurationString)) } It 'Should call New-ResourceSetConfigurationString with the correct ModuleName' {