From d4ce1b9f31cfcf4b98ca2f50db3494a2c0ec3d70 Mon Sep 17 00:00:00 2001 From: Jordan Borean Date: Tue, 11 Sep 2018 09:47:56 +1000 Subject: [PATCH] fix Ansible.ModuleUtils.FileUtil to respect ErrorAction if running in a try/catch (#45451) --- .../powershell/Ansible.ModuleUtils.FileUtil.psm1 | 11 ++++++++++- .../win_module_utils/library/file_util_test.ps1 | 8 ++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/lib/ansible/module_utils/powershell/Ansible.ModuleUtils.FileUtil.psm1 b/lib/ansible/module_utils/powershell/Ansible.ModuleUtils.FileUtil.psm1 index 857bd1bfdf..81a29ac036 100644 --- a/lib/ansible/module_utils/powershell/Ansible.ModuleUtils.FileUtil.psm1 +++ b/lib/ansible/module_utils/powershell/Ansible.ModuleUtils.FileUtil.psm1 @@ -38,7 +38,16 @@ Function Get-AnsibleItem { [Parameter(Mandatory=$true)][string]$Path ) # Replacement for Get-Item - $file_attributes = [System.IO.File]::GetAttributes($Path) + try { + $file_attributes = [System.IO.File]::GetAttributes($Path) + } catch { + # if -ErrorAction SilentlyCotinue is set on the cmdlet and we failed to + # get the attributes, just return $null, otherwise throw the error + if ($ErrorActionPreference -ne "SilentlyContinue") { + throw $_ + } + return $null + } if ([Int32]$file_attributes -eq -1) { throw New-Object -TypeName System.Management.Automation.ItemNotFoundException -ArgumentList "Cannot find path '$Path' because it does not exist." } elseif ($file_attributes.HasFlag([System.IO.FileAttributes]::Directory)) { diff --git a/test/integration/targets/win_module_utils/library/file_util_test.ps1 b/test/integration/targets/win_module_utils/library/file_util_test.ps1 index 5f48317e16..ae3e68ec4a 100644 --- a/test/integration/targets/win_module_utils/library/file_util_test.ps1 +++ b/test/integration/targets/win_module_utils/library/file_util_test.ps1 @@ -96,5 +96,13 @@ Assert-Equals -actual $actual.FullName -expected C:\Windows Assert-Equals -actual $actual.Attributes.HasFlag([System.IO.FileAttributes]::Directory) -expected $true Assert-Equals -actual $actual.Exists -expected $true +# ensure Get-AnsibleItem doesn't fail in a try/catch and -ErrorAction SilentlyContinue - stop's a trap from trapping it +try { + $actual = Get-AnsibleItem -Path C:\fakepath -ErrorAction SilentlyContinue +} catch { + Fail-Json -obj $result -message "this should not fire" +} +Assert-Equals -actual $actual -expected $null + $result.data = "success" Exit-Json -obj $result