From 0db5aec2d03984ee31a3c88accaa4014ea6d09d7 Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Tue, 13 Dec 2022 15:33:34 +1000 Subject: [PATCH] win_powershell - support scripts with 7 syntax --- .../fragments/powershell-support-7-syntax.yml | 2 ++ plugins/modules/win_powershell.ps1 | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 changelogs/fragments/powershell-support-7-syntax.yml diff --git a/changelogs/fragments/powershell-support-7-syntax.yml b/changelogs/fragments/powershell-support-7-syntax.yml new file mode 100644 index 00000000..14528754 --- /dev/null +++ b/changelogs/fragments/powershell-support-7-syntax.yml @@ -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' diff --git a/plugins/modules/win_powershell.ps1 b/plugins/modules/win_powershell.ps1 index 4a3ed240..bffdce2f 100644 --- a/plugins/modules/win_powershell.ps1 +++ b/plugins/modules/win_powershell.ps1 @@ -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 | @@ -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