Vasyl Stepulo
Vasyl Stepulo

Reputation: 1603

Execute Powershell code on remote computer and then use result on local computer

I know, that to execute code on remote computer, I must use -ArgumentList and param to pass variables to remote host.

Can anyone hint me, how to execute code on remote computer, and then use result on local computer?

My code, to determine free space on remote computer, and, depending on result - fail build, if remote host has not enough space:

$securePassword = ConvertTo-SecureString $env:password -AsPlainText -force
$credential = New-Object System.Management.Automation.PsCredential("$env:login",$securePassword)
Invoke-Command -ComputerName $env:SERVER -credential $credential -scriptblock {
$freespace = Get-PSDrive D
echo $freespace.Free
$DiskDSpace = ($freespace.Free) 
If ($DiskDSpace -lt 214748364809999999999999) { 
    echo "Free space on disk D is less than 20 GB" 
    $LastExitCode = 1
    exit $LastExitCode 
    }
}

Problem, is that $DiskDSpace variable value only present on remote computer and Jenkins fails build only, if "$LastExitCode = 1" & "exit $LastExitCode" executed outside "-scriptblock {"

Upvotes: 0

Views: 212

Answers (1)

Bernard Moeskops
Bernard Moeskops

Reputation: 1283

$diskSpace = Invoke-Command -ComputerName $env:SERVER -credential $credential -scriptblock {
$freespace = Get-PSDrive D
echo $freespace.Free
$DiskDSpace = ($freespace.Free) 
If ($DiskDSpace -lt 214748364809999999999999) { 
    echo "Free space on disk D is less than 20 GB" 
    $LastExitCode = 1
    exit $LastExitCode 
    }
}

Note the $diskSpace before the Invoke-Command. This should do the trick!

Upvotes: 1

Related Questions