Search code examples
powershelltry-catchinvoke-command

powershell invoke-command does not process try-cache block


I have the folowing code:

$output = foreach ($comp in $maschines.name) {
    invoke-command -computer comp1 -ScriptBlock {
        try
        {
            get-vm –VMName $using:comp | Select-Object VMId | Get-VHD | Select-Object @{ label = "vm"; expression = {$using:comp} }, 
            path,
            VhdType, 
            VhdFormat, 
            @{label = "file(gb)"; expression = {($_.FileSize / 1GB) -as [int]} }, 
            @{label = "size(gb)"; expression = {($_.Size / 1GB) -as [int]} }
        }
        catch
        {
            Write-Host some error
        }
    }
}

and I do not get

some error

but:

> The operation failed because the file was not found.
>     + CategoryInfo          : ObjectNotFound: (Microsoft.Hyper...l.VMStorageTask:VMStorageTask) [Ge     t-VHD],
> VirtualizationOperationFailedException
>     + FullyQualifiedErrorId : ObjectNotFound,Microsoft.Vhd.PowerShell.GetVhdCommand
>     + PSComputerName        : comp1

How can I get

some error

in cach block?


Solution

  • In order for a catch block to be triggered the exception needs to be terminating (PowerShell has both terminating and non-terminating errors).

    To force an error from a cmdlet to be terminating, you can use the -ErrorAction parameter with Stop as the value:

    $output = foreach ($comp in $maschines.name) {
        invoke-command -computer comp1 -ScriptBlock {
            try
            {
                get-vm –VMName $using:comp -ErrorAction Stop | Select-Object VMId | Get-VHD | Select-Object @{ label = "vm"; expression = {$using:comp} }, 
                path,
                VhdType, 
                VhdFormat, 
                @{label = "file(gb)"; expression = {($_.FileSize / 1GB) -as [int]} }, 
                @{label = "size(gb)"; expression = {($_.Size / 1GB) -as [int]} }
            }
            catch
            {
                Write-Host some error
            }
        }
    }