[英]How do I change which Powershell version is used in a remote session?
我有一個 Powershell 腳本,它創建一個 session 到虛擬機。 在這個遠程 session 中,我希望機器從 json 文件中讀取數據,並從該數據中返回一個自定義 object,因此我使用 -AsHashtable 標志來轉換 doFrom-Json 命令。 However this flag was introduced in Powershell 6 and when I write the powershell version from the remote session to the output the session displays "5.1" as powershell version...
虛擬機安裝了 Powershell 7.2.5,當手動登錄到 vm 並啟動 Powershell 7 並執行命令時,它按預期運行。 如何告訴我的腳本中的 session 使用 Powershell 7?
This code assumes that the PowerShell ZIP package has been downloaded and unzipped to the remote computer's C:\Users\Public\PSv7\
path. 如果在遠程計算機上使用安裝程序安裝了 PowerShell 7,則C:\Users\Public\PSv7\pwsh.exe
可能會簡化為pwsh
。 -ExecutionPolicy RemoteSigned
可能不需要,但我建議保留-NoProfile
以提高性能。
$ComputerName = 'RemotePCName'
$Temp = Invoke-Command -ComputerName $ComputerName -ScriptBlock {
if($PSVersionTable.PSVersion.Major -lt 7) {
return (C:\Users\Public\PSv7\pwsh.exe -NoProfile -ExecutionPolicy RemoteSigned $MyInvocation.MyCommand.ScriptBlock)
}
else {
return "[$($Env:ComputerName)] {$($PSVersionTable.PSVersion)}"
}
}
Write-Host "$Temp"
編碼:
Else
塊中,將當前機器的名稱和 PowerShell 版本作為字符串返回。else
部分的 PowerShell 版本。 命令,例如ConvertFrom-Json -AsHashtable
,應該在else
語句中運行良好。
這是我第一次嘗試從 PowerShell 中將 ScriptBlock 傳遞給 pwsh.exe,所以它似乎可以工作,但我不確定 pwsh.exe 如何接收 ScriptBlock 或在退出時返回信息。 如果 pwsh.exe 只能返回[string]
值,我不會感到驚訝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.