powershell - 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
}
}
解决方案
这可能与使用try{} catch{}
块而不使用ErrorAction Stop
.
在这种情况下,将代码包装在里面是最简单的:
$oldErrorAction = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
# your code
$ErrorActionPreference = $oldErrorAction
推荐阅读
- android - 小吃店可访问性
- c# - 如何在从具有工作“XmlInclude”属性的基类继承的类中包含“XmlInclude”?
- php - 如何使用 html 表单从 php 文件中加载和编辑所有字符串
- javascript - 悬停在highchart的同步图表上时线褪色
- react-redux - React -Redux:如何在提交事件上调度操作时将文本框值作为参数传递给调度方法
- python - 从具有多个值(〜500 000)的熊猫数据框创建数组的最快方法
- powershell - PowerShell If 语句失败
- java - 如何修复与语义谓词一起使用的左递归中的错误?
- d3.js - 条形图上的平均线
- java - 用于捕获特殊字符的正则表达式