PowerCLI Get-VM输出

时间:2014-08-27 15:22:12

标签: powershell powercli

我正在处理一个脚本,我遇到了一段代码问题。当我传入一个在VCenter中找到的计算机列表时,该脚本使用服务器列表和所包含的所有信息正确填充$ result对象。如果有任何错误(无法在VCenter中找到服务器),唯一返回的是错误行(在多个错误的情况下,只有最后一个错误在$ result中)。我有什么想法可以解决这个问题?

我知道如果我将Get-VM语句包含在foreach循环中,它会起作用,但是一次将一个服务器传递给VCenter需要很长时间。

try {
        $operation = Get-VM -Name $computers -ErrorAction Stop | Restart-VMGuest -Confirm:$false
        foreach ($comp in $operation) {
            $result += [pscustomobject] @{
                Server = $computer
                Status = $True
                Error = $False
                ErrorMessage = $null
                Stamp = Get-Date
                }
            }
        }
    catch {
        $result += [pscustomobject] @{
            Server = $computer
            Status = $False
            Error = $True
            ErrorMessage = $_
            Stamp = Get-Date
            }
        }

1 个答案:

答案 0 :(得分:0)

我认为try / catch处于假位置。也许如果你在foreach中添加if / else语句这项工作?
但我不知道如何检查$comp是否为error ...

 $operation = Get-VM -Name $computers -ErrorAction Stop | Restart-VMGuest -Confirm:$false

foreach ($comp in $operation) {
    If ($comp -eq "??error??") {
        $result += [pscustomobject] @{
            Server = $computer
            Status = $True
            Error = $False
            ErrorMessage = $null
            Stamp = Get-Date
            }
    }
    Else {
        $result += [pscustomobject] @{
                Server = $computer
                Status = $False
                Error = $True
                ErrorMessage = $_
                Stamp = Get-Date
                }
            }
    }