2017-01-13 33 views
1

私はPowershellでrobocopyをやっています。そして、私が望むのは、ログファイルを書くことです。 Robocopyは動作しますが、tryとcatchはうまく動作しません。ここに私のPowerShellのコードがある:シンプルなtry 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 
+1

ROBOCOPYには/ LOGまたは/ LOG +オプションがあります。あなたはそれを使うことができますか?私はあなたがtry catchで達成しようとしていたことを理解していません。エラーがなければ、何も記録されません。 –

+0

@ShawnEstermanいいえROBOCOPY LOGオプションを使用することはできません。毎日新しいログファイルを作成したいからです。私はrobocopyでそれを行うことはできません。しかし、試しフレーズに間違いがあると、それはキャッチに行きません。それは止まるでしょう。 – Doggo

+2

これはオプションです:robocopy.exe .../LOG: "C:\ users \ boriv \ Desktop \ $(取得日-f dd-MM-yyyy)" –

答えて

6

あなたは(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. 

私は強くあなたがプロセスの完全なログファイルを作成する ためにRobocopyを持つ/ LOGパラメータを使用することをお勧めします。このファイルは、何が問題になったかを知る上で非常に貴重です。 です。

関連する問題