使用這個Powershell腳本,我試圖從主機上寫入和讀取虛擬機上的一個變數。
$Username = 'administer'
$Password = 'password'/span>
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass >。
#添加值到VM上的一個變數。
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock {$InstallPath="C:Installinstall-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)}。
如你所見,結果是空的。誰能幫助我說明如何從主機上寫入和讀取虛擬機上的變數?謝謝!
uj5u.com熱心網友回復:
當使用Invoke-Command來遠程運行一個命令時,命令中的任何變數都會在遠程計算機上評估。因此,當你運行第一個Invoke-Command時,你只是定義了變數$InstallPath并終止了遠程PS會話。當你第二次運行Invoke-Command時,它會創建全新的PS會話,因此InstallPath將是null。相反,你可以在一個Cmdlet中定義并讀取變數,像這樣。
$remoteScriptblock = {
$InstallPath = "C:Installinstall-1.ps1"
Write-Host($InstallPath)
}
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock $remoteScriptblock
如果你仍然想在多個Cmdlets中運行這個,你可以考慮在持久化連接中運行一個命令
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326684.html
標籤:
