diff --git a/CHANGELOG.md b/CHANGELOG.md index cf0f797..e9421b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +* 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) diff --git a/DscResources/CommonResourceHelper.psm1 b/DscResources/CommonResourceHelper.psm1 index 0299b7d..1f3e32c 100644 --- a/DscResources/CommonResourceHelper.psm1 +++ b/DscResources/CommonResourceHelper.psm1 @@ -9,11 +9,11 @@ function Test-IsNanoServer param () $serverLevelsRegKey = 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels' - + if (Test-Path -Path $serverLevelsRegKey) { $serverLevels = Get-ItemProperty -Path $serverLevelsRegKey - + if ($serverLevels.NanoServer -eq 1) { $isNanoServer = $true @@ -27,7 +27,7 @@ function Test-IsNanoServer { $isNanoServer = $false } - + return $isNanoServer } @@ -46,7 +46,8 @@ function Test-CommandExists ( [Parameter(Mandatory = $true)] [ValidateNotNullOrEmpty()] - [System.String] $Name + [System.String] + $Name ) $command = Get-Command -Name $Name -ErrorAction 'SilentlyContinue' @@ -55,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 { @@ -80,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 @@ -92,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 { @@ -123,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 @@ -147,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.schema.psm1 b/DscResources/GroupSet/GroupSet.schema.psm1 index c82e64f..4c7a785 100644 --- a/DscResources/GroupSet/GroupSet.schema.psm1 +++ b/DscResources/GroupSet/GroupSet.schema.psm1 @@ -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 27eb19a..6ceb38e 100644 --- a/DscResources/MSFT_Archive/MSFT_Archive.psm1 +++ b/DscResources/MSFT_Archive/MSFT_Archive.psm1 @@ -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_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] + [Parameter(Mandatory = $true)] + [System.String] $ExistingPaths, - + [Parameter(Mandatory = $true)] - [String] + [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_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 fdc7f97..1a24fa0 100644 --- a/DscResources/MSFT_MsiPackage/MSFT_MsiPackage.psm1 +++ b/DscResources/MSFT_MsiPackage/MSFT_MsiPackage.psm1 @@ -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 } @@ -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_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_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_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_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 777450f..fb57255 100644 --- a/DscResources/MSFT_WindowsPackageCab/MSFT_WindowsPackageCab.psm1 +++ b/DscResources/MSFT_WindowsPackageCab/MSFT_WindowsPackageCab.psm1 @@ -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_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.schema.psm1 b/DscResources/ProcessSet/ProcessSet.schema.psm1 index 42435c0..c518b5a 100644 --- a/DscResources/ProcessSet/ProcessSet.schema.psm1 +++ b/DscResources/ProcessSet/ProcessSet.schema.psm1 @@ -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 6b9232b..c436951 100644 --- a/DscResources/ResourceSetHelper.psm1 +++ b/DscResources/ResourceSetHelper.psm1 @@ -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.schema.psm1 b/DscResources/ServiceSet/ServiceSet.schema.psm1 index 3ae17cc..2fac68a 100644 --- a/DscResources/ServiceSet/ServiceSet.schema.psm1 +++ b/DscResources/ServiceSet/ServiceSet.schema.psm1 @@ -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.schema.psm1 b/DscResources/WindowsFeatureSet/WindowsFeatureSet.schema.psm1 index c96f468..dfe2942 100644 --- a/DscResources/WindowsFeatureSet/WindowsFeatureSet.schema.psm1 +++ b/DscResources/WindowsFeatureSet/WindowsFeatureSet.schema.psm1 @@ -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.schema.psm1 b/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.schema.psm1 index f430804..585fb94 100644 --- a/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.schema.psm1 +++ b/DscResources/WindowsOptionalFeatureSet/WindowsOptionalFeatureSet.schema.psm1 @@ -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/Tests/Unit/MSFT_GroupResource.Tests.ps1 b/Tests/Unit/MSFT_GroupResource.Tests.ps1 index 5578b2d..acb50cf 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. #> @@ -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' } diff --git a/Tests/Unit/MSFT_ServiceResource.Tests.ps1 b/Tests/Unit/MSFT_ServiceResource.Tests.ps1 index 78c7a5c..bec9fce 100644 --- a/Tests/Unit/MSFT_ServiceResource.Tests.ps1 +++ b/Tests/Unit/MSFT_ServiceResource.Tests.ps1 @@ -1692,7 +1692,7 @@ try } } - Describe 'Service\Set-ServiceDependencies' { + Describe 'Service\Set-ServiceDependency' { $testServiceCimInstance = New-CimInstance -ClassName 'Win32_Service' -ClientOnly try { @@ -1716,7 +1716,7 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should Not Throw } It 'Should retrieve the service' { @@ -1739,7 +1739,7 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should Not Throw } It 'Should retrieve the service' { @@ -1762,7 +1762,7 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should Not Throw } It 'Should retrieve the service' { @@ -1791,7 +1791,7 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should Not Throw } It 'Should retrieve the service' { @@ -1814,7 +1814,7 @@ try } It 'Should not throw' { - { Set-ServiceDependencies @setServiceDependenciesParameters } | Should Not Throw + { Set-ServiceDependency @setServiceDependenciesParameters } | Should Not Throw } It 'Should retrieve the service' { @@ -1845,7 +1845,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 $errorMessage } } } @@ -2201,7 +2201,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 { } @@ -2223,7 +2223,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' { @@ -2254,7 +2254,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' { @@ -2285,7 +2285,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' { @@ -2317,7 +2317,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' { @@ -2348,7 +2348,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' { @@ -2379,7 +2379,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' { @@ -2410,7 +2410,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' { @@ -2441,7 +2441,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' { @@ -2472,7 +2472,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' { diff --git a/Tests/Unit/MSFT_WindowsFeature.Tests.ps1 b/Tests/Unit/MSFT_WindowsFeature.Tests.ps1 index 5f47aa2..b3ac958 100644 --- a/Tests/Unit/MSFT_WindowsFeature.Tests.ps1 +++ b/Tests/Unit/MSFT_WindowsFeature.Tests.ps1 @@ -556,17 +556,17 @@ try } } - 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) } }