Powershell:无法从主机读取和写入 Hyperv-V VM 上的变量
Powershell: Cannot read and write a variable on Hyperv-V VM from host
我尝试使用此 Powershell 脚本在主机上写入和读取 VM 上的变量。
$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)}
如您所见,结果为空。谁能帮我展示如何从主机在 VM 上写入和读取变量?谢谢!
使用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
如果您仍想 运行 在多个 Cmdlet 中执行此操作,您可以考虑 Run a command in a persistent connection
我尝试使用此 Powershell 脚本在主机上写入和读取 VM 上的变量。
$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)}
如您所见,结果为空。谁能帮我展示如何从主机在 VM 上写入和读取变量?谢谢!
使用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
如果您仍想 运行 在多个 Cmdlet 中执行此操作,您可以考虑 Run a command in a persistent connection