首页 > 解决方案 > powershell:日志文件未正确写入

问题描述

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

$file = get-content -path "C:\temp\pc.txt"
foreach($pc in $file) {
try {
copy-item -path "\\server1\folder1" -Destination "\\$pc\C$\temp\" -force -recurse -verbose

Write-Output $([string](get-date) + "`t $pc success") | out-file -append -filepath "C:\temp\sucess.log"
}
catch {Write-Output $([string](get-date) + "`t $pc failed") | out-file -append -filepath "C:\temp\failed.log"
}


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


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

标签: powershell

解决方案


这可能与使用try{} catch{}块而不使用ErrorAction Stop.

在这种情况下,将代码包装在里面是最简单的:

$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'

# your code

$ErrorActionPreference = $oldErrorAction

推荐阅读