简体   繁体   中英

PowerCLI Get-VM output

I am working on a script, and I am having trouble with a section of code. When I pass in a list of computers that are all found in VCenter, the script populates the $result object correctly with a list of servers and all of the information included. If there are any errors (unable to find server in VCenter) the only thing that is returned is the error line (in the case of multiple errors, only the last error is in $result). Any ideas what I can do to resolve this?

I know that it will work if I enclose the Get-VM statement in a foreach loop, but passing one server at a time to the VCenter takes a very long time.

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
            }
        }

I think the try / catch is on the false position. Maybe if you put an if / else statement in the foreach this work?
But I don't know how to check if $comp is en 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
                }
            }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM