Search code examples
arrayspowershellpowershell-remoting

How to get an variable output from remote pssession


I have a script to get virtual harddisk info from vmm, im executing it remotely from a server, currently im unable to get the variable value outside of the pssession in the local host, could you please help me out with achieveing the same.

PS C:\Windows\system32> enter-pssession iscvmm02
[iscvmm02]: PS C:\Users\su\Documents>Add-PSSnapin Microsoft.SystemCenter.VirtualMachineManager
[iscvmm02]: PS C:\Users\su\Documents>$hide= Get-VMMServer -ComputerName "iscvmm02.corp.avanade.org"
[iscvmm02]: PS C:\Users\su\Documents>$VM = Get-VM | where { $_.ComputerNameString -contains "idpsm02.corp.air.org" }
[iscvmm02]: PS C:\Users\su\Documents>$harddisk=$VM.VirtualHardDisks
[iscvmm02]: PS C:\Users\su\Documents>$h=$harddisk.length
[iscvmm02]: PS C:\Users\su\Documents>for($i=0;$i-lt$h;$i++){
    New-Variable -Name "HardDiskType_$i" -value $harddisk[$i].vhdtype
    New-Variable -Name "HardDiskLocation_$i" -value $harddisk[$i].Location
}
[iadpscvmm02]: PS C:\Users\su\Documents>Exit-PSSession
PS C:\Windows\system32>$harddisktype_0
PS C:\Windows\system32>$harddisklocation_0

as you can see both the variable output's give null value, im unable to retain the values


Solution

  • This example gets listing from remote computer's C drive and assigns it into a local variable. So tune your VMM script accordingly.

    $session = New-PSSession -ComputerName RemoteSystem
    Invoke-Command -Session $session -ScriptBlock { $remoteC = gci c:\ }
    # This shouldn't print anything.
    $localC
    # Print the result on remote computer an assing its output to localC variable
    $localC = Invoke-Command -Session $session  -ScriptBlock { $remoteC }
    # Print the local variable, it should contain remoteC data.
    $localC