Search code examples
powershellbooleantry-catchpowercli

Validate Expression Success with if condition in powershell


I am attempting to run a long PowerCLI command in a powershell script and output to the console based on its success. The command is executing and succeeding but NOT triggering the success output.

I tried making the entire command a variable but with no success. I suspect there is a more advanced way to do this that I am just not aware of.

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
            }

I want this to run the command, and if it completes with no error to output:

"vCenter Disk Collection for " $vcenter " Successful!"

if the command produces ANY error, it should trigger the catch and output:

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


Solution

  • It's still not clear why you need to put everything in an if statement. But perhaps this would work for you:

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