From c80d696cece235a5ad62787da20e372493543458 Mon Sep 17 00:00:00 2001 From: Andrea Scarpino Date: Fri, 17 Mar 2017 17:33:57 +0100 Subject: [PATCH] win_file: fix error when creating an existing dir (#19070) If something else created the dir New-Item will throw an exception and the task will fail. Check the existing file and as long as it's a dir, we don't need to error out. --- lib/ansible/modules/windows/win_file.ps1 | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/ansible/modules/windows/win_file.ps1 b/lib/ansible/modules/windows/win_file.ps1 index 4e6933923c8..7c270484085 100644 --- a/lib/ansible/modules/windows/win_file.ps1 +++ b/lib/ansible/modules/windows/win_file.ps1 @@ -66,7 +66,7 @@ function Remove-File($file, $checkmode) { Remove-Item -Path $file.FullName -Force -WhatIf:$checkmode } } catch [Exception] { - Fail-Json (New-Object psobject) "Failed to delete $($file.FullName): $($_.Exception.Message)" + Fail-Json $result "Failed to delete $($file.FullName): $($_.Exception.Message)" } } @@ -116,7 +116,18 @@ if (Test-Path $path) { } if ($state -eq "directory") { - New-Item -Path $path -ItemType Directory -WhatIf:$check_mode | Out-Null + try { + New-Item -Path $path -ItemType Directory -WhatIf:$check_mode | Out-Null + } catch { + if ($_.CategoryInfo.Category -eq "ResourceExists") { + $fileinfo = Get-Item $_.CategoryInfo.TargetName + if ($state -eq "directory" -and -not $fileinfo.PsIsContainer) { + Fail-Json $result "path $path is not a directory" + } + } else { + Fail-Json $result $_.Exception.Message + } + } $result.changed = $true } elseif ($state -eq "file") { Fail-Json $result "path $path will not be created"