Skip to content

Commit

Permalink
win_powershell - support scripts with 7 syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
jborean93 committed Dec 13, 2022
1 parent 4a45d3b commit 0db5aec
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
2 changes: 2 additions & 0 deletions changelogs/fragments/powershell-support-7-syntax.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
bugfixes:
- 'win_powershell - Support PowerShell 7 script syntax when targeting ``executable: pwsh.exe`` - https://github.com/ansible-collections/ansible.windows/issues/452'
16 changes: 14 additions & 2 deletions plugins/modules/win_powershell.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -514,9 +514,18 @@ if ($removes -and -not (Test-AnsiblePath -Path $removes)) {
}

# Check if the script has [CmdletBinding(SupportsShouldProcess)] on it
$scriptAst = [ScriptBlock]::Create($module.Params.script).Ast
try {
$scriptAst = [ScriptBlock]::Create($module.Params.script).Ast
}
catch [System.Management.Automation.ParseException] {
# Trying to parse pwsh 7 code may fail if using new syntax not available in
# WinPS. Need to fallback to a more rudimentary scanner.
# https://github.com/ansible-collections/ansible.windows/issues/452
$scriptAst = $null
}

$supportsShouldProcess = $false
if ($scriptAst -is [Management.Automation.Language.ScriptBlockAst] -and $scriptAst.ParamBlock.Attributes) {
if ($scriptAst -and $scriptAst -is [Management.Automation.Language.ScriptBlockAst] -and $scriptAst.ParamBlock.Attributes) {
$supportsShouldProcess = [bool]($scriptAst.ParamBlock.Attributes |
Where-Object { $_.TypeName.Name -eq 'CmdletBinding' } |
Select-Object -First 1 |
Expand All @@ -526,6 +535,9 @@ if ($scriptAst -is [Management.Automation.Language.ScriptBlockAst] -and $scriptA
}
})
}
elseif (-not $scriptAst) {
$supportsShouldProcess = $module.Params.script -match '\[CmdletBinding\((?:[\w=\$]+,\s*)?SupportsShouldProcess(?:=\$true)?(?:,\s*[\w=\$]+)?\)\]'
}

if ($module.CheckMode -and -not $supportsShouldProcess) {
$module.Result.changed = $true
Expand Down

0 comments on commit 0db5aec

Please sign in to comment.