【问题标题】:Powershell: Cannot read and write a variable on Hyperv-V VM from hostPowershell:无法从主机读取和写入 Hyperv-V VM 上的变量
【发布时间】:2021-09-19 14:11:53
【问题描述】:

使用这个 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)}

如您所见,结果为空。谁能帮我展示如何从主机上写入和读取虚拟机上的变量?谢谢!

【问题讨论】:

    标签: powershell virtual hyper-v


    【解决方案1】:

    使用Invoke-Command to run a command remotely 时,命令中的任何变量都将在远程计算机上进行评估。因此,当您运行第一个 Invoke-Command 时,您只需定义变量 $InstallPath 并终止远程 PS 会话。当您第二次运行Invoke-Command 时,它会创建全新的PS 会话,因此InstallPath 将是null。而不是这个,您可以定义和阅读variable in a single Cmdlet like this

    $remoteScriptblock = {
    $InstallPath = "C:\Install\install-1.ps1"
    写主机($InstallPath)
    }
    调用命令 -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock $remoteScriptblock
    

    如果您仍想在多个 Cmdlet 中运行它,您可以考虑 Run a command in a persistent connection

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-04
      • 2015-08-08
      • 2014-03-27
      • 1970-01-01
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      相关资源
      最近更新 更多