andrej
andrej

Reputation: 587

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?

Upvotes: 2

Views: 932

Answers (2)

Fourat
Fourat

Reputation: 2447

Add -ErrorAction Stop to Get-Vm to make it terminating.

You can read more about terminating ana non-terminating cmdlet in powershell here :

https://devblogs.microsoft.com/scripting/understanding-non-terminating-errors-in-powershell/

https://devblogs.microsoft.com/powershell/erroraction-and-errorvariable/

Upvotes: 1

Mark Wragg
Mark Wragg

Reputation: 23415

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

Upvotes: 1

Related Questions