windows 复制文件时如何将错误输出到powershell中的日志文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19777782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to output errors to a log file in powershell when copying files
提问by Bajan
I am trying to write a powershell script that does the following:
我正在尝试编写一个执行以下操作的 powershell 脚本:
- Check to see if a folder on a remote machine(text list of computers) exists, if so delete it.
- Copy a folder from a remote share to the same machine and if there is an error output to an error log file, if not, output to a success log file.
- 检查远程计算机上的文件夹(计算机的文本列表)是否存在,如果存在则将其删除。
- 将一个文件夹从远程共享复制到同一台机器,如果有错误输出到错误日志文件,如果没有,输出到成功日志文件。
I have searched but have been unable to find a solution to my seemingly simple problem, please see my code below:
我已经搜索过但一直无法找到解决我看似简单的问题的方法,请参阅下面的代码:
$computers=Get-Content C:\pcs.txt
$source="\RemoteShare\RemoteFolder"
$dest="C$\Program Files\Destination"
foreach ($computer in $computers) {
If (Test-Path \$computer$dest){
Remove-Item \$computer$dest -Force -Recurse
}
Copy-Item $source \$computer$dest -recurse -force -erroraction silentlycontinue
If (!$error)
{Write-Output $computer | out-file -append -filepath "C:\logs\success.log"}
Else
{Write-Output $computer | out-file -append -filepath "C:\logs\failed.log"}
}
Currently, when the script runs, everything is getting put in the failed.log file, regardless of if it fails or not.
目前,当脚本运行时,所有内容都被放入 failed.log 文件中,无论它是否失败。
How can I properly handle errors in powershell, while running through a for loop?
在运行 for 循环时,如何正确处理 powershell 中的错误?
回答by crownedjitter
Here's an example.
这是一个例子。
$array = @(3,0,1,2)
foreach ($item in $array)
{
try
{
1/$item | Out-Null
Write-Host "$item is okay"
}
catch
{
Write-Host "There was an error! Can't divide by $item!"
}
}
回答by zdan
Don't use $error
, it always contains an array of recent error objects, even if the last command was successful. To check the results of the last command, use the $?
, it will be false if the last command failed.
不要使用$error
,它总是包含最近错误对象的数组,即使最后一个命令成功。要检查最后一条命令的结果,请使用$?
,如果最后一条命令失败,则为假。
See about_Automatic_Variablesfor more details on these variables.
有关这些变量的更多详细信息,请参阅about_Automatic_Variables。