【发布时间】:2018-10-25 14:11:42
【问题描述】:
我有一个 - 在我看来 - PowerShell 抛出错误的奇怪情况,即使我试图忽略它。还有什么奇怪的,这是一个终止错误,这意味着整个函数即使不应该停止也停止
这是我的函数,我通过使用haveibeenpwned API 来获取我公司的被泄露电子邮件帐户。
function Get-Pwned {
Param(
[Parameter( Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
[string[]]$EmailAddress,
[ValidateNotNullOrEmpty()]
[string]$API = "https://haveibeenpwned.com/api/v2/breachedaccount/"
)
Begin {
$ErrorActionPreference = "SilentlyContinue"
# Setzen der Anfrage auf TLS 1.2, da TLS 1.0 nicht akzeptiert wird
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# ResultArray
$Pwned = @()
}
# über Mail Adressen loopen und schauen ob
Process {
foreach ($Email in $EmailAddress)
{
$Uri = "{0}{1}" -f $API, $Email
Write-Host $Uri
Invoke-WebRequest $Uri -ea Ignore | select -expand Content | ConvertFrom-Json |
foreach {
$Pwned += [PSCustomObject]@{
Email = $Email
Name = $_.Name
Domain = $_.Domain
BreachDate = $_.BreachDate
}
}
}
}
End {
# Return Object
$Pwned
}
}
API 的Documentation 说,如果没有发现电子邮件地址违规,我将得到状态码 404 作为回报。
我的问题是,每当发生这种情况时,我都会收到一个完全终止的错误。所以基本上,当一个电子邮件地址没有被 pwned 时(这是好事),脚本的执行会完全停止(这不是好事)。
如您所见,我正在尝试执行 $ErrorActionPreference = "SilentlyContinue" 和 -ea Ignore,但我仍然收到错误消息并且我的脚本仍然停止。
我使用这样的功能:
Get-Mailbox foo@bar.com | select -expand EmailAddresses | ? { $_.startswith("smtp:") } | % { $_.split(":")[1] } | Get-Pwned
如果你想测试它,你可以这样做:
"email@server.com", "email2@server.com" | get-pwned
这就是我得到的错误:
Invoke-WebRequest : Der Remoteserver hat einen Fehler zurückgegeben: (404) 无罪。在 \server\Powershell-Scripts\Functions\Get-Pwned.ps1:27 蔡晨:13 + Invoke-WebRequest $Uri -ea 忽略 |选择-展开内容... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], 网络异常 + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
如何让我的脚本在出现错误消息时不停止,以及如何忽略它,以免收到错误消息?
编辑: 我刚刚注意到,如果我这样做,它会起作用:
$addr = "email@server.com", "email2@server.com"
Get-Pwned $addr
为什么它不适用于管道输入?
【问题讨论】:
-
它不应该抛出终止错误,尤其是考虑到您要达到的长度。作为最后的手段,您可以将命令包装在 try/catch 块中。
-
@TheIncorrigible1 是的,
try / catch有效。多谢!我发现它仍然很奇怪,因为我已经忽略了这个错误。如果您愿意,可以将命令扩展为答案,我很乐意接受它
标签: powershell