本文說明如何使用 PowerShell 連線至 Windows 虛擬機器 (VM) 執行個體。
事前準備
-
如果尚未設定,請先設定驗證機制。驗證是指驗證身分,以便存取 Google Cloud 服務和 API 的程序。如要在本機開發環境中執行程式碼或範例,您可以選取下列任一選項,向 Compute Engine 進行驗證:
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
gcloud
-
After installing the Google Cloud CLI, initialize it by running the following command:
gcloud init
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
- Set a default region and zone.
-
使用 PowerShell 連線
如果您的 Windows 工作站內含 PowerShell,就可以透過遠端 PowerShell 工作階段連線至 Windows Server 執行個體。
如果您尚未在遠端 Windows 執行個體上建立使用者名稱和密碼,請建立或重設 Windows 密碼。
新增防火牆規則,該規則必須能在 Windows Server 執行個體所在的 Google Cloud VPC 網路上開啟通訊埠
5986
。在本機工作站上,開啟 PowerShell 終端機。
選用:您可以初始化變數來保留您的使用者憑證,這樣您就不需要每次連線至執行個體時都輸入這些憑證。如果略過這個步驟,系統之後會提醒您輸入使用者名稱與密碼。
$credentials = Get-Credential
建立互動式 PowerShell 工作階段
如要建立 PowerShell 工作階段,請執行下列指令:
Enter-PSSession -ComputerName IP_ADDRESS -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck) -Credential $credentials
將 IP_ADDRESS
替換成您要連線的執行個體的外部 IP 位址、DNS 名稱或 Windows 電腦名稱。
連線之後,指令提示字元會變更為包含遠端 Windows 執行個體的 IP 位址。現在,您可以使用終端機在遠端 Windows Server 執行個體上執行 PowerShell 指令。
從遠端叫用 Windows Server VM 上的指令
除了 Enter-PSSession
指令以外,您也可以搭配 -ScriptBlock
旗標執行 Invoke-Command
,以便在遠端執行個體上執行 PowerShell 指令,而不建立互動工作階段。
Invoke-Command -ComputerName IP_ADDRESS -ScriptBlock { SCRIPT } -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck) -Credential $credentials
更改下列內容:
IP_ADDRESS
:您要連線的執行個體的 IP 位址、DNS 名稱或 Windows 電腦名稱。SCRIPT
:要在遠端執行個體上執行的一或多個指令。例如,指定Get-EventLog -log "Windows PowerShell"
可取得記錄事件清單。