捕获PowerShell中的错误代码并跳过命令



我有一个简单的PowerShell脚本,利用ImageMagick来组合ImageFile,然后删除文件所在的目录。我需要做的是,当报告错误时[显示在命令窗口中]如果检测到错误,我们希望脚本跳过删除命令所在的命令。如有任何帮助,不胜感激。

$srcfolder = "C:WorkTest2"
$combine = "C:WorkScriptsToolsImageMagickconvert.exe "
$arg1 = " -compress zip "
$condition = "false"
#-------------------------------------------------------------------
Write-Host "Start"
foreach ($srcitem in $(Get-ChildItem -Path $srcfolder -Recurse -File -Include ('*.tif','*.g42') | Select -ExpandProperty DirectoryName -Unique))
{
$cmdline= $combine + "'"+$srcitem+"*'"+$arg1 +"'"+$srcitem+".tif'"
Write-Host $cmdline
invoke-expression -command $cmdline
$msg = command 2>&1

if ($msg)
{
$condition = "true"
Write-Output "The condition is true, skip"
}
if ( $condition )
{
Write-Output "The Condition was false, remove."
Remove-Item -path $srcitem -recurse
}
}

我编辑了你发布的脚本。我没有测试任何这些代码。您有几种解决错误处理的方法,但这里有2种:

选项1:捕获每个错误https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_trap

trap {
Write-Warning $error[0]
continue
}
$srcfolder = "C:WorkTest2"
$combine = "C:WorkScriptsToolsImageMagickconvert.exe "
$arg1 = " -compress zip "
$condition = "false"
#-------------------------------------------------------------------
Write-Host "Start"
foreach ($srcitem in $(Get-ChildItem -Path $srcfolder -Recurse -File -Include ('*.tif', '*.g42') | Select -ExpandProperty DirectoryName -Unique)) {
$cmdline = $combine + "'" + $srcitem + "*'" + $arg1 + "'" + $srcitem + ".tif'"
Write-Host $cmdline
invoke-expression -command $cmdline
$msg = command 2>&1

if ($msg) {
$condition = "true"
Write-Output "The condition is true, skip"
}
if ( $condition ) {
Write-Output "The Condition was false, remove."
Remove-Item -path $srcitem -recurse
}
}

选项2:Try Catchhttps://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally

$srcfolder = "C:WorkTest2"
$combine = "C:WorkScriptsToolsImageMagickconvert.exe "
$arg1 = " -compress zip "
$condition = "false"
#-------------------------------------------------------------------
Write-Host "Start"
foreach ($srcitem in $(Get-ChildItem -Path $srcfolder -Recurse -File -Include ('*.tif', '*.g42') | Select -ExpandProperty DirectoryName -Unique)) {
$cmdline = $combine + "'" + $srcitem + "*'" + $arg1 + "'" + $srcitem + ".tif'"
Write-Host $cmdline
try {
invoke-expression -command $cmdline -ErrorAction Stop
$msg = command 2>&1
if ($msg) {
$condition = "true"
Write-Output "The condition is true, skip"
}
if ( $condition ) {
Write-Output "The Condition was false, remove."
Remove-Item -path $srcitem -recurse
}
}
catch {
Write-Warning $error[0]
continue
}
}

相关内容

最新更新