Using this Powershell script I try to write and read a variable on VM from host.
$Username = 'administrator'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
#Added value to a variable on VM
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock {$InstallPath="C:\Install\install-1.ps1"}
#Trying to read the variable on VM but with no result
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock {Write-Host($InstallPath)}
As you see the result is empty. Can anyone help me to show how to write and read an variable on VM from host machine? Thanks!
CodePudding user response:
When using Invoke-Command
to run a command remotely, any variables in the command are evaluated on the remote computer. So when you run the first Invoke-Command
you are only defining the variable $InstallPath
and terminating the remote PS session. When you are run the Invoke-Command
second time it create entirely new PS session, hence InstallPath
would be null
. Instead of this you can define and read the variable in a single Cmdlet like this.
$remoteScriptblock = { $InstallPath = "C:\Install\install-1.ps1" Write-Host($InstallPath) } Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock $remoteScriptblock
If you still want to run this in multiple Cmdlets you may consider Run a command in a persistent connection