powershell:日志文件写错



我需要帮助我的脚本下面。我想把文件夹复制到多台电脑上,并调整权限。应该记录复制过程是否成功以及授权设置是否成功。然而,对于第二个,它将向日志文件写入失败,尽管它是失败的,并且设置了权限。

$file = get-content -path "C:temppc.txt"
foreach($pc in $file) {
try {
copy-item -path "\server1folder1" -Destination "\$pcC$temp" -force -recurse -verbose
Write-Output $([string](get-date) + "`t $pc success") | out-file -append -filepath "C:tempsucess.log"
}
catch {Write-Output $([string](get-date) + "`t $pc failed") | out-file -append -filepath "C:tempfailed.log"
}

foreach($pc in $file) {
try {
$acl = get-acl -path "\$pcc$tempfolder1"
$new = "users","full","ContainerInherit,ObjectInherit","None","Allow" 
$accessRule = new-object System.Security.AccessControl.FileSystemAccessRule $new 
$acl.SetAccessRule($accessRule) 
$acl | Set-Acl "\$pcc$tempfolder1"
Write-Output $([string](get-date) + "`t $pc success") | out-file -append -filepath "C:tempacl_sucess.log"
}
catch {Write-Output $([string](get-date) + "`t $pc failed") | out-file -append -filepath "C:tempacl_failed.log"
}

write-host
write-host "see Log" -foreground "green"
write-host
}
}

这可能与使用try{} catch{}块而不使用ErrorAction Stop有关。

在这种情况下,最简单的方法是将代码封装在:

$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
# your code
$ErrorActionPreference = $oldErrorAction

最新更新