sunny
sunny

Reputation: 71

Get the status of Invoke-Command

I have a command below to connect to remote computer and do the action:

$myfile = [System.IO.File]::ReadAllBytes("C:\temp\test.txt")
$session = $null
$session = New-PSSession -computerName $server -credential $user
Invoke-Command -Session $session -ArgumentList $myfile -ScriptBlock {[System.IO.File]::WriteAllBytes("C:\temp\test.txt", $args)}

But I am struggling to get the status of the process, how would I get the status of Invoke-Command?

I have tried like below but it's not working:

try {
    Invoke-Command -Session $session -ArgumentList $myfile -ScriptBlock {[System.IO.File]::WriteAllBytes("C:\temp\abc\Bank_Wiz_copy2.txt", $args)}
    $Stat = "Success"
}
catch {
    $Stat = "Failed"
}

Upvotes: 1

Views: 2858

Answers (1)

fdafadf
fdafadf

Reputation: 819

There is many ways. But in PowerShell the idea behind Invoke-Command is the script block specified is executed in the same manner as local script. So, you can do it like that:

try { Invoke-Command -Session $session -ScriptBlock { Write-Error "err" } -ErrorAction Stop } catch { Write-Host "!" }

Write-Error generates exception because of ErrorAction is Stop. Exception is transmitted over the session then you can catch it.

Upvotes: 4

Related Questions