Powershell 在发生 try catch 时优雅地继续

问题描述 投票:0回答:1

抱歉,这可能是一件简单的事情,但我无法让它工作!我有一个更大的脚本用于演示目的,我已经简化了它。基本上,我想要的是 PowerShell 继续并返回代码 0 并执行 write-host,即使存在 try catch,例如在这种情况下,我希望 json_template 打印包含错误消息的消息,但其他字段为空。目前,当我运行脚本时,我得到这个:

非常感谢并感谢您的回复。代码如下:

$hostName = ""

if ([string]::IsNullOrEmpty($hostName)) {
    throw "Host name cannot be null or empty"
}

$json_template = $null

try {
    $nameModel = Get-WmiObject Win32_ComputerSystem -ComputerName $hostName  | select name, model | ConvertTo-Json;
    $serialNumer = Get-WmiObject win32_bios -ComputerName $hostName | select Serialnumber | ConvertTo-Json;

    $json_template = @"
{
  "Info": $($nameModel),
  "Serial": $($serialNumer),
  "Message": ""
}
"@
}
catch {
    $json_template = @"
{
    "Info": "",
    "Serial": "",
    "Message": "$($_.Exception.Message)"
}
"@
    # Gracefully exit with code 0
    #exit 0
}
finally {
    # Print the JSON template
    Write-Host $json_template
    exit 0;
}

powershell try-catch exit
1个回答
1
投票

主要错误是

Throw
位于
Try{}
之外。
有评论版本,希望有用,点

# Managing hard-coded JSON is hard
# Let's make an empty template Object instead and convert it only when necessary!
$json_template = [PSCustomObject]@{
    Info    = ''
    Serial  = ''
    Message = ''
}


# Setting up the variable to fail
$hostName = ''


try {
    # Catch is never going to catch the Throw if it's outside the Try
    if ([string]::IsNullOrEmpty($hostName)) { throw 'Host name cannot be null or empty' }

    # Two things:
    # 1. Get-WmiObject has been Obsolete for years and removed from
    #    Powershell 6+. Use Get-CimInstance instead.
    # 2. Depending on your system settings you might need tell Cmdlets to
    #    stop(and throw) if they hit an error. You can do it by adding
    #    "-ErrorAction Stop" to each cmdlet or setting it on a global level.
    #    I'll let you look up for that to decide what's the best course of
    #    action case-by-case.
    $json_template.Info = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $hostName -ErrorAction Stop | Select-Object -Property Name, Model
    $json_template.Serial = Get-CimInstance -ClassName Win32_BIOS -ComputerName $hostName -ErrorAction Stop | Select-Object -Property SerialNumber
}
catch {
    $json_template.Message = $_.Exception.Message
}
finally {
    # Convert the whole Object to JSON and send it to be printed on screen
    $json_template | ConvertTo-Json | Write-Host
    exit 0
}
© www.soinside.com 2019 - 2024. All rights reserved.