powershellinvoke-command

How to get local variable value from Invoke-command -Asjob?


I want to run [System.Net.Dns]::GetHostAddresses("mail") on remote computers and write it.

Foreach($PCName in $PCNameArray) {
    $arrayJobs += Invoke-Command -Credential $cred -scriptblock { 
                param (
                    [String]$ip                )
                $IPs = [System.Net.Dns]::GetHostAddresses("mail")
                $ip = $ips[0]
    } -ComputerName $PCName -AsJob -ArgumentList $ip
}

Wait-Job $arrayJobs

$ResultArray=[System.Collections.ArrayList]@()

foreach ($job in $arrayJobs) {
    if ($job.State -eq 'Completed') {
        $ResultArray += Receive-Job $job
    } 
    Stop-Job $job
}

$ResultArray | Select PsComputerName,ip | Export-Csv $OutputFile -NoTypeInformation -Delimiter ';' -Encoding UTF8

How can get $ip value from inside Invoke-Command for all jobs?


Solution

  • As mentioned in the comments, all you have to do is to not assign the desired value to a variable, and instead let PowerShell return it:

    Foreach($PCName in $PCNameArray) {
        $arrayJobs += Invoke-Command -Credential $cred -scriptblock { 
                    param (
                        [String]$ip                )
                    $IPs = [System.Net.Dns]::GetHostAddresses("mail")
                    $ips[0] # don't assign, just evaluate
        } -ComputerName $PCName -AsJob -ArgumentList $ip
    }
    
    Wait-Job $arrayJobs
    
    $ResultArray=[System.Collections.ArrayList]@()
    
    foreach ($job in $arrayJobs) {
        if ($job.State -eq 'Completed') {
            $ResultArray += Receive-Job $job
        } 
        Stop-Job $job
    }
    
    $ResultArray | Select PsComputerName,@{Name='IP';Expression='IPAddressToString'} | Export-Csv $OutputFile -NoTypeInformation -Delimiter ';' -Encoding UTF8
    

    The IPAddressToString property on the resulting [ipaddress] objects will give you the string representation, eg. 10.0.0.1