├── Commands.ps1 ├── Common.ps1 ├── DscResources ├── PshOrg_AccountAdminTemplateSetting │ ├── PshOrg_AccountAdminTemplateSetting.Tests.ps1 │ ├── PshOrg_AccountAdminTemplateSetting.psm1 │ └── PshOrg_AccountAdminTemplateSetting.schema.mof └── PshOrg_AdminTemplateSetting │ ├── PshOrg_AdminTemplateSetting.Tests.ps1 │ ├── PshOrg_AdminTemplateSetting.psm1 │ └── PshOrg_AdminTemplateSetting.schema.mof ├── LICENSE ├── PolFileEditor.dll ├── PolicyFileEditor.Tests.ps1 ├── PolicyFileEditor.psd1 ├── PolicyFileEditor.psm1 ├── README.md ├── Sources └── PolFileEditor.cs ├── build.psake.ps1 └── en-US └── about_RegistryValuesForAdminTemplates.Help.txt /Commands.ps1: -------------------------------------------------------------------------------- 1 | #requires -Version 2.0 2 | 3 | $scriptRoot = Split-Path $MyInvocation.MyCommand.Path 4 | . "$scriptRoot\Common.ps1" 5 | 6 | <# 7 | .SYNOPSIS 8 | Creates or modifies a value in a .pol file. 9 | .DESCRIPTION 10 | Creates or modifies a value in a .pol file. By default, also updates the version number in the policy's gpt.ini file. 11 | .PARAMETER Path 12 | Path to the .pol file that is to be modified. 13 | .PARAMETER Key 14 | The registry key inside the .pol file that you want to modify. 15 | .PARAMETER ValueName 16 | The name of the registry value. May be set to an empty string to modify the default value of a key. 17 | .PARAMETER Data 18 | The new value to assign to the registry key / value. Cannot be $null, but can be set to an empty string or empty array. 19 | .PARAMETER Type 20 | The type of registry value to set in the policy file. Cannot be set to Unknown or None, but all other values of the RegistryValueKind enum are legal. 21 | .PARAMETER NoGptIniUpdate 22 | When this switch is used, the command will not attempt to update the version number in the gpt.ini file 23 | .EXAMPLE 24 | Set-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue -Data 'Hello, World!' -Type String 25 | 26 | Assigns a value of 'Hello, World!' to the String value Software\Policies\Something\SomeValue in the local computer Machine GPO. Updates the Machine version counter in $env:systemroot\system32\GroupPolicy\gpt.ini 27 | .EXAMPLE 28 | Set-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue -Data 'Hello, World!' -Type String -NoGptIniUpdate 29 | 30 | Same as example 1, except this one does not update gpt.ini right away. This can be useful if you want to set multiple 31 | values in the policy file and only trigger a single Group Policy refresh. 32 | .EXAMPLE 33 | Set-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue -Data '0x12345' -Type DWord 34 | 35 | Example demonstrating that strings with valid numeric data (including hexadecimal strings beginning with 0x) can be assigned to the numeric types DWord, QWord and Binary. 36 | .EXAMPLE 37 | $entries = @( 38 | New-Object psobject -Property @{ ValueName = 'MaxXResolution'; Data = 1680 } 39 | New-Object psobject -Property @{ ValueName = 'MaxYResolution'; Data = 1050 } 40 | ) 41 | 42 | $entries | Set-PolicyFileEntry -Path $env:SystemRoot\system32\GroupPolicy\Machine\registry.pol ` 43 | -Key 'SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services' ` 44 | -Type DWord 45 | 46 | Example of using pipeline input to set multiple values at once. The advantage to this approach is that the 47 | .pol file on disk (and the GPT.ini file) will be updated if _any_ of the specified settings had to be modified, 48 | and will be left alone if the file already contained all of the correct values. 49 | 50 | The Key and Type properties could have also been specified via the pipeline objects instead of on the command line, 51 | but since both values shared the same Key and Type, this example shows that you can pass the values in either way. 52 | .INPUTS 53 | The Key, ValueName, Data, and Type properties may be bound via the pipeline by property name. 54 | .OUTPUTS 55 | None. This command does not generate output. 56 | .NOTES 57 | If the specified policy file already contains the correct value, the file will not be modified, and the gpt.ini file will not be updated. 58 | .LINK 59 | Get-PolicyFileEntry 60 | .LINK 61 | Remove-PolicyFileEntry 62 | .LINK 63 | Update-GptIniVersion 64 | .LINK 65 | about_RegistryValuesForAdminTemplates 66 | #> 67 | 68 | function Set-PolicyFileEntry 69 | { 70 | [CmdletBinding(SupportsShouldProcess = $true)] 71 | param ( 72 | [Parameter(Mandatory = $true, Position = 0)] 73 | [string] $Path, 74 | 75 | [Parameter(Mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = $true)] 76 | [string] $Key, 77 | 78 | [Parameter(Mandatory = $true, Position = 2, ValueFromPipelineByPropertyName = $true)] 79 | [AllowEmptyString()] 80 | [string] $ValueName, 81 | 82 | [Parameter(Mandatory = $true, Position = 3, ValueFromPipelineByPropertyName = $true)] 83 | [AllowEmptyString()] 84 | [AllowEmptyCollection()] 85 | [object] $Data, 86 | 87 | [Parameter(ValueFromPipelineByPropertyName = $true)] 88 | [ValidateScript({ 89 | if ($_ -eq [Microsoft.Win32.RegistryValueKind]::Unknown) 90 | { 91 | throw 'Unknown is not a valid value for the Type parameter' 92 | } 93 | 94 | if ($_ -eq [Microsoft.Win32.RegistryValueKind]::None) 95 | { 96 | throw 'None is not a valid value for the Type parameter' 97 | } 98 | 99 | return $true 100 | })] 101 | [Microsoft.Win32.RegistryValueKind] $Type = [Microsoft.Win32.RegistryValueKind]::String, 102 | 103 | [switch] $NoGptIniUpdate 104 | ) 105 | 106 | begin 107 | { 108 | if (Get-Command [G]et-CallerPreference -CommandType Function -Module PreferenceVariables) 109 | { 110 | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState 111 | } 112 | 113 | $dirty = $false 114 | 115 | try 116 | { 117 | $policyFile = OpenPolicyFile -Path $Path -ErrorAction Stop 118 | } 119 | catch 120 | { 121 | $PSCmdlet.ThrowTerminatingError($_) 122 | } 123 | } 124 | 125 | process 126 | { 127 | $existingEntry = $policyFile.GetValue($Key, $ValueName) 128 | 129 | if ($null -ne $existingEntry -and $Type -eq (PolEntryTypeToRegistryValueKind $existingEntry.Type)) 130 | { 131 | $existingData = GetEntryData -Entry $existingEntry -Type $Type 132 | if (DataIsEqual $Data $existingData -Type $Type) 133 | { 134 | Write-Verbose "Policy setting '$Key\$ValueName' is already set to '$Data' of type '$Type'." 135 | return 136 | } 137 | } 138 | 139 | Write-Verbose "Configuring '$Key\$ValueName' to value '$Data' of type '$Type'." 140 | 141 | try 142 | { 143 | switch ($Type) 144 | { 145 | ([Microsoft.Win32.RegistryValueKind]::Binary) 146 | { 147 | $bytes = $Data -as [byte[]] 148 | if ($null -eq $bytes) 149 | { 150 | $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to Binary, -Data must be passed a Byte[] array.' 151 | $PSCmdlet.ThrowTerminatingError($errorRecord) 152 | } 153 | else 154 | { 155 | $policyFile.SetBinaryValue($Key, $ValueName, $bytes) 156 | } 157 | 158 | break 159 | } 160 | 161 | ([Microsoft.Win32.RegistryValueKind]::String) 162 | { 163 | $array = @($Data) 164 | 165 | if ($array.Count -ne 1) 166 | { 167 | $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to String, -Data must be passed a scalar value or single-element array.' 168 | $PSCmdlet.ThrowTerminatingError($errorRecord) 169 | } 170 | else 171 | { 172 | $policyFile.SetStringValue($Key, $ValueName, $array[0].ToString()) 173 | } 174 | 175 | break 176 | } 177 | 178 | ([Microsoft.Win32.RegistryValueKind]::ExpandString) 179 | { 180 | $array = @($Data) 181 | 182 | if ($array.Count -ne 1) 183 | { 184 | $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to ExpandString, -Data must be passed a scalar value or single-element array.' 185 | $PSCmdlet.ThrowTerminatingError($errorRecord) 186 | } 187 | else 188 | { 189 | $policyFile.SetStringValue($Key, $ValueName, $array[0].ToString(), $true) 190 | } 191 | 192 | break 193 | } 194 | 195 | ([Microsoft.Win32.RegistryValueKind]::DWord) 196 | { 197 | $array = @($Data) 198 | $dword = ($array | Select-Object -First 1) -as [UInt32] 199 | if ($null -eq $dword -or $array.Count -ne 1) 200 | { 201 | $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to DWord, -Data must be passed a valid UInt32 value.' 202 | $PSCmdlet.ThrowTerminatingError($errorRecord) 203 | } 204 | else 205 | { 206 | $policyFile.SetDWORDValue($key, $ValueName, $dword) 207 | } 208 | 209 | break 210 | } 211 | 212 | ([Microsoft.Win32.RegistryValueKind]::QWord) 213 | { 214 | $array = @($Data) 215 | $qword = ($array | Select-Object -First 1) -as [UInt64] 216 | if ($null -eq $qword -or $array.Count -ne 1) 217 | { 218 | $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'When -Type is set to QWord, -Data must be passed a valid UInt64 value.' 219 | $PSCmdlet.ThrowTerminatingError($errorRecord) 220 | } 221 | else 222 | { 223 | $policyFile.SetQWORDValue($key, $ValueName, $qword) 224 | } 225 | 226 | break 227 | } 228 | 229 | ([Microsoft.Win32.RegistryValueKind]::MultiString) 230 | { 231 | $strings = [string[]] @( 232 | foreach ($item in @($Data)) 233 | { 234 | $item.ToString() 235 | } 236 | ) 237 | 238 | $policyFile.SetMultiStringValue($Key, $ValueName, $strings) 239 | 240 | break 241 | } 242 | 243 | } # switch ($Type) 244 | 245 | $dirty = $true 246 | } 247 | catch 248 | { 249 | throw 250 | } 251 | } 252 | 253 | end 254 | { 255 | if ($dirty) 256 | { 257 | $doUpdateGptIni = -not $NoGptIniUpdate 258 | 259 | try 260 | { 261 | # SavePolicyFile contains the calls to $PSCmdlet.ShouldProcess, and will inherit our 262 | # WhatIfPreference / ConfirmPreference values from here. 263 | SavePolicyFile -PolicyFile $policyFile -UpdateGptIni:$doUpdateGptIni -ErrorAction Stop 264 | } 265 | catch 266 | { 267 | $PSCmdlet.ThrowTerminatingError($_) 268 | } 269 | } 270 | } 271 | } 272 | 273 | <# 274 | .SYNOPSIS 275 | Retrieves the current setting(s) from a .pol file. 276 | .DESCRIPTION 277 | Retrieves the current setting(s) from a .pol file. 278 | .PARAMETER Path 279 | Path to the .pol file that is to be read. 280 | .PARAMETER Key 281 | The registry key inside the .pol file that you want to read. 282 | .PARAMETER ValueName 283 | The name of the registry value. May be set to an empty string to read the default value of a key. 284 | .PARAMETER All 285 | Switch indicating that all entries from the specified .pol file should be output, instead of searching for a specific key / ValueName pair. 286 | .EXAMPLE 287 | Get-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue 288 | 289 | Reads the value of Software\Policies\Something\SomeValue from the Machine admin templates of the local GPO. 290 | Either returns an object with the data and type of this registry value (if present), or returns nothing, if not found. 291 | .EXAMPLE 292 | Get-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -All 293 | 294 | Outputs all of the registry values from the local machine Administrative Templates 295 | .INPUTS 296 | None. This command does not accept pipeline input. 297 | .OUTPUTS 298 | If the specified registry value is found, the function outputs a PSCustomObject with the following properties: 299 | ValueName: The same value that was passed to the -ValueName parameter 300 | Key: The same value that was passed to the -Key parameter 301 | Data: The current value assigned to the specified Key / ValueName in the .pol file. 302 | Type: The RegistryValueKind type of the specified Key / ValueName in the .pol file. 303 | If the specified registry value is not found in the .pol file, the command returns nothing. No error is produced. 304 | .LINK 305 | Set-PolicyFileEntry 306 | .LINK 307 | Remove-PolicyFileEntry 308 | .LINK 309 | Update-GptIniVersion 310 | .LINK 311 | about_RegistryValuesForAdminTemplates 312 | #> 313 | 314 | function Get-PolicyFileEntry 315 | { 316 | [CmdletBinding(DefaultParameterSetName = 'ByKeyAndValue')] 317 | param ( 318 | [Parameter(Mandatory = $true, Position = 0)] 319 | [string] $Path, 320 | 321 | [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ByKeyAndValue')] 322 | [string] $Key, 323 | 324 | [Parameter(Mandatory = $true, Position = 2, ParameterSetName = 'ByKeyAndValue')] 325 | [string] $ValueName, 326 | 327 | [Parameter(Mandatory = $true, ParameterSetName = 'All')] 328 | [switch] $All 329 | ) 330 | 331 | if (Get-Command [G]et-CallerPreference -CommandType Function -Module PreferenceVariables) 332 | { 333 | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState 334 | } 335 | 336 | try 337 | { 338 | $policyFile = OpenPolicyFile -Path $Path -ErrorAction Stop 339 | } 340 | catch 341 | { 342 | $PSCmdlet.ThrowTerminatingError($_) 343 | } 344 | 345 | if ($PSCmdlet.ParameterSetName -eq 'ByKeyAndValue') 346 | { 347 | $entry = $policyFile.GetValue($Key, $ValueName) 348 | 349 | if ($null -ne $entry) 350 | { 351 | PolEntryToPsObject -PolEntry $entry 352 | } 353 | } 354 | else 355 | { 356 | foreach ($entry in $policyFile.Entries) 357 | { 358 | PolEntryToPsObject -PolEntry $entry 359 | } 360 | } 361 | } 362 | 363 | <# 364 | .SYNOPSIS 365 | Removes a value from a .pol file. 366 | .DESCRIPTION 367 | Removes a value from a .pol file. By default, also updates the version number in the policy's gpt.ini file. 368 | .PARAMETER Path 369 | Path to the .pol file that is to be modified. 370 | .PARAMETER Key 371 | The registry key inside the .pol file from which you want to remove a value. 372 | .PARAMETER ValueName 373 | The name of the registry value to be removed. May be set to an empty string to remove the default value of a key. 374 | .PARAMETER NoGptIniUpdate 375 | When this switch is used, the command will not attempt to update the version number in the gpt.ini file 376 | .EXAMPLE 377 | Remove-PolicyFileEntry -Path $env:systemroot\system32\GroupPolicy\Machine\registry.pol -Key Software\Policies\Something -ValueName SomeValue 378 | 379 | Removes the value Software\Policies\Something\SomeValue from the local computer Machine GPO, if present. Updates the Machine version counter in $env:systemroot\system32\GroupPolicy\gpt.ini 380 | .EXAMPLE 381 | $entries = @( 382 | New-Object psobject -Property @{ ValueName = 'MaxXResolution'; Data = 1680 } 383 | New-Object psobject -Property @{ ValueName = 'MaxYResolution'; Data = 1050 } 384 | ) 385 | 386 | $entries | Remove-PolicyFileEntry -Path $env:SystemRoot\system32\GroupPolicy\Machine\registry.pol ` 387 | -Key 'SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services' 388 | 389 | Example of using pipeline input to remove multiple values at once. The advantage to this approach is that the 390 | .pol file on disk (and the GPT.ini file) will be updated if _any_ of the specified settings had to be removed, 391 | and will be left alone if the file already did not contain any of those values. 392 | 393 | The Key property could have also been specified via the pipeline objects instead of on the command line, but 394 | since both values shared the same Key, this example shows that you can pass the value in either way. 395 | 396 | .INPUTS 397 | The Key and ValueName properties may be bound via the pipeline by property name. 398 | .OUTPUTS 399 | None. This command does not generate output. 400 | .NOTES 401 | If the specified policy file is already not present in the .pol file, the file will not be modified, and the gpt.ini file will not be updated. 402 | .LINK 403 | Get-PolicyFileEntry 404 | .LINK 405 | Set-PolicyFileEntry 406 | .LINK 407 | Update-GptIniVersion 408 | .LINK 409 | about_RegistryValuesForAdminTemplates 410 | #> 411 | 412 | function Remove-PolicyFileEntry 413 | { 414 | [CmdletBinding(SupportsShouldProcess = $true)] 415 | param ( 416 | [Parameter(Mandatory = $true, Position = 0)] 417 | [string] $Path, 418 | 419 | [Parameter(Mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = $true)] 420 | [string] $Key, 421 | 422 | [Parameter(Mandatory = $true, Position = 2, ValueFromPipelineByPropertyName = $true)] 423 | [string] $ValueName, 424 | 425 | [switch] $NoGptIniUpdate 426 | ) 427 | 428 | begin 429 | { 430 | if (Get-Command [G]et-CallerPreference -CommandType Function -Module PreferenceVariables) 431 | { 432 | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState 433 | } 434 | 435 | $dirty = $false 436 | 437 | try 438 | { 439 | $policyFile = OpenPolicyFile -Path $Path -ErrorAction Stop 440 | } 441 | catch 442 | { 443 | $PSCmdlet.ThrowTerminatingError($_) 444 | } 445 | } 446 | 447 | process 448 | { 449 | $entry = $policyFile.GetValue($Key, $ValueName) 450 | 451 | if ($null -eq $entry) 452 | { 453 | Write-Verbose "Entry '$Key\$ValueName' is already not present in file '$Path'." 454 | return 455 | } 456 | 457 | Write-Verbose "Removing entry '$Key\$ValueName' from file '$Path'" 458 | $policyFile.DeleteValue($Key, $ValueName) 459 | $dirty = $true 460 | } 461 | 462 | end 463 | { 464 | if ($dirty) 465 | { 466 | $doUpdateGptIni = -not $NoGptIniUpdate 467 | 468 | try 469 | { 470 | # SavePolicyFile contains the calls to $PSCmdlet.ShouldProcess, and will inherit our 471 | # WhatIfPreference / ConfirmPreference values from here. 472 | SavePolicyFile -PolicyFile $policyFile -UpdateGptIni:$doUpdateGptIni -ErrorAction Stop 473 | } 474 | catch 475 | { 476 | $PSCmdlet.ThrowTerminatingError($_) 477 | } 478 | } 479 | } 480 | } 481 | 482 | <# 483 | .SYNOPSIS 484 | Increments the version counter in a gpt.ini file. 485 | .DESCRIPTION 486 | Increments the version counter in a gpt.ini file. 487 | .PARAMETER Path 488 | Path to the gpt.ini file that is to be modified. 489 | .PARAMETER PolicyType 490 | Can be set to either 'Machine', 'User', or both. This affects how the value of the Version number in the ini file is changed. 491 | .EXAMPLE 492 | Update-GptIniVersion -Path $env:SystemRoot\system32\GroupPolicy\gpt.ini -PolicyType Machine 493 | 494 | Increments the Machine version counter of the local GPO. 495 | .EXAMPLE 496 | Update-GptIniVersion -Path $env:SystemRoot\system32\GroupPolicy\gpt.ini -PolicyType User 497 | 498 | Increments the User version counter of the local GPO. 499 | .EXAMPLE 500 | Update-GptIniVersion -Path $env:SystemRoot\system32\GroupPolicy\gpt.ini -PolicyType Machine,User 501 | 502 | Increments both the Machine and User version counters of the local GPO. 503 | .INPUTS 504 | None. This command does not accept pipeline input. 505 | .OUTPUTS 506 | None. This command does not generate output. 507 | .NOTES 508 | A gpt.ini file contains only a single Version value. However, this represents two separate counters, for machine and user versions. 509 | The high 16 bits of the value are the User counter, and the low 16 bits are the Machine counter. For example (on PowerShell 3.0 510 | and later), the Version value when the Machine counter is set to 3 and the User counter is set to 5 can be found by evaluating this 511 | expression: (5 -shl 16) -bor 3 , which will show up as decimal value 327683 in the INI file. 512 | .LINK 513 | Get-PolicyFileEntry 514 | .LINK 515 | Set-PolicyFileEntry 516 | .LINK 517 | Remove-PolicyFileEntry 518 | .LINK 519 | about_RegistryValuesForAdminTemplates 520 | #> 521 | 522 | function Update-GptIniVersion 523 | { 524 | [CmdletBinding(SupportsShouldProcess = $true)] 525 | param ( 526 | [Parameter(Mandatory = $true)] 527 | [ValidateScript({ 528 | if (Test-Path -LiteralPath $_ -PathType Leaf) 529 | { 530 | return $true 531 | } 532 | 533 | throw "Path '$_' does not exist." 534 | })] 535 | [string] $Path, 536 | 537 | [Parameter(Mandatory = $true)] 538 | [ValidateSet('Machine', 'User')] 539 | [string[]] $PolicyType 540 | ) 541 | 542 | if (Get-Command [G]et-CallerPreference -CommandType Function -Module PreferenceVariables) 543 | { 544 | Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState 545 | } 546 | 547 | try 548 | { 549 | IncrementGptIniVersion @PSBoundParameters 550 | } 551 | catch 552 | { 553 | $PSCmdlet.ThrowTerminatingError($_) 554 | } 555 | } 556 | -------------------------------------------------------------------------------- /Common.ps1: -------------------------------------------------------------------------------- 1 | #requires -Version 2.0 2 | 3 | $script:MachineExtensionGuids = '[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F72-3407-48AE-BA88-E8213C6761F1}]' 4 | $script:UserExtensionGuids = '[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F73-3407-48AE-BA88-E8213C6761F1}]' 5 | 6 | function OpenPolicyFile 7 | { 8 | [CmdletBinding()] 9 | param ( 10 | [Parameter(Mandatory = $true)] 11 | [string] $Path 12 | ) 13 | 14 | $policyFile = New-Object TJX.PolFileEditor.PolFile 15 | $policyFile.FileName = $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path) 16 | 17 | if (Test-Path -LiteralPath $policyFile.FileName) 18 | { 19 | try 20 | { 21 | $policyFile.LoadFile() 22 | } 23 | catch [TJX.PolFileEditor.FileFormatException] 24 | { 25 | $message = "File '$Path' is not a valid POL file." 26 | $exception = New-Object System.Exception($message) 27 | 28 | $errorRecord = New-Object System.Management.Automation.ErrorRecord( 29 | $exception, 'InvalidPolFileContents', [System.Management.Automation.ErrorCategory]::InvalidData, $Path 30 | ) 31 | 32 | throw $errorRecord 33 | } 34 | catch 35 | { 36 | $errorRecord = $_ 37 | $message = "Error loading policy file at path '$Path': $($errorRecord.Exception.Message)" 38 | $exception = New-Object System.Exception($message, $errorRecord.Exception) 39 | 40 | $newErrorRecord = New-Object System.Management.Automation.ErrorRecord( 41 | $exception, 'FailedToOpenPolicyFile', [System.Management.Automation.ErrorCategory]::OperationStopped, $Path 42 | ) 43 | 44 | throw $newErrorRecord 45 | } 46 | } 47 | 48 | return $policyFile 49 | } 50 | 51 | function PolEntryToPsObject 52 | { 53 | param ( 54 | [TJX.PolFileEditor.PolEntry] $PolEntry 55 | ) 56 | 57 | $type = PolEntryTypeToRegistryValueKind $PolEntry.Type 58 | $data = GetEntryData -Entry $PolEntry -Type $type 59 | 60 | return New-Object psobject -Property @{ 61 | Key = $PolEntry.KeyName 62 | ValueName = $PolEntry.ValueName 63 | Type = $type 64 | Data = $data 65 | } 66 | } 67 | 68 | function GetEntryData 69 | { 70 | param ( 71 | [TJX.PolFileEditor.PolEntry] $Entry, 72 | [Microsoft.Win32.RegistryValueKind] $Type 73 | ) 74 | 75 | switch ($type) 76 | { 77 | ([Microsoft.Win32.RegistryValueKind]::Binary) 78 | { 79 | return $Entry.BinaryValue 80 | } 81 | 82 | ([Microsoft.Win32.RegistryValueKind]::DWord) 83 | { 84 | return $Entry.DWORDValue 85 | } 86 | 87 | ([Microsoft.Win32.RegistryValueKind]::ExpandString) 88 | { 89 | return $Entry.StringValue 90 | } 91 | 92 | ([Microsoft.Win32.RegistryValueKind]::MultiString) 93 | { 94 | return $Entry.MultiStringValue 95 | } 96 | 97 | ([Microsoft.Win32.RegistryValueKind]::QWord) 98 | { 99 | return $Entry.QWORDValue 100 | } 101 | 102 | ([Microsoft.Win32.RegistryValueKind]::String) 103 | { 104 | return $Entry.StringValue 105 | } 106 | } 107 | 108 | } 109 | 110 | function SavePolicyFile 111 | { 112 | [CmdletBinding(SupportsShouldProcess = $true)] 113 | param ( 114 | [Parameter(Mandatory = $true)] 115 | [TJX.PolFileEditor.PolFile] $PolicyFile, 116 | 117 | [switch] $UpdateGptIni 118 | ) 119 | 120 | if ($PSCmdlet.ShouldProcess($PolicyFile.FileName, 'Save new settings')) 121 | { 122 | $parentPath = Split-Path $PolicyFile.FileName -Parent 123 | if (-not (Test-Path -LiteralPath $parentPath -PathType Container)) 124 | { 125 | try 126 | { 127 | $null = New-Item -Path $parentPath -ItemType Directory -ErrorAction Stop -Confirm:$false -WhatIf:$false 128 | } 129 | catch 130 | { 131 | $errorRecord = $_ 132 | $message = "Error creating parent folder of path '$Path': $($errorRecord.Exception.Message)" 133 | $exception = New-Object System.Exception($message, $errorRecord.Exception) 134 | 135 | $newErrorRecord = New-Object System.Management.Automation.ErrorRecord( 136 | $exception, 'CreateParentFolderError', $errorRecord.CategoryInfo.Category, $Path 137 | ) 138 | 139 | throw $newErrorRecord 140 | } 141 | } 142 | 143 | try 144 | { 145 | $PolicyFile.SaveFile() 146 | } 147 | catch 148 | { 149 | $errorRecord = $_ 150 | $message = "Error saving policy file to path '$($PolicyFile.FileName)': $($errorRecord.Exception.Message)" 151 | $exception = New-Object System.Exception($message, $errorRecord.Exception) 152 | 153 | $newErrorRecord = New-Object System.Management.Automation.ErrorRecord( 154 | $exception, 'FailedToSavePolicyFile', [System.Management.Automation.ErrorCategory]::OperationStopped, $PolicyFile 155 | ) 156 | 157 | throw $newErrorRecord 158 | } 159 | } 160 | 161 | if ($UpdateGptIni) 162 | { 163 | if ($policyFile.FileName -match '^(.*)\\+([^\\]+)\\+[^\\]+$' -and 164 | $Matches[2] -eq 'User' -or $Matches[2] -eq 'Machine') 165 | { 166 | $iniPath = Join-Path $Matches[1] GPT.ini 167 | 168 | if (Test-Path -LiteralPath $iniPath -PathType Leaf) 169 | { 170 | if ($PSCmdlet.ShouldProcess($iniPath, 'Increment version number in INI file')) 171 | { 172 | IncrementGptIniVersion -Path $iniPath -PolicyType $Matches[2] -Confirm:$false -WhatIf:$false 173 | } 174 | } 175 | else 176 | { 177 | if ($PSCmdlet.ShouldProcess($iniPath, 'Create new gpt.ini file')) 178 | { 179 | NewGptIni -Path $iniPath -PolicyType $Matches[2] 180 | } 181 | } 182 | } 183 | } 184 | } 185 | 186 | function NewGptIni 187 | { 188 | param ( 189 | [string] $Path, 190 | [string[]] $PolicyType 191 | ) 192 | 193 | $parent = Split-Path $Path -Parent 194 | 195 | if (-not (Test-Path $parent -PathType Container)) 196 | { 197 | $null = New-Item -Path $parent -ItemType Directory -ErrorAction Stop 198 | } 199 | 200 | $version = GetNewVersionNumber -Version 0 -PolicyType $PolicyType 201 | 202 | Set-Content -Path $Path -Encoding Ascii -Value @" 203 | [General] 204 | gPCMachineExtensionNames=$script:MachineExtensionGuids 205 | Version=$version 206 | gPCUserExtensionNames=$script:UserExtensionGuids 207 | "@ 208 | } 209 | 210 | function IncrementGptIniVersion 211 | { 212 | [CmdletBinding(SupportsShouldProcess = $true)] 213 | param ( 214 | [string] $Path, 215 | [string[]] $PolicyType 216 | ) 217 | 218 | $foundVersionLine = $false 219 | $section = '' 220 | 221 | $newContents = @( 222 | foreach ($line in Get-Content $Path) 223 | { 224 | # This might not be the most unreadable regex ever, but it's trying hard to be! 225 | # It's looking for section lines: [SectionName] 226 | if ($line -match '^\s*\[([^\]]+)\]\s*$') 227 | { 228 | if ($section -eq 'General') 229 | { 230 | if (-not $foundVersionLine) 231 | { 232 | $foundVersionLine = $true 233 | $newVersion = GetNewVersionNumber -Version 0 -PolicyType $PolicyType 234 | 235 | "Version=$newVersion" 236 | } 237 | 238 | if (-not $foundMachineExtensionLine) 239 | { 240 | $foundMachineExtensionLine = $true 241 | "gPCMachineExtensionNames=$script:MachineExtensionGuids" 242 | } 243 | 244 | if (-not $foundUserExtensionLine) 245 | { 246 | $foundUserExtensionLine = $true 247 | "gPCUserExtensionNames=$script:UserExtensionGuids" 248 | } 249 | } 250 | 251 | $section = $matches[1] 252 | } 253 | elseif ($section -eq 'General' -and 254 | $line -match '^\s*Version\s*=\s*(\d+)\s*$' -and 255 | $null -ne ($version = $matches[1] -as [uint32])) 256 | { 257 | $foundVersionLine = $true 258 | $newVersion = GetNewVersionNumber -Version $version -PolicyType $PolicyType 259 | $line = "Version=$newVersion" 260 | } 261 | elseif ($section -eq 'General' -and $line -match '^\s*gPC(Machine|User)ExtensionNames\s*=') 262 | { 263 | if ($matches[1] -eq 'Machine') 264 | { 265 | $foundMachineExtensionLine = $true 266 | } 267 | else 268 | { 269 | $foundUserExtensionLine = $true 270 | } 271 | 272 | $line = EnsureAdminTemplateCseGuidsArePresent $line 273 | } 274 | 275 | $line 276 | } 277 | 278 | if ($section -eq 'General') 279 | { 280 | if (-not $foundVersionLine) 281 | { 282 | $foundVersionLine = $true 283 | $newVersion = GetNewVersionNumber -Version 0 -PolicyType $PolicyType 284 | 285 | "Version=$newVersion" 286 | } 287 | 288 | if (-not $foundMachineExtensionLine) 289 | { 290 | $foundMachineExtensionLine = $true 291 | "gPCMachineExtensionNames=$script:MachineExtensionGuids" 292 | } 293 | 294 | if (-not $foundUserExtensionLine) 295 | { 296 | $foundUserExtensionLine = $true 297 | "gPCUserExtensionNames=$script:UserExtensionGuids" 298 | } 299 | } 300 | ) 301 | 302 | if ($PSCmdlet.ShouldProcess($Path, 'Increment Version number')) 303 | { 304 | Set-Content -Path $Path -Value $newContents -Encoding Ascii -Confirm:$false -WhatIf:$false 305 | } 306 | } 307 | 308 | function EnsureAdminTemplateCseGuidsArePresent 309 | { 310 | param ([string] $Line) 311 | 312 | # These lines contain pairs of GUIDs in "registry" format (with the curly braces), separated by nothing, with 313 | # each pair of GUIDs wrapped in square brackets. Example: 314 | 315 | # gPCMachineExtensionNames=[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F72-3407-48AE-BA88-E8213C6761F1}] 316 | 317 | # Per Darren Mar-Elia, these GUIDs must be in alphabetical order, or GP processing will have problems. 318 | 319 | if ($Line -notmatch '\s*(gPC(?:Machine|User)ExtensionNames)\s*=\s*(.*)$') 320 | { 321 | throw "Malformed gpt.ini line: $Line" 322 | } 323 | 324 | $valueName = $matches[1] 325 | $guidStrings = @($matches[2] -split '(?<=\])(?=\[)') 326 | 327 | if ($matches[1] -eq 'gPCMachineExtensionNames') 328 | { 329 | $toolExtensionGuid = $script:MachineExtensionGuids 330 | } 331 | else 332 | { 333 | $toolExtensionGuid = $script:UserExtensionGuids 334 | } 335 | 336 | $guidList = @( 337 | $guidStrings 338 | $toolExtensionGuid 339 | ) 340 | 341 | $newGuidString = ($guidList | Sort-Object -Unique) -join '' 342 | 343 | return "$valueName=$newGuidString" 344 | } 345 | 346 | function GetNewVersionNumber 347 | { 348 | param ( 349 | [UInt32] $Version, 350 | [string[]] $PolicyType 351 | ) 352 | 353 | # User version is the high 16 bits, Machine version is the low 16 bits. 354 | # Reference: http://blogs.technet.com/b/grouppolicy/archive/2007/12/14/understanding-the-gpo-version-number.aspx 355 | 356 | $pair = UInt32ToUInt16Pair -UInt32 $version 357 | 358 | if ($PolicyType -contains 'User') 359 | { 360 | $pair.HighPart++ 361 | } 362 | 363 | if ($PolicyType -contains 'Machine') 364 | { 365 | $pair.LowPart++ 366 | } 367 | 368 | return UInt16PairToUInt32 -UInt16Pair $pair 369 | } 370 | 371 | function UInt32ToUInt16Pair 372 | { 373 | param ([UInt32] $UInt32) 374 | 375 | # Deliberately avoiding bitwise shift operators here, for PowerShell v2 compatibility. 376 | 377 | $lowPart = $UInt32 -band 0xFFFF 378 | $highPart = ($UInt32 - $lowPart) / 0x10000 379 | 380 | return New-Object psobject -Property @{ 381 | LowPart = [UInt16] $lowPart 382 | HighPart = [UInt16] $highPart 383 | } 384 | } 385 | 386 | function UInt16PairToUInt32 387 | { 388 | param ([object] $UInt16Pair) 389 | 390 | # Deliberately avoiding bitwise shift operators here, for PowerShell v2 compatibility. 391 | 392 | return ([UInt32] $UInt16Pair.HighPart) * 0x10000 + $UInt16Pair.LowPart 393 | } 394 | 395 | function PolEntryTypeToRegistryValueKind 396 | { 397 | param ([TJX.PolFileEditor.PolEntryType] $PolEntryType) 398 | 399 | switch ($PolEntryType) 400 | { 401 | ([TJX.PolFileEditor.PolEntryType]::REG_NONE) 402 | { 403 | return [Microsoft.Win32.RegistryValueKind]::None 404 | } 405 | 406 | ([TJX.PolFileEditor.PolEntryType]::REG_DWORD) 407 | { 408 | return [Microsoft.Win32.RegistryValueKind]::DWord 409 | } 410 | 411 | ([TJX.PolFileEditor.PolEntryType]::REG_DWORD_BIG_ENDIAN) 412 | { 413 | return [Microsoft.Win32.RegistryValueKind]::DWord 414 | } 415 | 416 | ([TJX.PolFileEditor.PolEntryType]::REG_BINARY) 417 | { 418 | return [Microsoft.Win32.RegistryValueKind]::Binary 419 | } 420 | 421 | ([TJX.PolFileEditor.PolEntryType]::REG_EXPAND_SZ) 422 | { 423 | return [Microsoft.Win32.RegistryValueKind]::ExpandString 424 | } 425 | 426 | ([TJX.PolFileEditor.PolEntryType]::REG_MULTI_SZ) 427 | { 428 | return [Microsoft.Win32.RegistryValueKind]::MultiString 429 | } 430 | 431 | ([TJX.PolFileEditor.PolEntryType]::REG_QWORD) 432 | { 433 | return [Microsoft.Win32.RegistryValueKind]::QWord 434 | } 435 | 436 | ([TJX.PolFileEditor.PolEntryType]::REG_SZ) 437 | { 438 | return [Microsoft.Win32.RegistryValueKind]::String 439 | } 440 | } 441 | } 442 | 443 | function GetPolFilePath 444 | { 445 | param ( 446 | [Parameter(Mandatory = $true, ParameterSetName = 'PolicyType')] 447 | [string] $PolicyType, 448 | 449 | [Parameter(Mandatory = $true, ParameterSetName = 'Account')] 450 | [string] $Account 451 | ) 452 | 453 | if ($PolicyType) 454 | { 455 | switch ($PolicyType) 456 | { 457 | 'Machine' 458 | { 459 | return Join-Path $env:SystemRoot System32\GroupPolicy\Machine\registry.pol 460 | } 461 | 462 | 'User' 463 | { 464 | return Join-Path $env:SystemRoot System32\GroupPolicy\User\registry.pol 465 | } 466 | 467 | 'Administrators' 468 | { 469 | # BUILTIN\Administrators well-known SID 470 | return Join-Path $env:SystemRoot System32\GroupPolicyUsers\S-1-5-32-544\User\registry.pol 471 | } 472 | 473 | 'NonAdministrators' 474 | { 475 | # BUILTIN\Users well-known SID 476 | return Join-Path $env:SystemRoot System32\GroupPolicyUsers\S-1-5-32-545\User\registry.pol 477 | } 478 | } 479 | } 480 | else 481 | { 482 | try 483 | { 484 | $sid = $Account -as [System.Security.Principal.SecurityIdentifier] 485 | 486 | if ($null -eq $sid) 487 | { 488 | $sid = GetSidForAccount $Account 489 | } 490 | 491 | return Join-Path $env:SystemRoot "System32\GroupPolicyUsers\$($sid.Value)\User\registry.pol" 492 | } 493 | catch 494 | { 495 | throw 496 | } 497 | } 498 | } 499 | 500 | function GetSidForAccount($Account) 501 | { 502 | $acc = $Account 503 | if ($acc -notlike '*\*') { $acc = "$env:COMPUTERNAME\$acc" } 504 | 505 | try 506 | { 507 | $ntAccount = [System.Security.Principal.NTAccount]$acc 508 | return $ntAccount.Translate([System.Security.Principal.SecurityIdentifier]) 509 | } 510 | catch 511 | { 512 | $message = "Could not translate account '$acc' to a security identifier." 513 | $exception = New-Object System.Exception($message, $_.Exception) 514 | $errorRecord = New-Object System.Management.Automation.ErrorRecord( 515 | $exception, 516 | 'CouldNotGetSidForAccount', 517 | [System.Management.Automation.ErrorCategory]::ObjectNotFound, 518 | $Acc 519 | ) 520 | 521 | throw $errorRecord 522 | } 523 | } 524 | 525 | function DataIsEqual 526 | { 527 | param ( 528 | [object] $First, 529 | [object] $Second, 530 | [Microsoft.Win32.RegistryValueKind] $Type 531 | ) 532 | 533 | if ($Type -eq [Microsoft.Win32.RegistryValueKind]::String -or 534 | $Type -eq [Microsoft.Win32.RegistryValueKind]::ExpandString -or 535 | $Type -eq [Microsoft.Win32.RegistryValueKind]::DWord -or 536 | $Type -eq [Microsoft.Win32.RegistryValueKind]::QWord) 537 | { 538 | return @($First)[0] -ceq @($Second)[0] 539 | } 540 | 541 | # If we get here, $Type is either MultiString or Binary, both of which need to compare arrays. 542 | # The PolicyFileEditor module never returns type Unknown or None. 543 | 544 | $First = @($First) 545 | $Second = @($Second) 546 | 547 | if ($First.Count -ne $Second.Count) { return $false } 548 | 549 | $count = $First.Count 550 | for ($i = 0; $i -lt $count; $i++) 551 | { 552 | if ($First[$i] -cne $Second[$i]) { return $false } 553 | } 554 | 555 | return $true 556 | } 557 | 558 | function ParseKeyValueName 559 | { 560 | param ([string] $KeyValueName) 561 | 562 | $key = $KeyValueName -replace '^\\+|\\+$' 563 | $valueName = '' 564 | 565 | if ($KeyValueName -match '^\\*(?.+?)\\+(?[^\\]*)$') 566 | { 567 | $key = $matches['Key'] -replace '\\{2,}', '\' 568 | $valueName = $matches['ValueName'] 569 | } 570 | 571 | return $key, $valueName 572 | } 573 | 574 | function GetTargetResourceCommon 575 | { 576 | param ( 577 | [string] $Path, 578 | [string] $KeyValueName 579 | ) 580 | 581 | $configuration = @{ 582 | KeyValueName = $KeyValueName 583 | Ensure = 'Absent' 584 | Data = $null 585 | Type = [Microsoft.Win32.RegistryValueKind]::Unknown 586 | } 587 | 588 | if (Test-Path -LiteralPath $path -PathType Leaf) 589 | { 590 | $key, $valueName = ParseKeyValueName $KeyValueName 591 | $entry = Get-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName 592 | 593 | if ($entry) 594 | { 595 | $configuration['Ensure'] = 'Present' 596 | $configuration['Type'] = $entry.Type 597 | $configuration['Data'] = @($entry.Data) 598 | } 599 | } 600 | 601 | return $configuration 602 | } 603 | 604 | function SetTargetResourceCommon 605 | { 606 | param ( 607 | [string] $Path, 608 | [string] $KeyValueName, 609 | [string] $Ensure, 610 | [string[]] $Data, 611 | [Microsoft.Win32.RegistryValueKind] $Type 612 | ) 613 | 614 | if ($null -eq $Data) { $Data = @() } 615 | 616 | try 617 | { 618 | Assert-ValidDataAndType -Data $Data -Type $Type 619 | } 620 | catch 621 | { 622 | Write-Error -ErrorRecord $_ 623 | return 624 | } 625 | 626 | $key, $valueName = ParseKeyValueName $KeyValueName 627 | 628 | if ($Ensure -eq 'Present') 629 | { 630 | Set-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName -Data $Data -Type $Type 631 | } 632 | else 633 | { 634 | Remove-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName 635 | } 636 | } 637 | 638 | function TestTargetResourceCommon 639 | { 640 | [OutputType([bool])] 641 | param ( 642 | [string] $Path, 643 | [string] $KeyValueName, 644 | [string] $Ensure, 645 | [string[]] $Data, 646 | [Microsoft.Win32.RegistryValueKind] $Type 647 | ) 648 | 649 | if ($null -eq $Data) { $Data = @() } 650 | 651 | try 652 | { 653 | Assert-ValidDataAndType -Data $Data -Type $Type 654 | } 655 | catch 656 | { 657 | Write-Error -ErrorRecord $_ 658 | return $false 659 | } 660 | 661 | $key, $valueName = ParseKeyValueName $KeyValueName 662 | 663 | $fileExists = Test-Path -LiteralPath $Path -PathType Leaf 664 | 665 | if ($Ensure -eq 'Present') 666 | { 667 | if (-not $fileExists) { return $false } 668 | $entry = Get-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName 669 | 670 | return $null -ne $entry -and $Type -eq $entry.Type -and (DataIsEqual $entry.Data $Data -Type $Type) 671 | } 672 | else # Ensure is 'Absent' 673 | { 674 | if (-not $fileExists) { return $true } 675 | $entry = Get-PolicyFileEntry -Path $Path -Key $key -ValueName $valueName 676 | 677 | return $null -eq $entry 678 | } 679 | 680 | } 681 | 682 | function Assert-ValidDataAndType 683 | { 684 | param ( 685 | [string[]] $Data, 686 | [Microsoft.Win32.RegistryValueKind] $Type 687 | ) 688 | 689 | if ($Type -ne [Microsoft.Win32.RegistryValueKind]::MultiString -and 690 | $Type -ne [Microsoft.Win32.RegistryValueKind]::Binary -and 691 | $Data.Count -gt 1) 692 | { 693 | $errorRecord = InvalidDataTypeCombinationErrorRecord -Message 'Do not pass arrays with multiple values to the -Data parameter when -Type is not set to either Binary or MultiString.' 694 | throw $errorRecord 695 | } 696 | } 697 | 698 | function InvalidDataTypeCombinationErrorRecord($Message) 699 | { 700 | $exception = New-Object System.Exception($Message) 701 | return New-Object System.Management.Automation.ErrorRecord( 702 | $exception, 'InvalidDataTypeCombination', [System.Management.Automation.ErrorCategory]::InvalidArgument, $null 703 | ) 704 | } 705 | -------------------------------------------------------------------------------- /DscResources/PshOrg_AccountAdminTemplateSetting/PshOrg_AccountAdminTemplateSetting.Tests.ps1: -------------------------------------------------------------------------------- 1 | <# 2 | Most of the tests we need are already taken care of in PshOrg_AdminTemplateSetting. 3 | The only difference between the two resources is that AccountAdminTemplateSetting calls 4 | GetPolFilePath with the -Account parameter instead of the -PolicyType parameter. 5 | 6 | Rather than going through the motions of testing the *-TargetResource methods here, 7 | we'll just unit test the GetPolFilePath function instead. 8 | #> 9 | 10 | . "$PSScriptRoot\..\..\Common.ps1" 11 | 12 | Describe 'GetPolFilePath with -Account parameter' { 13 | It 'Returns the proper path for a well-known SID' { 14 | $actual = GetPolFilePath -Account BUILTIN\Administrators 15 | $expected = Join-Path $env:SystemRoot System32\GroupPolicyUsers\S-1-5-32-544\User\registry.pol 16 | $actual | Should Be $expected 17 | } 18 | 19 | It 'Returns the proper path for a local account' { 20 | $computer = [adsi]"WinNT://$env:COMPUTERNAME" 21 | $user = $computer.Children | 22 | Where SchemaClassName -eq User | 23 | Select -First 1 24 | 25 | $sid = New-Object System.Security.Principal.SecurityIdentifier($user.objectSid[0], 0) 26 | 27 | $actual = GetPolFilePath -Account $user.Name[0] 28 | $expected = Join-Path $env:SystemRoot System32\GroupPolicyUsers\$($sid.Value)\User\registry.pol 29 | 30 | $actual | Should Be $expected 31 | } 32 | 33 | It 'Allows a SID string to be passed directly' { 34 | $actual = GetPolFilePath -Account S-1-5-32-544 35 | $expected = Join-Path $env:SystemRoot System32\GroupPolicyUsers\S-1-5-32-544\User\registry.pol 36 | $actual | Should Be $expected 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /DscResources/PshOrg_AccountAdminTemplateSetting/PshOrg_AccountAdminTemplateSetting.psm1: -------------------------------------------------------------------------------- 1 | Add-Type -Path $PSScriptRoot\..\..\PolFileEditor.dll -ErrorAction Stop 2 | . "$PSScriptRoot\..\..\Commands.ps1" 3 | 4 | function Get-TargetResource 5 | { 6 | [OutputType([hashtable])] 7 | param ( 8 | [Parameter(Mandatory)] 9 | [string] $Account, 10 | 11 | [Parameter(Mandatory)] 12 | [string] $KeyValueName 13 | ) 14 | 15 | try 16 | { 17 | $path = GetPolFilePath -Account $Account -ErrorAction Stop 18 | 19 | $hashTable = GetTargetResourceCommon -Path $path -KeyValueName $KeyValueName 20 | $hashTable['Account'] = $Account 21 | 22 | return $hashTable 23 | } 24 | catch 25 | { 26 | Write-Error -ErrorRecord $_ 27 | return 28 | } 29 | } 30 | 31 | function Set-TargetResource 32 | { 33 | param ( 34 | [Parameter(Mandatory)] 35 | [string] $Account, 36 | 37 | [Parameter(Mandatory)] 38 | [string] $KeyValueName, 39 | 40 | [ValidateSet('Present', 'Absent')] 41 | [string] $Ensure = 'Present', 42 | 43 | [string[]] $Data, 44 | 45 | [Microsoft.Win32.RegistryValueKind] $Type = [Microsoft.Win32.RegistryValueKind]::String 46 | ) 47 | 48 | try 49 | { 50 | $path = GetPolFilePath -Account $Account -ErrorAction Stop 51 | SetTargetResourceCommon -Path $path -KeyValueName $KeyValueName -Ensure $Ensure -Data $Data -Type $Type 52 | } 53 | catch 54 | { 55 | Write-Error -ErrorRecord $_ 56 | return 57 | } 58 | } 59 | 60 | function Test-TargetResource 61 | { 62 | [OutputType([bool])] 63 | param ( 64 | [Parameter(Mandatory)] 65 | [string] $Account, 66 | 67 | [Parameter(Mandatory)] 68 | [string] $KeyValueName, 69 | 70 | [ValidateSet('Present', 'Absent')] 71 | [string] $Ensure = 'Present', 72 | 73 | [string[]] $Data, 74 | 75 | [Microsoft.Win32.RegistryValueKind] $Type = [Microsoft.Win32.RegistryValueKind]::String 76 | ) 77 | 78 | try 79 | { 80 | $path = GetPolFilePath -Account $Account -ErrorAction Stop 81 | return TestTargetResourceCommon -Path $path -KeyValueName $KeyValueName -Ensure $Ensure -Data $Data -Type $Type 82 | } 83 | catch 84 | { 85 | Write-Error -ErrorRecord $_ 86 | return 87 | } 88 | } 89 | 90 | Export-ModuleMember Get-TargetResource, Test-TargetResource, Set-TargetResource 91 | -------------------------------------------------------------------------------- /DscResources/PshOrg_AccountAdminTemplateSetting/PshOrg_AccountAdminTemplateSetting.schema.mof: -------------------------------------------------------------------------------- 1 | [ClassVersion("2"), FriendlyName("cAccountAdministrativeTemplateSetting")] 2 | class PshOrg_AccountAdminTemplateSetting : OMI_BaseResource 3 | { 4 | [Key] string Account; 5 | [Key] string KeyValueName; 6 | [write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] string Ensure; 7 | [write] string Data[]; 8 | [write,ValueMap{"Unknown", "String", "ExpandString", "Binary", "DWord", "MultiString", "QWord", "None"},Values{"Unknown","String","ExpandString","Binary","DWord","MultiString","QWord","None"}] string Type; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /DscResources/PshOrg_AdminTemplateSetting/PshOrg_AdminTemplateSetting.Tests.ps1: -------------------------------------------------------------------------------- 1 | $modulePath = $PSCommandPath -replace '\.Tests\.ps1$', '.psm1' 2 | $prefix = [guid]::NewGuid().Guid -replace '[^a-f\d]' 3 | 4 | $module = $null 5 | 6 | try 7 | { 8 | $module = Import-Module $modulePath -PassThru -Prefix $prefix -ErrorAction Stop 9 | 10 | InModuleScope $module.Name { 11 | Describe 'Get-TargetResource' { 12 | Mock Test-Path { $true } -ParameterFilter { $LiteralPath -like "$env:SystemRoot\system32\GroupPolicy\*\registry.pol" } 13 | 14 | Context 'When the value is present' { 15 | $key = 'Software\Testing' 16 | $valueName = 'TestValue' 17 | $data = [uint32]12345 18 | $type = [Microsoft.Win32.RegistryValueKind]::DWord 19 | 20 | Mock Get-PolicyFileEntry { 21 | return New-Object psobject -Property @{ 22 | ValueName = $valueName 23 | Key = $key 24 | Data = $data 25 | Type = $type 26 | } 27 | } 28 | 29 | It 'Returns the proper state' { 30 | $hashtable = Get-TargetResource -PolicyType Machine -KeyValueName "$key\$valueName" 31 | 32 | $hashtable.PSBase.Count | Should Be 5 33 | $hashtable['PolicyType'] | Should Be Machine 34 | $hashtable['Ensure'] | Should Be 'Present' 35 | $hashtable['KeyValueName'] | Should Be "$key\$valueName" 36 | $hashtable['Data'] | Should Be $data 37 | $hashtable['Type'] | Should Be $type 38 | } 39 | } 40 | 41 | Context 'When the value is absent' { 42 | $key = 'Software\Testing' 43 | $valueName = 'TestValue' 44 | 45 | Mock Get-PolicyFileEntry { } 46 | 47 | It 'Returns the proper state' { 48 | $hashtable = Get-TargetResource -PolicyType Machine -KeyValueName "$key\$valueName" 49 | 50 | $hashtable.PSBase.Count | Should Be 5 51 | $hashtable['PolicyType'] | Should Be Machine 52 | $hashtable['Ensure'] | Should Be 'Absent' 53 | $hashtable['KeyValueName'] | Should Be "$key\$valueName" 54 | $hashtable['Data'] | Should Be $null 55 | $hashtable['Type'] | Should Be ([Microsoft.Win32.RegistryValueKind]::Unknown) 56 | } 57 | } 58 | } 59 | 60 | Describe 'Test-TargetResource' { 61 | # Using a hashtable here to avoid variable naming collisions with the function parameter names 62 | # (Sometimes a danger when using InModuleScope) 63 | 64 | $mockValues = @{ 65 | key = 'Software\Testing' 66 | valueName = 'TestValue' 67 | data = [uint32]12345 68 | type = [Microsoft.Win32.RegistryValueKind]::DWord 69 | } 70 | 71 | Mock Test-Path { $true } -ParameterFilter { $LiteralPath -like "$env:SystemRoot\system32\GroupPolicy\*\registry.pol" } 72 | 73 | Mock Get-PolicyFileEntry { 74 | return New-Object psobject -Property @{ 75 | ValueName = $mockValues.valueName 76 | Key = $mockValues.key 77 | Data = $mockValues.data 78 | Type = $mockValues.type 79 | } 80 | } 81 | 82 | It 'Returns true when the system is in the proper state' { 83 | $result = Test-TargetResource -PolicyType Machine ` 84 | -KeyValueName "$($mockValues.key)\$($mockValues.valueName)" ` 85 | -Ensure 'Present' ` 86 | -Data $mockValues.data ` 87 | -Type $mockValues.type 88 | 89 | $result | Should Be $true 90 | } 91 | 92 | It 'Returns false if the Data does not match' { 93 | $result = Test-TargetResource -PolicyType Machine ` 94 | -KeyValueName "$($mockValues.key)\$($mockValues.valueName)" ` 95 | -Ensure 'Present' ` 96 | -Data BogusData ` 97 | -Type $mockValues.type 98 | 99 | $result | Should Be $false 100 | } 101 | 102 | It 'Returns false if the Type does not match' { 103 | $result = Test-TargetResource -PolicyType Machine ` 104 | -KeyValueName "$($mockValues.key)\$($mockValues.valueName)" ` 105 | -Ensure 'Present' ` 106 | -Data $mockValues.data ` 107 | -Type ([Microsoft.Win32.RegistryValueKind]::QWord) 108 | 109 | $result | Should Be $false 110 | } 111 | 112 | Mock Get-PolicyFileEntry { } 113 | 114 | It 'Returns false when the entry is not found' { 115 | $result = Test-TargetResource -PolicyType Machine ` 116 | -KeyValueName "$($mockValues.key)\$($mockValues.valueName)" ` 117 | -Ensure 'Present' ` 118 | -Data $mockValues.data ` 119 | -Type $mockValues.type 120 | 121 | $result | Should Be $false 122 | } 123 | } 124 | 125 | Describe 'Set-TargetResource' { 126 | # Using a hashtable here to avoid variable naming collisions with the function parameter names 127 | # (Sometimes a danger when using InModuleScope) 128 | 129 | $values = @{ 130 | key = 'Software\Testing' 131 | valueName = 'TestValue' 132 | data = [uint32]12345 133 | type = [Microsoft.Win32.RegistryValueKind]::DWord 134 | } 135 | 136 | Mock Test-Path { $true } -ParameterFilter { $LiteralPath -like "$env:SystemRoot\system32\GroupPolicy\*\registry.pol" } 137 | Mock Set-PolicyFileEntry 138 | Mock Remove-PolicyFileEntry 139 | 140 | It 'Calls Set-PolicyFileEntry when Ensure is set to Present' { 141 | Set-TargetResource -PolicyType Machine ` 142 | -KeyValueName "$($values.key)\$($values.valueName)" ` 143 | -Ensure 'Present' ` 144 | -Data $values.data ` 145 | -Type $values.type 146 | 147 | Assert-MockCalled Set-PolicyFileEntry -Scope It -ParameterFilter { 148 | $Key -eq $values.key -and 149 | $ValueName -eq $values.valueName -and 150 | $Data -eq $values.data -and 151 | $Type -eq $values.type 152 | } 153 | 154 | Assert-MockCalled Remove-PolicyFileEntry -Scope It -Times 0 155 | } 156 | 157 | It 'Calls Remove-PolicyFileEntry when Ensure is set to Absent' { 158 | Set-TargetResource -PolicyType Machine ` 159 | -KeyValueName "$($values.key)\$($values.valueName)" ` 160 | -Ensure 'Absent' 161 | 162 | Assert-MockCalled Remove-PolicyFileEntry -Scope It -ParameterFilter { 163 | $Key -eq $values.key -and 164 | $ValueName -eq $values.valueName 165 | } 166 | 167 | Assert-MockCalled Set-PolicyFileEntry -Scope It -Times 0 168 | } 169 | } 170 | } 171 | } 172 | finally 173 | { 174 | if ($module) { Remove-Module -ModuleInfo $module } 175 | } 176 | -------------------------------------------------------------------------------- /DscResources/PshOrg_AdminTemplateSetting/PshOrg_AdminTemplateSetting.psm1: -------------------------------------------------------------------------------- 1 | Add-Type -Path $PSScriptRoot\..\..\PolFileEditor.dll -ErrorAction Stop 2 | . "$PSScriptRoot\..\..\Commands.ps1" 3 | 4 | function Get-TargetResource 5 | { 6 | [OutputType([hashtable])] 7 | param ( 8 | [Parameter(Mandatory)] 9 | [ValidateSet('Machine', 'User', 'Administrators', 'NonAdministrators')] 10 | [string] $PolicyType, 11 | 12 | [Parameter(Mandatory)] 13 | [string] $KeyValueName 14 | ) 15 | 16 | try 17 | { 18 | $path = GetPolFilePath -PolicyType $PolicyType 19 | $hashTable = GetTargetResourceCommon -Path $path -KeyValueName $KeyValueName 20 | $hashTable['PolicyType'] = $PolicyType 21 | 22 | return $hashTable 23 | } 24 | catch 25 | { 26 | Write-Error -ErrorRecord $_ 27 | return 28 | } 29 | } 30 | 31 | function Set-TargetResource 32 | { 33 | param ( 34 | [Parameter(Mandatory)] 35 | [ValidateSet('Machine', 'User', 'Administrators', 'NonAdministrators')] 36 | [string] $PolicyType, 37 | 38 | [Parameter(Mandatory)] 39 | [string] $KeyValueName, 40 | 41 | [ValidateSet('Present', 'Absent')] 42 | [string] $Ensure = 'Present', 43 | 44 | [string[]] $Data, 45 | 46 | [Microsoft.Win32.RegistryValueKind] $Type = [Microsoft.Win32.RegistryValueKind]::String 47 | ) 48 | 49 | try 50 | { 51 | $path = GetPolFilePath -PolicyType $PolicyType 52 | SetTargetResourceCommon -Path $path -KeyValueName $KeyValueName -Ensure $Ensure -Data $Data -Type $Type 53 | } 54 | catch 55 | { 56 | Write-Error -ErrorRecord $_ 57 | return 58 | } 59 | } 60 | 61 | function Test-TargetResource 62 | { 63 | [OutputType([bool])] 64 | param ( 65 | [Parameter(Mandatory)] 66 | [ValidateSet('Machine', 'User', 'Administrators', 'NonAdministrators')] 67 | [string] $PolicyType, 68 | 69 | [Parameter(Mandatory)] 70 | [string] $KeyValueName, 71 | 72 | [ValidateSet('Present', 'Absent')] 73 | [string] $Ensure = 'Present', 74 | 75 | [string[]] $Data, 76 | 77 | [Microsoft.Win32.RegistryValueKind] $Type = [Microsoft.Win32.RegistryValueKind]::String 78 | ) 79 | 80 | try 81 | { 82 | $path = GetPolFilePath -PolicyType $PolicyType 83 | return TestTargetResourceCommon -Path $path -KeyValueName $KeyValueName -Ensure $Ensure -Data $Data -Type $Type 84 | } 85 | catch 86 | { 87 | Write-Error -ErrorRecord $_ 88 | return 89 | } 90 | } 91 | 92 | Export-ModuleMember Get-TargetResource, Test-TargetResource, Set-TargetResource 93 | -------------------------------------------------------------------------------- /DscResources/PshOrg_AdminTemplateSetting/PshOrg_AdminTemplateSetting.schema.mof: -------------------------------------------------------------------------------- 1 | [ClassVersion("2"), FriendlyName("cAdministrativeTemplateSetting")] 2 | class PshOrg_AdminTemplateSetting : OMI_BaseResource 3 | { 4 | [Key,ValueMap{"Machine", "User", "Administrators", "NonAdministrators"},Values{"Machine", "User", "Administrators", "NonAdministrators"}] string PolicyType; 5 | [Key] string KeyValueName; 6 | [write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] string Ensure; 7 | [write] string Data[]; 8 | [write,ValueMap{"Unknown", "String", "ExpandString", "Binary", "DWord", "MultiString", "QWord", "None"},Values{"Unknown","String","ExpandString","Binary","DWord","MultiString","QWord","None"}] string Type; 9 | }; 10 | 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /PolFileEditor.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dlwyatt/PolicyFileEditor/6de41e597e403ac1747fd24fa4bd61e6897d940e/PolFileEditor.dll -------------------------------------------------------------------------------- /PolicyFileEditor.Tests.ps1: -------------------------------------------------------------------------------- 1 | Remove-Module [P]olicyFileEditor 2 | $scriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent 3 | $psd1Path = Join-Path $scriptRoot PolicyFileEditor.psd1 4 | 5 | $module = $null 6 | 7 | function CreateDefaultGpo($Path) 8 | { 9 | $paths = @( 10 | $Path 11 | Join-Path $Path Machine 12 | Join-Path $Path User 13 | ) 14 | 15 | foreach ($p in $paths) 16 | { 17 | if (-not (Test-Path $p -PathType Container)) 18 | { 19 | New-Item -Path $p -ItemType Directory -ErrorAction Stop 20 | } 21 | } 22 | 23 | $content = @' 24 | [General] 25 | gPCMachineExtensionNames=[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F72-3407-48AE-BA88-E8213C6761F1}] 26 | Version=65537 27 | gPCUserExtensionNames=[{35378EAC-683F-11D2-A89A-00C04FBBCFA2}{D02B1F73-3407-48AE-BA88-E8213C6761F1}] 28 | '@ 29 | 30 | $gptIniPath = Join-Path $Path gpt.ini 31 | Set-Content -Path $gptIniPath -ErrorAction Stop -Encoding Ascii -Value $content 32 | 33 | Get-ChildItem -Path $Path -Include registry.pol -Force | Remove-Item -Force 34 | } 35 | 36 | function GetGptIniVersion($Path) 37 | { 38 | foreach ($result in Select-String -Path $Path -Pattern '^\s*Version\s*=\s*(\d+)\s*$') 39 | { 40 | foreach ($match in $result.Matches) 41 | { 42 | $match.Groups[1].Value 43 | } 44 | } 45 | } 46 | 47 | try 48 | { 49 | $module = Import-Module $psd1Path -ErrorAction Stop -PassThru -Force 50 | $gpoPath = 'TestDrive:\TestGpo' 51 | $gptIniPath = "$gpoPath\gpt.ini" 52 | 53 | Describe 'KeyValueName parsing' { 54 | InModuleScope PolicyFileEditor { 55 | $testCases = @( 56 | @{ 57 | KeyValueName = 'Left\Right' 58 | ExpectedKey = 'Left' 59 | ExpectedValue = 'Right' 60 | Description = 'Simple' 61 | } 62 | 63 | @{ 64 | KeyValueName = 'Left\\Right' 65 | ExpectedKey = 'Left' 66 | ExpectedValue = 'Right' 67 | Description = 'Multiple consecutive separators' 68 | } 69 | 70 | @{ 71 | KeyValueName = '\Left\Right' 72 | ExpectedKey = 'Left' 73 | ExpectedValue = 'Right' 74 | Description = 'Leading separator' 75 | } 76 | 77 | @{ 78 | KeyValueName = 'Left\Right\' 79 | ExpectedKey = 'Left\Right' 80 | ExpectedValue = '' 81 | Description = 'Trailing separator' 82 | } 83 | 84 | @{ 85 | KeyValueName = '\\\Left\\\\Right\\\\\' 86 | ExpectedKey = 'Left\Right' 87 | ExpectedValue = '' 88 | Description = 'Ridiculous with trailing separator' 89 | } 90 | 91 | @{ 92 | KeyValueName = '\\\\\\\\Left\\\\\\\Right' 93 | ExpectedKey = 'Left' 94 | ExpectedValue = 'Right' 95 | Description = 'Ridiculous with no trailing separator' 96 | } 97 | ) 98 | 99 | It -TestCases $testCases 'Properly parses KeyValueName with ' { 100 | param ($KeyValueName, $ExpectedKey, $ExpectedValue) 101 | $key, $valueName = ParseKeyValueName $KeyValueName 102 | 103 | $key | Should Be $ExpectedKey 104 | $valueName | Should Be $ExpectedValue 105 | } 106 | } 107 | } 108 | 109 | Describe 'Happy Path' { 110 | BeforeEach { 111 | CreateDefaultGpo -Path $gpoPath 112 | } 113 | 114 | Context 'Incrementing GPT.Ini version' { 115 | # User version is the high 16 bits, Machine version is the low 16 bits. 116 | # Reference: http://blogs.technet.com/b/grouppolicy/archive/2007/12/14/understanding-the-gpo-version-number.aspx 117 | 118 | # Default value set in our CreateDefaultGpo function is 65537, or (1 -shl 16) + 1 ; Machine and User version both set to 1. 119 | # Decimal values ard hard-coded here so we can run the tests on PowerShell v2, which didn't have the -shl / -shr operators. 120 | # This puts the module's internal code which replaces these operators through a test as well. 121 | 122 | $testCases = @( 123 | @{ 124 | PolicyType = 'Machine' 125 | Expected = '65538' # (1 -shl 16) + 2 126 | } 127 | 128 | @{ 129 | PolicyType = 'User' 130 | Expected = '131073' # (2 -shl 16) + 1 131 | } 132 | 133 | @{ 134 | PolicyType = 'Machine', 'User' 135 | Expected = '131074' # (2 -shl 16) + 2 136 | } 137 | ) 138 | 139 | It 'Sets the correct value for updates' -TestCases $testCases { 140 | param ($PolicyType, $Expected) 141 | 142 | Update-GptIniVersion -Path $gptIniPath -PolicyType $PolicyType 143 | $version = @(GetGptIniVersion -Path $gptIniPath) 144 | 145 | $version.Count | Should Be 1 146 | $actual = $version[0] 147 | 148 | $actual | Should Be $Expected 149 | } 150 | } 151 | 152 | Context 'Automated modification of gpt.ini' { 153 | # These tests incidentally also cover the happy path functionality of 154 | # Set-PolicyFileEntry and Remove-PolicyFileEntry. We'll cover errors 155 | # in a different section. 156 | 157 | $testCases = @( 158 | @{ 159 | PolicyType = 'Machine' 160 | ExpectedVersions = '65538', '65539' # (1 -shl 16) + 2, (1 -shl 16) + 2 161 | NoGptIniUpdate = $false 162 | Count = 1 163 | } 164 | 165 | @{ 166 | PolicyType = 'User' 167 | ExpectedVersions = '131073', '196609' # (2 -shl 16) + 1, (3 -shl 16) + 1 168 | NoGptIniUpdate = $false 169 | Count = 1 170 | } 171 | 172 | @{ 173 | PolicyType = 'Machine' 174 | ExpectedVersions = '65537', '65537' # (1 -shl 16) + 1, (1 -shl 16) + 1 175 | NoGptIniUpdate = $true 176 | Count = 1 177 | } 178 | 179 | @{ 180 | PolicyType = 'User' 181 | ExpectedVersions = '65537', '65537' # (1 -shl 16) + 1, (1 -shl 16) + 1 182 | NoGptIniUpdate = $true 183 | Count = 1 184 | } 185 | 186 | @{ 187 | PolicyType = 'User' 188 | ExpectedVersions = '131073', '196609' # (2 -shl 16) + 1, (3 -shl 16) + 1 189 | NoGptIniUpdate = $false 190 | Count = 2 191 | EntriesToModify = @( 192 | New-Object psobject -Property @{ 193 | Key = 'Software\Testing' 194 | ValueName = 'Value1' 195 | Type = 'String' 196 | Data = 'Data' 197 | } 198 | 199 | New-Object psobject -Property @{ 200 | Key = 'Software\Testing' 201 | ValueName = 'Value2' 202 | Type = 'MultiString' 203 | Data = 'Multi', 'String', 'Data' 204 | } 205 | ) 206 | } 207 | ) 208 | 209 | It 'Behaves properly modifying entries in a registry.pol file and NoGptIniUpdate is ' -TestCases $testCases { 210 | param ($PolicyType, [string[]] $ExpectedVersions, [switch] $NoGptIniUpdate, [object[]] $EntriesToModify) 211 | 212 | if (-not $PSBoundParameters.ContainsKey('EntriesToModify')) 213 | { 214 | $EntriesToModify = @( 215 | New-Object psobject -Property @{ 216 | Key = 'Software\Testing' 217 | ValueName = 'TestValue' 218 | Data = 1 219 | Type = 'DWord' 220 | } 221 | ) 222 | } 223 | 224 | $polPath = Join-Path $gpoPath $PolicyType\registry.pol 225 | 226 | $scriptBlock = { 227 | $EntriesToModify | Set-PolicyFileEntry -Path $polPath -NoGptIniUpdate:$NoGptIniUpdate 228 | } 229 | 230 | # We do this next block of code twice to ensure that when "setting" a value that is already present in the 231 | # GPO, the version of gpt.ini is not updated. 232 | 233 | # Code is deliberately duplicated (rather then refactored into a loop) so that if we get failures, 234 | # the line numbers will tell us whether it was on the first or second execution of the duplicated 235 | # parts. 236 | 237 | $scriptBlock | Should Not Throw 238 | 239 | $expected = $ExpectedVersions[0] 240 | $version = @(GetGptIniVersion -Path $gptIniPath) 241 | 242 | $version.Count | Should Be 1 243 | $actual = $version[0] 244 | 245 | $actual | Should Be $expected 246 | 247 | $entries = @(Get-PolicyFileEntry -Path $PolPath -All) 248 | 249 | $entries.Count | Should Be $EntriesToModify.Count 250 | 251 | $count = $entries.Count 252 | for ($i = 0; $i -lt $count; $i++) 253 | { 254 | $matchingEntry = $EntriesToModify | Where-Object { $_.Key -eq $entries[$i].Key -and $_.ValueName -eq $entries[$i].ValueName } 255 | 256 | $entries[$i].ValueName | Should Be $matchingEntry.ValueName 257 | $entries[$i].Key | Should Be $matchingEntry.Key 258 | $entries[$i].Data | Should Be $matchingEntry.Data 259 | $entries[$i].Type | Should Be $matchingEntry.Type 260 | } 261 | 262 | $scriptBlock | Should Not Throw 263 | 264 | $expected = $ExpectedVersions[0] 265 | $version = @(GetGptIniVersion -Path $gptIniPath) 266 | 267 | $version.Count | Should Be 1 268 | $actual = $version[0] 269 | 270 | $actual | Should Be $expected 271 | 272 | $entries = @(Get-PolicyFileEntry -Path $polPath -All) 273 | 274 | $entries.Count | Should Be $EntriesToModify.Count 275 | 276 | $count = $entries.Count 277 | for ($i = 0; $i -lt $count; $i++) 278 | { 279 | $matchingEntry = $EntriesToModify | Where-Object { $_.Key -eq $entries[$i].Key -and $_.ValueName -eq $entries[$i].ValueName } 280 | 281 | $entries[$i].ValueName | Should Be $matchingEntry.ValueName 282 | $entries[$i].Key | Should Be $matchingEntry.Key 283 | $entries[$i].Data | Should Be $matchingEntry.Data 284 | $entries[$i].Type | Should Be $matchingEntry.Type 285 | } 286 | 287 | # End of duplicated bits; now we make sure that removing the entry 288 | # works, and still updates the gpt.ini version (if appropriate.) 289 | 290 | $scriptBlock = { 291 | $EntriesToModify | Remove-PolicyFileEntry -Path $polPath -NoGptIniUpdate:$NoGptIniUpdate 292 | } 293 | 294 | $scriptBlock | Should Not Throw 295 | 296 | $expected = $ExpectedVersions[1] 297 | $version = @(GetGptIniVersion -Path $gptIniPath) 298 | 299 | $version.Count | Should Be 1 300 | $actual = $version[0] 301 | 302 | $actual | Should Be $expected 303 | 304 | $entries = @(Get-PolicyFileEntry -Path $polPath -All) 305 | 306 | $entries.Count | Should Be 0 307 | 308 | # Duplicate the Remove block for the same reasons; make sure the ini file isn't incremented 309 | # when the value is already missing. 310 | 311 | $scriptBlock | Should Not Throw 312 | 313 | $expected = $ExpectedVersions[1] 314 | $version = @(GetGptIniVersion -Path $gptIniPath) 315 | 316 | $version.Count | Should Be 1 317 | $actual = $version[0] 318 | 319 | $actual | Should Be $expected 320 | 321 | $entries = @(Get-PolicyFileEntry -Path $polPath -All) 322 | 323 | $entries.Count | Should Be 0 324 | } 325 | } 326 | 327 | Context 'Get/Set parity' { 328 | $testCases = @( 329 | @{ 330 | TestName = 'Creates a DWord value properly' 331 | Type = [Microsoft.Win32.RegistryValueKind]::DWord 332 | Data = @([UInt32]1) 333 | } 334 | 335 | @{ 336 | TestName = 'Creates a QWord value properly' 337 | Type = [Microsoft.Win32.RegistryValueKind]::QWord 338 | Data = @([UInt64]0x100000000L) 339 | } 340 | 341 | @{ 342 | TestName = 'Creates a String value properly' 343 | Type = [Microsoft.Win32.RegistryValueKind]::String 344 | Data = @('I am a string') 345 | } 346 | 347 | @{ 348 | TestName = 'Creates an ExpandString value properly' 349 | Type = [Microsoft.Win32.RegistryValueKind]::ExpandString 350 | Data = @('My temp path is %TEMP%') 351 | } 352 | 353 | @{ 354 | TestName = 'Creates a MultiString value properly' 355 | Type = [Microsoft.Win32.RegistryValueKind]::MultiString 356 | Data = [string[]]('I', 'am', 'a', 'multi', 'string') 357 | } 358 | 359 | @{ 360 | TestName = 'Creates a Binary value properly' 361 | Type = [Microsoft.Win32.RegistryValueKind]::Binary 362 | Data = [byte[]](1..32) 363 | } 364 | 365 | @{ 366 | TestName = 'Allows hex strings to be assigned to DWord values' 367 | Type = [Microsoft.Win32.RegistryValueKind]::DWord 368 | Data = @('0x12345') 369 | ExpectedData = [UInt32]0x12345 370 | } 371 | 372 | @{ 373 | TestName = 'Allows hex strings to be assigned to QWord values' 374 | Type = [Microsoft.Win32.RegistryValueKind]::QWord 375 | Data = @('0x12345789') 376 | ExpectedData = [Uint64]0x123456789L 377 | } 378 | 379 | @{ 380 | TestName = 'Allows hex strings to be assigned to Binary types' 381 | Type = [Microsoft.Win32.RegistryValueKind]::Binary 382 | Data = '0x1', '0xFF', '0x12' 383 | ExpectedData = [byte[]](0x1,0xFF,0x12) 384 | } 385 | 386 | @{ 387 | TestName = 'Allows non-string data to be assigned to String values' 388 | Type = [Microsoft.Win32.RegistryValueKind]::String 389 | Data = @(12345) 390 | ExpectedData = '12345' 391 | } 392 | 393 | @{ 394 | TestName = 'Allows non-string data to be assigned to ExpandString values' 395 | Type = [Microsoft.Win32.RegistryValueKind]::ExpandString 396 | Data = @(12345) 397 | ExpectedData = '12345' 398 | } 399 | 400 | @{ 401 | TestName = 'Allows non-string data to be assigned to MultiString values' 402 | Type = [Microsoft.Win32.RegistryValueKind]::MultiString 403 | Data = 1..5 404 | ExpectedData = '1', '2', '3', '4', '5' 405 | } 406 | ) 407 | 408 | It '' -TestCases $testCases { 409 | param ($TestName, $Type, $Data, $ExpectedData) 410 | 411 | $polPath = Join-Path $gpoPath Machine\registry.pol 412 | 413 | if (-not $PSBoundParameters.ContainsKey('ExpectedData')) 414 | { 415 | $ExpectedData = $Data 416 | } 417 | 418 | $scriptBlock = { 419 | Set-PolicyFileEntry -Path $polPath ` 420 | -Key Software\Testing ` 421 | -ValueName TestValue ` 422 | -Data $Data ` 423 | -Type $Type 424 | } 425 | 426 | $scriptBlock | Should Not Throw 427 | 428 | $entries = @(Get-PolicyFileEntry -Path $polPath -All) 429 | 430 | $entries.Count | Should Be 1 431 | 432 | $entries[0].ValueName | Should Be TestValue 433 | $entries[0].Key | Should Be Software\Testing 434 | $entries[0].Type | Should Be $Type 435 | 436 | $newData = @($entries[0].Data) 437 | $Data = @($Data) 438 | 439 | $Data.Count | Should Be $newData.Count 440 | 441 | $count = $Data.Count 442 | for ($i = 0; $i -lt $count; $i++) 443 | { 444 | $Data[$i] | Should BeExactly $newData[$i] 445 | } 446 | 447 | } 448 | 449 | It 'Gets values by Key and PropertyName successfully' { 450 | $polPath = Join-Path $gpoPath Machine\registry.pol 451 | $key = 'Software\Testing' 452 | $valueName = 'TestValue' 453 | $data = 'I am a string' 454 | $type = ([Microsoft.Win32.RegistryValueKind]::String) 455 | 456 | $scriptBlock = { 457 | Set-PolicyFileEntry -Path $polPath ` 458 | -Key $key ` 459 | -ValueName $valueName ` 460 | -Data $data ` 461 | -Type $type 462 | } 463 | 464 | $scriptBlock | Should Not Throw 465 | 466 | $entry = Get-PolicyFileEntry -Path $polPath -Key $key -ValueName $valueName 467 | 468 | $entry | Should Not Be $null 469 | $entry.ValueName | Should Be $valueName 470 | $entry.Key | Should Be $key 471 | $entry.Type | Should Be $type 472 | $entry.Data | Should Be $data 473 | } 474 | } 475 | 476 | Context 'Automatic creation of gpt.ini' { 477 | It 'Creates a gpt.ini file if one is not found' { 478 | Remove-Item $gptIniPath 479 | 480 | $path = Join-Path $gpoPath Machine\registry.pol 481 | 482 | Set-PolicyFileEntry -Path $path -Key 'Whatever' -ValueName 'Whatever' -Data 'Whatever' -Type String 483 | 484 | $gptIniPath | Should Exist 485 | GetGptIniVersion -Path $gptIniPath | Should Be 1 486 | } 487 | } 488 | } 489 | 490 | Describe 'Not-so-happy Path' { 491 | BeforeEach { 492 | CreateDefaultGpo -Path $gpoPath 493 | } 494 | 495 | $testCases = @( 496 | @{ 497 | Type = [Microsoft.Win32.RegistryValueKind]::DWord 498 | ExpectedMessage = 'When -Type is set to DWord, -Data must be passed a valid UInt32 value.' 499 | } 500 | 501 | @{ 502 | Type = [Microsoft.Win32.RegistryValueKind]::QWord 503 | ExpectedMessage = 'When -Type is set to QWord, -Data must be passed a valid UInt64 value.' 504 | } 505 | 506 | @{ 507 | Type = [Microsoft.Win32.RegistryValueKind]::Binary 508 | ExpectedMessage = 'When -Type is set to Binary, -Data must be passed a Byte[] array.' 509 | } 510 | ) 511 | 512 | It 'Gives a reasonable error when non-numeric data is passed to values' -TestCases $testCases { 513 | param ($Type, $ExpectedMessage) 514 | 515 | $scriptBlock = { 516 | Set-PolicyFileEntry -Path $gpoPath\Machine\registry.pol ` 517 | -Key Software\Testing ` 518 | -ValueName TestValue ` 519 | -Type $Type ` 520 | -Data 'I am not a number' ` 521 | -ErrorAction Stop 522 | } 523 | 524 | $scriptBlock | Should Throw $ExpectedMessage 525 | } 526 | } 527 | } 528 | finally 529 | { 530 | if ($null -ne $module) 531 | { 532 | Remove-Module -ModuleInfo $module -Force 533 | } 534 | } 535 | -------------------------------------------------------------------------------- /PolicyFileEditor.psd1: -------------------------------------------------------------------------------- 1 | @{ 2 | ModuleToProcess = 'PolicyFileEditor.psm1' 3 | ModuleVersion = '3.0.1' 4 | GUID = '110a2398-3053-4ffc-89d1-1b6a38a2dc86' 5 | Author = 'Dave Wyatt' 6 | CompanyName = 'Home' 7 | Copyright = '(c) 2015 Dave Wyatt. All rights reserved.' 8 | Description = 'Commands and DSC resource for modifying Administrative Templates settings in local GPO registry.pol files.' 9 | PowerShellVersion = '2.0' 10 | # PowerShellHostName = '' 11 | # PowerShellHostVersion = '' 12 | DotNetFrameworkVersion = '2.0' 13 | # CLRVersion = '' 14 | # ProcessorArchitecture = '' 15 | # RequiredModules = @() 16 | # RequiredAssemblies = @() 17 | # ScriptsToProcess = @() 18 | # TypesToProcess = @() 19 | # FormatsToProcess = @() 20 | # NestedModules = @() 21 | FunctionsToExport = @('Set-PolicyFileEntry', 'Remove-PolicyFileEntry', 'Get-PolicyFileEntry', 'Update-GptIniVersion') 22 | # CmdletsToExport = '*' 23 | # VariablesToExport = '*' 24 | # AliasesToExport = '*' 25 | # DscResourcesToExport = @() 26 | # ModuleList = @() 27 | # FileList = @() 28 | 29 | # HelpInfoURI = '' 30 | 31 | # DefaultCommandPrefix = '' 32 | 33 | PrivateData = @{ 34 | PSData = @{ 35 | # Tags = @() 36 | LicenseUri = 'https://www.apache.org/licenses/LICENSE-2.0.html' 37 | ProjectUri = 'https://github.com/dlwyatt/PolicyFileEditor' 38 | # IconUri = '' 39 | ReleaseNotes = 'Updated resource schemas to be more friendly with Invoke-DscResource.' 40 | } 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /PolicyFileEditor.psm1: -------------------------------------------------------------------------------- 1 | #requires -Version 2.0 2 | 3 | $scriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent 4 | $dllPath = Join-Path $scriptRoot PolFileEditor.dll 5 | 6 | Add-Type -Path $dllPath -ErrorAction Stop 7 | 8 | $commandsFile = Join-Path $scriptRoot Commands.ps1 9 | 10 | . $commandsFile 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | __Build Status:__ [![Build status](https://build.powershell.org/guestAuth/app/rest/builds/buildType:(id:PolicyFileEditor_PublishStatusToGitHub)/statusIcon)](https://build.powershell.org/project.html?projectId=PolicyFileEditor&tab=projectOverview&guest=1) 2 | 3 | # PolicyFileEditor 4 | PowerShell functions and DSC resource wrappers around the TJX.PolFileEditor.PolFile .NET class. 5 | 6 | This is for modifying registry.pol files (Administrative Templates) of local GPOs. The .NET class code and examples of the original usage can be found at https://gallery.technet.microsoft.com/Read-or-modify-Registrypol-778fed6e . 7 | 8 | It was written when I was still very new to both C# and PowerShell, and is pretty ugly / painful to use. The new functions make this less of a problem, and the DSC resource wrapper around the functions will give us some capability to manage user-specific settings via DSC (something that's come up in discussions on a mailing list recently.) 9 | 10 | ## Quick start 11 | 12 | This example shows you how to install PolicyFileEditor from the gallery and use it to set a mandatory screen saver timout with logon: 13 | 14 | ```powershell 15 | Write-host "Trusting PS Gallery" 16 | Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted 17 | 18 | Write-Host "Installing PolicyFileEditor V3" 19 | Install-Module -Name PolicyFileEditor -RequiredVersion 3.0.0 -Scope CurrentUser 20 | 21 | $UserDir = "$env:windir\system32\GroupPolicy\User\registry.pol" 22 | 23 | Write-Host "Setting `Password protect the screen saver` to on" 24 | $RegPath = 'Software\Policies\Microsoft\Windows\Control Panel\Desktop' 25 | $RegName = 'ScreenSaverIsSecure' 26 | $RegData = '1' 27 | $RegType = 'String' 28 | Set-PolicyFileEntry -Path $UserDir -Key $RegPath -ValueName $RegName -Data $RegData -Type $RegType 29 | 30 | Write-Host "Setting `Screen saver timeout` to 5m" 31 | 32 | $RegPath = 'Software\Policies\Microsoft\Windows\Control Panel\Desktop' 33 | $RegName = 'ScreenSaveTimeOut' 34 | $RegData = '300' 35 | $RegType = 'String' 36 | 37 | Set-PolicyFileEntry -Path $UserDir -Key $RegPath -ValueName $RegName -Data $RegData -Type $RegType 38 | 39 | # apply the new policy immediately 40 | gpupdate.exe /force 41 | ``` 42 | -------------------------------------------------------------------------------- /Sources/PolFileEditor.cs: -------------------------------------------------------------------------------- 1 | namespace TJX.PolFileEditor 2 | { 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Text; 6 | using System.IO; 7 | using Microsoft.Win32; 8 | 9 | public enum PolEntryType : uint 10 | { 11 | REG_NONE = 0, 12 | REG_SZ = 1, 13 | REG_EXPAND_SZ = 2, 14 | REG_BINARY = 3, 15 | REG_DWORD = 4, 16 | REG_DWORD_BIG_ENDIAN = 5, 17 | REG_MULTI_SZ = 7, 18 | REG_QWORD = 11, 19 | } 20 | 21 | public class PolEntry : IComparable 22 | { 23 | private List byteList; 24 | 25 | public PolEntryType Type { get; set; } 26 | public string KeyName { get; set; } 27 | public string ValueName { get; set; } 28 | 29 | internal List DataBytes 30 | { 31 | get { return this.byteList; } 32 | } 33 | 34 | public uint DWORDValue 35 | { 36 | get 37 | { 38 | byte[] bytes = this.byteList.ToArray(); 39 | 40 | switch (this.Type) 41 | { 42 | case PolEntryType.REG_NONE: 43 | case PolEntryType.REG_SZ: 44 | case PolEntryType.REG_MULTI_SZ: 45 | case PolEntryType.REG_EXPAND_SZ: 46 | uint result; 47 | if (UInt32.TryParse(this.StringValue, out result)) 48 | { 49 | return result; 50 | } 51 | else 52 | { 53 | throw new InvalidCastException(); 54 | } 55 | case PolEntryType.REG_DWORD: 56 | if (bytes.Length != 4) { throw new InvalidOperationException(); } 57 | if (BitConverter.IsLittleEndian == false) { Array.Reverse(bytes); } 58 | return BitConverter.ToUInt32(bytes, 0); 59 | case PolEntryType.REG_DWORD_BIG_ENDIAN: 60 | if (bytes.Length != 4) { throw new InvalidOperationException(); } 61 | if (BitConverter.IsLittleEndian == true) { Array.Reverse(bytes); } 62 | return BitConverter.ToUInt32(bytes, 0); 63 | case PolEntryType.REG_QWORD: 64 | if (bytes.Length != 8) { throw new InvalidOperationException(); } 65 | if (BitConverter.IsLittleEndian == false) { Array.Reverse(bytes); } 66 | ulong lvalue = BitConverter.ToUInt64(bytes, 0); 67 | 68 | if (lvalue > UInt32.MaxValue || lvalue < UInt32.MinValue) 69 | { 70 | throw new OverflowException("QWORD value '" + lvalue.ToString() + "' cannot fit into an UInt32 value."); 71 | } 72 | 73 | return (uint)lvalue; 74 | case PolEntryType.REG_BINARY: 75 | if (bytes.Length != 4) { throw new InvalidOperationException(); } 76 | return BitConverter.ToUInt32(bytes, 0); 77 | default: 78 | throw new Exception("Reached default cast that should be unreachable in PolEntry.UIntValue"); 79 | } 80 | } 81 | set 82 | { 83 | this.Type = PolEntryType.REG_DWORD; 84 | this.byteList.Clear(); 85 | byte[] arrBytes = BitConverter.GetBytes(value); 86 | if (BitConverter.IsLittleEndian == false) { Array.Reverse(arrBytes); } 87 | this.byteList.AddRange(arrBytes); 88 | } 89 | } 90 | public ulong QWORDValue 91 | { 92 | get 93 | { 94 | byte[] bytes = this.byteList.ToArray(); 95 | 96 | switch (this.Type) 97 | { 98 | case PolEntryType.REG_NONE: 99 | case PolEntryType.REG_SZ: 100 | case PolEntryType.REG_MULTI_SZ: 101 | case PolEntryType.REG_EXPAND_SZ: 102 | ulong result; 103 | if (UInt64.TryParse(this.StringValue, out result)) 104 | { 105 | return result; 106 | } 107 | else 108 | { 109 | throw new InvalidCastException(); 110 | } 111 | case PolEntryType.REG_DWORD: 112 | if (bytes.Length != 4) { throw new InvalidOperationException(); } 113 | if (BitConverter.IsLittleEndian == false) { Array.Reverse(bytes); } 114 | return (ulong)BitConverter.ToUInt32(bytes, 0); 115 | case PolEntryType.REG_DWORD_BIG_ENDIAN: 116 | if (bytes.Length != 4) { throw new InvalidOperationException(); } 117 | if (BitConverter.IsLittleEndian == true) { Array.Reverse(bytes); } 118 | return (ulong)BitConverter.ToUInt32(bytes, 0); 119 | case PolEntryType.REG_QWORD: 120 | if (bytes.Length != 8) { throw new InvalidOperationException(); } 121 | if (BitConverter.IsLittleEndian == false) { Array.Reverse(bytes); } 122 | return BitConverter.ToUInt64(bytes, 0); 123 | case PolEntryType.REG_BINARY: 124 | if (bytes.Length != 8) { throw new InvalidOperationException(); } 125 | return BitConverter.ToUInt64(bytes, 0); 126 | default: 127 | throw new Exception("Reached default cast that should be unreachable in PolEntry.ULongValue"); 128 | } 129 | } 130 | set 131 | { 132 | this.Type = PolEntryType.REG_QWORD; 133 | this.byteList.Clear(); 134 | byte[] arrBytes = BitConverter.GetBytes(value); 135 | if (BitConverter.IsLittleEndian == false) { Array.Reverse(arrBytes); } 136 | this.byteList.AddRange(arrBytes); 137 | } 138 | } 139 | public string StringValue 140 | { 141 | get 142 | { 143 | byte[] bytes = this.byteList.ToArray(); 144 | 145 | StringBuilder sb = new StringBuilder(bytes.Length * 2); 146 | 147 | switch (this.Type) 148 | { 149 | case PolEntryType.REG_NONE: 150 | return ""; 151 | case PolEntryType.REG_MULTI_SZ: 152 | string[] mstring = MultiStringValue; 153 | for (int i = 0; i < mstring.Length; i++) 154 | { 155 | if (i > 0) { sb.Append("\\0"); } 156 | sb.Append(mstring[i]); 157 | } 158 | 159 | return sb.ToString(); 160 | case PolEntryType.REG_DWORD: 161 | case PolEntryType.REG_DWORD_BIG_ENDIAN: 162 | case PolEntryType.REG_QWORD: 163 | return this.QWORDValue.ToString(); 164 | case PolEntryType.REG_BINARY: 165 | for (int i = 0; i < bytes.Length; i++) 166 | { 167 | sb.AppendFormat("{0:X2}", bytes[i]); 168 | } 169 | 170 | return sb.ToString(); 171 | case PolEntryType.REG_SZ: 172 | case PolEntryType.REG_EXPAND_SZ: 173 | return UnicodeEncoding.Unicode.GetString(bytes).Trim('\0'); 174 | default: 175 | throw new Exception("Reached default cast that should be unreachable in PolEntry.StringValue"); 176 | } 177 | } 178 | set 179 | { 180 | if (value == null) { value = String.Empty; } 181 | 182 | this.Type = PolEntryType.REG_SZ; 183 | this.byteList.Clear(); 184 | this.byteList.AddRange(UnicodeEncoding.Unicode.GetBytes(value + "\0")); 185 | } 186 | } 187 | public string[] MultiStringValue 188 | { 189 | get 190 | { 191 | byte[] bytes = this.byteList.ToArray(); 192 | 193 | switch (this.Type) 194 | { 195 | case PolEntryType.REG_NONE: 196 | throw new InvalidCastException("StringValue cannot be used on the REG_NONE type."); 197 | case PolEntryType.REG_DWORD: 198 | case PolEntryType.REG_DWORD_BIG_ENDIAN: 199 | case PolEntryType.REG_QWORD: 200 | case PolEntryType.REG_BINARY: 201 | case PolEntryType.REG_SZ: 202 | case PolEntryType.REG_EXPAND_SZ: 203 | return new string[] { this.StringValue }; 204 | case PolEntryType.REG_MULTI_SZ: 205 | List list = new List(); 206 | 207 | StringBuilder sb = new StringBuilder(256); 208 | 209 | for (int i = 0; i < (bytes.Length - 1); i += 2) 210 | { 211 | char[] curChar = UnicodeEncoding.Unicode.GetChars(bytes, i, 2); 212 | if (curChar[0] == '\0') 213 | { 214 | if (sb.Length == 0) { break; } 215 | list.Add(sb.ToString()); 216 | sb.Length = 0; 217 | } 218 | else 219 | { 220 | sb.Append(curChar[0]); 221 | } 222 | } 223 | 224 | return list.ToArray(); 225 | default: 226 | throw new Exception("Reached default cast that should be unreachable in PolEntry.MultiStringValue"); 227 | } 228 | } 229 | set 230 | { 231 | this.Type = PolEntryType.REG_MULTI_SZ; 232 | this.byteList.Clear(); 233 | 234 | if (value != null) 235 | { 236 | for (int i = 0; i < value.Length; i++) 237 | { 238 | if (i > 0) { this.byteList.AddRange(UnicodeEncoding.Unicode.GetBytes("\0")); } 239 | 240 | if (value[i] != null) 241 | { 242 | this.byteList.AddRange(UnicodeEncoding.Unicode.GetBytes(value[i])); 243 | } 244 | } 245 | } 246 | 247 | this.byteList.AddRange(UnicodeEncoding.Unicode.GetBytes("\0\0")); 248 | } 249 | } 250 | public byte[] BinaryValue 251 | { 252 | get { return this.byteList.ToArray(); } 253 | set 254 | { 255 | this.Type = PolEntryType.REG_BINARY; 256 | this.byteList.Clear(); 257 | 258 | if (value != null) 259 | { 260 | this.byteList.AddRange(value); 261 | } 262 | } 263 | 264 | } 265 | 266 | public void SetDWORDBigEndianValue(uint value) 267 | { 268 | this.Type = PolEntryType.REG_DWORD_BIG_ENDIAN; 269 | this.byteList.Clear(); 270 | byte[] arrBytes = BitConverter.GetBytes(value); 271 | if (BitConverter.IsLittleEndian == true) { Array.Reverse(arrBytes); } 272 | this.byteList.AddRange(arrBytes); 273 | } 274 | 275 | public void SetExpandStringValue(string value) 276 | { 277 | this.StringValue = value; 278 | this.Type = PolEntryType.REG_EXPAND_SZ; 279 | } 280 | 281 | public PolEntry() 282 | { 283 | this.byteList = new List(); 284 | Type = PolEntryType.REG_NONE; 285 | KeyName = ""; 286 | ValueName = ""; 287 | } 288 | 289 | ~PolEntry() 290 | { 291 | this.byteList = null; 292 | } 293 | 294 | // IComparable 295 | 296 | public int CompareTo(PolEntry other) 297 | { 298 | int result; 299 | 300 | result = String.Compare(this.KeyName, other.KeyName, StringComparison.OrdinalIgnoreCase); 301 | 302 | if (result != 0) { return result; } 303 | 304 | bool firstSpecial, secondSpecial; 305 | 306 | firstSpecial = this.ValueName.StartsWith("**", StringComparison.OrdinalIgnoreCase); 307 | secondSpecial = other.ValueName.StartsWith("**", StringComparison.OrdinalIgnoreCase); 308 | 309 | if (firstSpecial == true && secondSpecial == false) { return -1; } 310 | if (secondSpecial == true && firstSpecial == false) { return 1; } 311 | 312 | return String.Compare(this.ValueName, other.ValueName, StringComparison.OrdinalIgnoreCase); 313 | } 314 | } 315 | 316 | public class PolFile 317 | { 318 | private enum PolEntryParseState 319 | { 320 | Key, 321 | ValueName, 322 | Start 323 | } 324 | 325 | private static readonly uint PolHeader = 0x50526567; 326 | private static readonly uint PolVersion = 0x01000000; 327 | 328 | private Dictionary entries; 329 | 330 | public List Entries 331 | { 332 | get 333 | { 334 | List pl = new List(entries.Values); 335 | pl.Sort(); 336 | 337 | return pl; 338 | } 339 | } 340 | 341 | public string FileName { get; set; } 342 | 343 | public PolFile() 344 | { 345 | this.FileName = ""; 346 | this.entries = new Dictionary(StringComparer.OrdinalIgnoreCase); 347 | } 348 | 349 | public void SetValue(PolEntry pe) 350 | { 351 | this.entries[pe.KeyName + "\\" + pe.ValueName] = pe; 352 | } 353 | 354 | public void SetStringValue(string key, string value, string data) 355 | { 356 | this.SetStringValue(key, value, data, false); 357 | } 358 | 359 | public void SetStringValue(string key, string value, string data, bool bExpand) 360 | { 361 | PolEntry pe = new PolEntry(); 362 | pe.KeyName = key; 363 | pe.ValueName = value; 364 | 365 | if (bExpand) 366 | { 367 | pe.SetExpandStringValue(data); 368 | } 369 | else 370 | { 371 | pe.StringValue = data; 372 | } 373 | 374 | this.SetValue(pe); 375 | } 376 | 377 | public void SetDWORDValue(string key, string value, uint data) 378 | { 379 | this.SetDWORDValue(key, value, data, true); 380 | } 381 | 382 | public void SetDWORDValue(string key, string value, uint data, bool bLittleEndian) 383 | { 384 | PolEntry pe = new PolEntry(); 385 | pe.KeyName = key; 386 | pe.ValueName = value; 387 | 388 | if (bLittleEndian) 389 | { 390 | pe.DWORDValue = data; 391 | } 392 | else 393 | { 394 | pe.SetDWORDBigEndianValue(data); 395 | } 396 | 397 | this.SetValue(pe); 398 | } 399 | 400 | public void SetQWORDValue(string key, string value, ulong data) 401 | { 402 | PolEntry pe = new PolEntry(); 403 | pe.KeyName = key; 404 | pe.ValueName = value; 405 | 406 | pe.QWORDValue = data; 407 | 408 | this.SetValue(pe); 409 | } 410 | 411 | public void SetMultiStringValue(string key, string value, string[] data) 412 | { 413 | PolEntry pe = new PolEntry(); 414 | pe.KeyName = key; 415 | pe.ValueName = value; 416 | 417 | pe.MultiStringValue = data; 418 | 419 | this.SetValue(pe); 420 | } 421 | 422 | public void SetBinaryValue(string key, string value, byte[] data) 423 | { 424 | PolEntry pe = new PolEntry(); 425 | pe.KeyName = key; 426 | pe.ValueName = value; 427 | 428 | pe.BinaryValue = data; 429 | 430 | this.SetValue(pe); 431 | } 432 | 433 | public PolEntry GetValue(string key, string value) 434 | { 435 | PolEntry pe = null; 436 | this.entries.TryGetValue(key + "\\" + value, out pe); 437 | return pe; 438 | } 439 | 440 | public string GetStringValue(string key, string value) 441 | { 442 | PolEntry pe = this.GetValue(key, value); 443 | if (pe == null) { throw new ArgumentOutOfRangeException(); } 444 | 445 | return pe.StringValue; 446 | } 447 | 448 | public string[] GetMultiStringValue(string key, string value) 449 | { 450 | PolEntry pe = this.GetValue(key, value); 451 | if (pe == null) { throw new ArgumentOutOfRangeException(); } 452 | 453 | return pe.MultiStringValue; 454 | } 455 | 456 | public uint GetDWORDValue(string key, string value) 457 | { 458 | PolEntry pe = this.GetValue(key, value); 459 | if (pe == null) { throw new ArgumentOutOfRangeException(); } 460 | 461 | return pe.DWORDValue; 462 | } 463 | 464 | public ulong GetQWORDValue(string key, string value) 465 | { 466 | PolEntry pe = this.GetValue(key, value); 467 | if (pe == null) { throw new ArgumentOutOfRangeException(); } 468 | 469 | return pe.QWORDValue; 470 | } 471 | 472 | public byte[] GetBinaryValue(string key, string value) 473 | { 474 | PolEntry pe = this.GetValue(key, value); 475 | if (pe == null) { throw new ArgumentOutOfRangeException(); } 476 | 477 | return pe.BinaryValue; 478 | } 479 | 480 | public bool Contains(string key, string value) 481 | { 482 | return (this.GetValue(key, value) != null); 483 | } 484 | 485 | public bool Contains(string key, string value, PolEntryType type) 486 | { 487 | PolEntry pe = this.GetValue(key, value); 488 | return (pe != null && pe.Type == type); 489 | } 490 | 491 | public PolEntryType GetValueType(string key, string value) 492 | { 493 | PolEntry pe = this.GetValue(key, value); 494 | if (pe == null) { throw new ArgumentOutOfRangeException(); } 495 | return pe.Type; 496 | } 497 | 498 | public void DeleteValue(string key, string value) 499 | { 500 | if (this.entries.ContainsKey(key + "\\" + value) == true) this.entries.Remove(key + "\\" + value); 501 | } 502 | 503 | public void LoadFile() 504 | { 505 | this.LoadFile(null); 506 | } 507 | 508 | public void LoadFile(string file) 509 | { 510 | if (!string.IsNullOrEmpty(file)) { this.FileName = file; } 511 | 512 | byte[] bytes; 513 | int nBytes = 0; 514 | 515 | using (FileStream fs = new FileStream(this.FileName, FileMode.Open, FileAccess.Read)) 516 | { 517 | // Read the source file into a byte array. 518 | bytes = new byte[fs.Length]; 519 | int nBytesToRead = (int)fs.Length; 520 | while (nBytesToRead > 0) 521 | { 522 | // Read may return anything from 0 to nBytesToRead. 523 | int n = fs.Read(bytes, nBytes, nBytesToRead); 524 | 525 | // Break when the end of the file is reached. 526 | if (n == 0) break; 527 | 528 | nBytes += n; 529 | nBytesToRead -= n; 530 | } 531 | 532 | fs.Close(); 533 | } 534 | 535 | // registry.pol files are an 8-byte fixed header followed by some number of entries in the following format: 536 | // [KeyName;ValueName;;;] 537 | // The brackets, semicolons, KeyName and ValueName are little-endian Unicode text. 538 | // type and size are 4-byte little-endian unsigned integers. Size cannot be greater than 0xFFFF, even though it's 539 | // stored as a 32-bit number. type will be one of the values REG_SZ, etc as defined in the Win32 API. 540 | // Data will be the number of bytes indicated by size. The next 2 bytes afterward must be unicode "]". 541 | // 542 | // All strings (KeyName, ValueName, and data when type is REG_SZ or REG_EXPAND_SZ) are terminated by a single 543 | // null character. 544 | // 545 | // Multi strings are strings separated by a single null character, with the whole list terminated by a double null. 546 | 547 | if (nBytes < 8) { throw new FileFormatException(); } 548 | 549 | int header = (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]; 550 | int version = (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7]; 551 | 552 | if (header != PolFile.PolHeader || version != PolFile.PolVersion) { throw new FileFormatException(); } 553 | 554 | var parseState = PolEntryParseState.Start; 555 | int i = 8; 556 | 557 | var keyName = new StringBuilder(50); 558 | var valueName = new StringBuilder(50); 559 | uint type = 0; 560 | int size = 0; 561 | 562 | while (i < (nBytes - 1)) 563 | { 564 | char[] curChar = UnicodeEncoding.Unicode.GetChars(bytes, i, 2); 565 | 566 | switch (parseState) 567 | { 568 | case PolEntryParseState.Start: 569 | if (curChar[0] != '[') { throw new FileFormatException(); } 570 | i += 2; 571 | parseState = PolEntryParseState.Key; 572 | continue; 573 | case PolEntryParseState.Key: 574 | if (curChar[0] == '\0') 575 | { 576 | if (i > (nBytes - 4)) { throw new FileFormatException(); } 577 | curChar = UnicodeEncoding.Unicode.GetChars(bytes, i + 2, 2); 578 | if (curChar[0] != ';') { throw new FileFormatException(); } 579 | 580 | // We've reached the end of the key name. Switch to parsing value name. 581 | 582 | i += 4; 583 | parseState = PolEntryParseState.ValueName; 584 | } 585 | else 586 | { 587 | keyName.Append(curChar[0]); 588 | i += 2; 589 | } 590 | continue; 591 | case PolEntryParseState.ValueName: 592 | if (curChar[0] == '\0') 593 | { 594 | if (i > (nBytes - 16)) { throw new FileFormatException(); } 595 | curChar = UnicodeEncoding.Unicode.GetChars(bytes, i + 2, 2); 596 | if (curChar[0] != ';') { throw new FileFormatException(); } 597 | 598 | // We've reached the end of the value name. Now read in the type and size fields, and the data bytes 599 | type = (uint)(bytes[i + 7] << 24 | bytes[i + 6] << 16 | bytes[i + 5] << 8 | bytes[i + 4]); 600 | if (Enum.IsDefined(typeof(PolEntryType), type) == false) { throw new FileFormatException(); } 601 | 602 | curChar = UnicodeEncoding.Unicode.GetChars(bytes, i + 8, 2); 603 | if (curChar[0] != ';') { throw new FileFormatException(); } 604 | 605 | size = bytes[i + 13] << 24 | bytes[i + 12] << 16 | bytes[i + 11] << 8 | bytes[i + 10]; 606 | if ((size > 0xFFFF) || (size < 0)) { throw new FileFormatException(); } 607 | 608 | curChar = UnicodeEncoding.Unicode.GetChars(bytes, i + 14, 2); 609 | if (curChar[0] != ';') { throw new FileFormatException(); } 610 | 611 | i += 16; 612 | 613 | if (i > (nBytes - (size + 2))) { throw new FileFormatException(); } 614 | curChar = UnicodeEncoding.Unicode.GetChars(bytes, i + size, 2); 615 | if (curChar[0] != ']') { throw new FileFormatException(); } 616 | 617 | PolEntry pe = new PolEntry(); 618 | pe.KeyName = keyName.ToString(); 619 | pe.ValueName = valueName.ToString(); 620 | pe.Type = (PolEntryType)type; 621 | 622 | for (int j = 0; j < size; j++) 623 | { 624 | pe.DataBytes.Add(bytes[i + j]); 625 | } 626 | 627 | this.SetValue(pe); 628 | 629 | i += size + 2; 630 | 631 | keyName.Length = 0; 632 | valueName.Length = 0; 633 | parseState = PolEntryParseState.Start; 634 | } 635 | else 636 | { 637 | valueName.Append(curChar[0]); 638 | i += 2; 639 | } 640 | continue; 641 | default: 642 | throw new Exception("Unreachable code"); 643 | } 644 | } 645 | } 646 | 647 | public void SaveFile() 648 | { 649 | this.SaveFile(null); 650 | } 651 | 652 | public void SaveFile(string file) 653 | { 654 | if (!string.IsNullOrEmpty(file)) { this.FileName = file; } 655 | 656 | // Because we maintain the byte array for each PolEntry in memory, writing back to the file 657 | // is a simple operation, creating entries of the format: 658 | // [KeyName;ValueName;type;size;data] after the fixed 8-byte header. 659 | // The only things we must do are add null terminators to KeyName and ValueName, which are 660 | // represented by C# strings in memory, and make sure Size and Type are written in little-endian 661 | // byte order. 662 | 663 | using (FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write)) 664 | { 665 | fs.Write(new byte[] { 0x50, 0x52, 0x65, 0x67, 0x01, 0x00, 0x00, 0x00 }, 0, 8); 666 | byte[] openBracket = UnicodeEncoding.Unicode.GetBytes("["); 667 | byte[] closeBracket = UnicodeEncoding.Unicode.GetBytes("]"); 668 | byte[] semicolon = UnicodeEncoding.Unicode.GetBytes(";"); 669 | byte[] nullChar = new byte[] { 0, 0 }; 670 | 671 | byte[] bytes; 672 | 673 | foreach (PolEntry pe in this.Entries) 674 | { 675 | fs.Write(openBracket, 0, 2); 676 | bytes = UnicodeEncoding.Unicode.GetBytes(pe.KeyName); 677 | fs.Write(bytes, 0, bytes.Length); 678 | fs.Write(nullChar, 0, 2); 679 | 680 | fs.Write(semicolon, 0, 2); 681 | bytes = UnicodeEncoding.Unicode.GetBytes(pe.ValueName); 682 | fs.Write(bytes, 0, bytes.Length); 683 | fs.Write(nullChar, 0, 2); 684 | 685 | fs.Write(semicolon, 0, 2); 686 | bytes = BitConverter.GetBytes((uint)pe.Type); 687 | if (BitConverter.IsLittleEndian == false) { Array.Reverse(bytes); } 688 | fs.Write(bytes, 0, 4); 689 | 690 | fs.Write(semicolon, 0, 2); 691 | byte[] data = pe.DataBytes.ToArray(); 692 | bytes = BitConverter.GetBytes((uint)data.Length); 693 | if (BitConverter.IsLittleEndian == false) { Array.Reverse(bytes); } 694 | fs.Write(bytes, 0, 4); 695 | 696 | fs.Write(semicolon, 0, 2); 697 | fs.Write(data, 0, data.Length); 698 | fs.Write(closeBracket, 0, 2); 699 | } 700 | fs.Close(); 701 | } 702 | } 703 | } 704 | 705 | public class FileFormatException : Exception 706 | { 707 | } 708 | } 709 | -------------------------------------------------------------------------------- /build.psake.ps1: -------------------------------------------------------------------------------- 1 | #requires -Version 3.0 2 | 3 | Task default -depends Build,Sign 4 | 5 | Properties { 6 | $source = $psake.build_script_dir 7 | $buildTarget = "$home\Documents\WindowsPowerShell\Modules\PolicyFileEditor" 8 | $signerCertThumbprint = '572DD922FB11FD90D47EE466EDF4191019FB19FA' 9 | $signerTimestampUrl = 'http://timestamp.digicert.com' 10 | 11 | $filesToExclude = @( 12 | 'README.md' 13 | '*.Tests.ps1' 14 | 'build.psake.ps1' 15 | ) 16 | } 17 | 18 | Task Test { 19 | $result = Invoke-Pester -Path $source -PassThru 20 | $failed = $result.FailedCount 21 | 22 | if ($failed -gt 0) 23 | { 24 | throw "$failed unit tests failed; build aborting." 25 | } 26 | } 27 | 28 | Task Build -depends Test { 29 | function Get-RelativePath 30 | { 31 | param ( [string] $Path, [string] $RelativeTo ) 32 | return $Path -replace "^$([regex]::Escape($RelativeTo))\\?" 33 | } 34 | 35 | if (Test-Path -Path $buildTarget -PathType Container) 36 | { 37 | Remove-Item -Path $buildTarget -Recurse -Force -ErrorAction Stop 38 | } 39 | 40 | $null = New-Item -Path $buildTarget -ItemType Directory -ErrorAction Stop 41 | 42 | Get-ChildItem -Path $source\* -File -Recurse -ErrorAction Stop | 43 | Where { $file = $_; -not ($filesToExclude | Where { $file.Name -like $_ }) } | 44 | ForEach { 45 | $sourceFile = $_ 46 | $relativePath = Get-RelativePath -Path $sourceFile.FullName -RelativeTo $source 47 | $targetPath = Join-Path $buildTarget $relativePath 48 | $parent = Split-Path $targetPath -Parent 49 | 50 | if (-not (Test-Path -LiteralPath $parent -PathType Container)) 51 | { 52 | $null = New-Item -Path $parent -ItemType Directory -ErrorAction Stop 53 | } 54 | 55 | Copy-Item -LiteralPath $sourceFile.FullName -Destination $targetPath -ErrorAction Stop 56 | } 57 | } 58 | 59 | Task Sign { 60 | if (-not $signerCertThumbprint) 61 | { 62 | throw 'Sign task cannot run without a value in the signerCertThumbprint property.' 63 | } 64 | 65 | $paths = @( 66 | "Cert:\CurrentUser\My\$signerCertThumbprint" 67 | "Cert:\LocalMachine\My\$signerCertThumbprint" 68 | ) 69 | 70 | $cert = Get-ChildItem -Path $paths | 71 | Where-Object { $_.PrivateKey -is [System.Security.Cryptography.RSACryptoServiceProvider] } | 72 | Select-Object -First 1 73 | 74 | if ($cert -eq $null) { 75 | throw "Code signing certificate with thumbprint '$signerCertThumbprint' was not found, or did not have a usable private key." 76 | } 77 | 78 | $properties = @( 79 | @{ Label = 'Name'; Expression = { Split-Path -Path $_.Path -Leaf } } 80 | 'Status' 81 | @{ Label = 'SignerCertificate'; Expression = { $_.SignerCertificate.Thumbprint } } 82 | @{ Label = 'TimeStamperCertificate'; Expression = { $_.TimeStamperCertificate.Thumbprint } } 83 | ) 84 | 85 | $splat = @{ 86 | Certificate = $cert 87 | IncludeChain = 'All' 88 | Force = $true 89 | HashAlgorithm = 'SHA256' 90 | } 91 | 92 | if ($signerTimestampUrl) { $splat['TimestampServer'] = $signerTimestampUrl } 93 | 94 | Get-ChildItem -Path $buildTarget -Recurse -File -Include *.ps1, *.psm1, *.psd1 | 95 | Set-AuthenticodeSignature @splat -ErrorAction Stop | 96 | Format-Table -Property $properties -AutoSize 97 | } 98 | -------------------------------------------------------------------------------- /en-US/about_RegistryValuesForAdminTemplates.Help.txt: -------------------------------------------------------------------------------- 1 | TOPIC 2 | about_RegistryValuesForAdminTemplates 3 | 4 | The PolicyFileEditor module allows you to modify the contents of registry.pol and gpt.ini files 5 | in local GPOs. These .pol files correspond to the settings found under Administrative Templates 6 | in the Group Policy Object Editor console. However, you need to know which registry values need 7 | to be modified in order to affect a particular Administrative Templates setting. 8 | 9 | To find this information, you can either search online, or, if you're running a Windows Vista/2008 10 | or later system, you can examine the contents of the .adml and .admx files found in the directory 11 | \PolicyDefinitions. This is how the Group Policy Object Editor console determines what 12 | settings to display in its console, and how to read or set the values in the registry.pol files. 13 | 14 | The first thing you should do is search the .ADML files in the language directory of your choice. 15 | If your language is US English, you'd search the files in the PolicyDefinitions\en-US directory. 16 | Inside these files, you'll find the exact strings that are displayed in the Group Policy Object 17 | Editor console for each setting. 18 | 19 | For example, if you want to know how to modify the "Limit maximum display resolution" setting 20 | for Remote Desktop Services, when you search the folder, you'll find this line in the 21 | TerminalServer.ADML file: Limit maximum display resolution. 22 | 23 | Next, open the associated .ADMX file (in this case, TerminalServer.ADMX) from \PolicyDefinitions, 24 | and search for the string ID you found in the ADML file (in this case, TS_MAXDISPLAYRES). You'll find a 25 | element associated with that displayName. In this case, it looks like this: 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | Not all Policy elements are this simple. Sometimes they can have different actions for Enabled / Disabled, and so on. 37 | You can learn more about ADMX file syntax at https://technet.microsoft.com/en-ca/library/cc753471(v=ws.10).aspx . 38 | 39 | In this case, you can see that two registry values are being modified, named MaxXResolution and MaxYResolution 40 | (indicated by the valueName attributes on the two elements). A element indicates that the 41 | data type will be DWord. 42 | 43 | Armed with that information, you can now do something like this using the PolicyFileEditor module: 44 | 45 | $entries = @( 46 | New-Object psobject -Property @{ ValueName = 'MaxXResolution'; Data = 1680 } 47 | New-Object psobject -Property @{ ValueName = 'MaxYResolution'; Data = 1050 } 48 | ) 49 | 50 | $entries | Set-PolicyFileEntry -Path $env:SystemRoot\system32\GroupPolicy\Machine\registry.pol ` 51 | -Key 'SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services' ` 52 | -Type DWord 53 | 54 | SEE ALSO 55 | Protect-Data 56 | Unprotect-Data 57 | Add-ProtectedDataCredential 58 | Remove-ProtectedDataCredential 59 | Get-ProtectedDataSupportedTypes 60 | Get-KeyEncryptionCertificate 61 | --------------------------------------------------------------------------------