gpt4 book ai didi

powershell - 一个简单的 try catch 不起作用Powershell

转载 作者:行者123 更新时间:2023-12-03 00:28:40 25 4
gpt4 key购买 nike

因此,我正在使用Powershell进行robocopy。我只想写一个日志文件。 Robocopy有效,但try and catch不起作用。这是我的Powershell代码:

function Write-Log{[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
[String]
$level = "INFO",

[Parameter(Mandatory=$True)]
[string]
$message ,

[Parameter(Mandatory=$True)]
[string]
$logfile
)

$timeStamp = (Get-Date).toString("dd.MM.yyyy HH:mm:ss")
$line = "$timeStamp $level $message"
if($logfile) {
Add-Content $logfile -Value $line
} else {
Write-Output $line
}}


try {C:\WINDOWS\SysWOW64\robocopy.exe "C:\Users\boriv\Desktop\por" "C:/users/boriv/desktop/1" robocopy *.* /MIR /EFSRAW /DCOPY:DAT /A+:R /A-:AE /IA:ACEHNORST /V /BYTES}

catch { Write-Log -message "Der Kopiervorgang war nicht erfolgreich" -logfile "C:\users\boriv\Desktop\$(get-date -f dd-MM-yyyy).txt" -level ERROR}

Write-Log -message "Der Kopiervorgang war erfolgreich" -logfile "C:\users\boriv\Desktop\$(get-date -f dd-MM-yyyy).txt" -level INFO

最佳答案

您不能对外部进程(即robocopy.exe是)使用异常处理。

相反,您应该使用$LASTEXITCODE来确定执行状态。每个单独的外部命令具有不同的退出代码,这些退出代码表示不同的内容(尽管0几乎普遍表示成功)。

See the very last section here有关处理外部错误的信息。

A list of robocopy exit codes is available here并提供以下信息:

0 No errors occurred and no files were copied.
1 One of more files were copied successfully.
2 Extra files or directories were detected. Examine the log file for more information.
4 Mismatched files or directories were detected. Examine the log file for more information.
8 Some files or directories could not be copied and the retry limit was exceeded.
16 Robocopy did not copy any files. Check the command line parameters and verify that Robocopy has enough rights to write to the destination folder.

I strongly recommend that you use the /LOG parameter with Robocopy in order to create a complete log file of the process. This file is invaluable for finding out what went wrong.

关于powershell - 一个简单的 try catch 不起作用Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41637632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com