Powershell终止执行



当找不到具有当前日期戳的文件时,我正在使用powershell处理目录中的csv文件,我希望进程引发错误通知未找到文件并退出。

# Powershell raise error and exit
# File name: sale_2020_02_03.csv
$getLatestCSVFile = Get-ChildItem -Path $Folder -Filter "*.csv" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
if ($getLatestCSVFile)
{
try
{
# Process .csv file
}
catch
{
# on error
$ErrorMessage = $_.Exception.Message
throw "$ErrorMessage"
}
}
else
{
# If current date file not found raise error and exit
Send-MailMessage
throw "File not found"
}

至于这个...

我想让 powershell 脚本停止执行

。这就是 Exit 关键字或"-ErrorAction Stop"选项的用途。

至于这个...

如果代码进入 else 块中的 else 块,我想 未找到通知文件

。根据我上面的说法,同样的事情,你必须设置它。

意思是像...

Clear-Host
$Error.Clear()
try
{
# Statement to try
New-Item -Path 'D:TempDoesNOtExist' -Name 'Test.txt' -ItemType File -ErrorAction Stop
}
catch 
{
# What to do with terminating errors
Write-Warning -Message $Error[0]
}
# Results
<#
WARNING: Could not find a part of the path 'D:TempDoesNOtExistTest.txt'.
#>

或者使用多个 catch 语句,例如...

示例:强制文件警告

Clear-Host
$Error.Clear()
try
{
# Results in NoSupportException
# Statement to try
New-Item -Path 'D:TempTemp' -Name my:Test.txt -ItemType File -ErrorAction Stop
# Results in DirectoryNotFoundException
# New-Item -Path 'D:TempTemp' -Name 'Test.txt' -ItemType File -ErrorAction Stop
}
catch [System.NotSupportedException]
{
# What to do with terminating errors
Write-Warning -Message 'Illegal chracter or filename.'
}
catch [System.IO.DirectoryNotFoundException]
{
# What to do with terminating errors
Write-Warning -Message 'The path is not valid.'
}
catch 
{
# What to do with terminating errors
Write-Warning -Message 'An unexpected error occurred.'
}
# Results
<#
WARNING: Illegal character or filename.
#>

示例:强制路径警告

Clear-Host
$Error.Clear()
try
{
# Results in NoSupportException
# Statement to try
# New-Item -Path 'D:TempTemp' -Name my:Test.txt -ItemType File -ErrorAction Stop
# Results in DirectoryNotFoundException
New-Item -Path 'D:TempTemp' -Name 'Test.txt' -ItemType File -ErrorAction Stop
}
catch [System.NotSupportedException]
{
# What to do with terminating errors
Write-Warning -Message 'Illegal chracter or filename.'
}
catch [System.IO.DirectoryNotFoundException]
{
# What to do with terminating errors
Write-Warning -Message 'The path is not valid.'
}
catch 
{
# What to do with terminating errors
Write-Warning -Message 'An unexpected error occurred.'
}
# Results
<#
WARNING: The path is not valid.
#>

另请参阅此讨论,这是一个类似的用例。特别注意"退出与返回与中断"答案。

在 PowerShell 中终止脚本

最新更新