在 powershell 中使用 if 条件验证表达式是否成功

Validate Expression Success with if condition in powershell

我正在尝试 运行 在 powershell 脚本中执行一个长的 PowerCLI 命令,并根据它的成功输出到控制台。该命令正在执行并成功但未触发成功输出。

我尝试将整个命令设为变量但没有成功。我怀疑有一种我不知道的更高级的方法可以做到这一点。

Try{      
        #get list of all vms
        Write-Host "Collecting data and adding to file..."
        [Environment]::NewLine
        #create list of VMs in a variable
        $vmList = Get-VM -ErrorAction Stop


        #collect the VMWare Disk List here.
        #run the list through the appropriate filters and prompt for success (failure will initiate the catch)
        if ($vmList | Where-Object {$_.PowerState -eq "PoweredOff" -and $_.ExtensionData.config.ManagedBy.ExtensionKey -ne 'com.vmware.vcDr'} | Select-Object Name, @{N="Disk (GB)"; E={[math]::Round(($_ | Get-HardDisk | Measure-Object CapacityGB -Sum).sum)}}, @{N="Power State"; E={$_.PowerState}} | Export-Csv -Append -LiteralPath c:\temp\VMdiskTotals.csv) {
        Write-Host "vCenter Disk Collection for " $vcenter " Successful!"
        }

        }
Catch{
            Write-Host "Failed to collect the data from " $vcenter.Vcenter -ForegroundColor Red
            }

我想要这个 运行 命令,如果它完成且没有错误输出:

"vCenter Disk Collection for " $vcenter “成功!”

如果命令产生任何错误,它应该触发捕获并输出:

Write-Host "Failed to collect the data from " $vcenter.Vcenter -ForegroundColor 红色

您可以执行此操作的一种方法是在 If 语句中的变量中捕获该信息,然后在脚本块中将其输出为 CSV 并写入控制台。

    if (($ToOutput=$vmList | Where-Object {$_.PowerState -eq "PoweredOff" -and $_.ExtensionData.config.ManagedBy.ExtensionKey -ne 'com.vmware.vcDr'})){
        $ToOutput | Select-Object Name, @{N="Disk (GB)"; E={[math]::Round(($_ | Get-HardDisk | Measure-Object CapacityGB -Sum).sum)}}, @{N="Power State"; E={$_.PowerState}} | Export-Csv -Append -LiteralPath c:\temp\VMdiskTotals.csv
        Write-Host "vCenter Disk Collection for " $vcenter " Successful!"
    }

仍然不清楚为什么需要将所有内容都放在 if 语句中。但也许这对你有用:

try {
    $vmList = Get-Vm -ErrorAction Stop
    if ($vmList) {  # If there are any VM objects in the array
        "vCenter Disk Collection for $vcenter Successful!"
        $vmList | Where-Object {$_.PowerState -eq "PoweredOff" -and $_.ExtensionData.config.ManagedBy.ExtensionKey -ne 'com.vmware.vcDr'} | 
            Select-Object Name, @{N="Disk (GB)"; E={[math]::Round(($_ | Get-HardDisk | Measure-Object CapacityGB -Sum).sum)}}, @{N="Power State"; E={$_.PowerState}} | 
            Export-Csv -Path c:\temp\VMdiskTotals.csv -Append -ErrorAction Stop
        "Successfully outputted to file."
    }
    else {
        "No VMs found."
    }
}
catch [VMware.VimAutomation.Sdk.Types.V1.ErrorHandling.VimException.VimException] {
    "Search for VMs failed."
}
catch [System.IO.IOException] {
    "Unable to write to file."
}
catch {
    "Other catch."
    $Error[0]
}