使用 PowerShell 连接到 Windows 虚拟机


本文档介绍如何使用 PowerShell 连接到 Windows 虚拟机实例。

准备工作

  • 设置身份验证(如果尚未设置)。身份验证是通过其进行身份验证以访问 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

    1. 安装 Google Cloud CLI,然后通过运行以下命令初始化 Google Cloud CLI:

      gcloud init
    2. Set a default region and zone.

使用 PowerShell 进行连接

如果您拥有带 PowerShell 的 Windows 工作站,可以通过远程 PowerShell 会话连接到 Windows Server 实例。

  1. 如果尚未在远程 Windows 实例上创建用户名和密码,请创建或重置 Windows 密码

  2. 添加一条防火墙规则,该规则必须在 Windows Server 实例所在的 Google Cloud VPC 网络上打开端口 5986

  3. 在本地工作站上,打开 PowerShell 终端。

  4. 可选:您可以初始化变量以保留用户凭据,这样您就无需在每次连接到实例时输入这些凭据。如果您跳过此步骤,系统之后会提示您输入用户名和密码。

    $credentials = Get-Credential
    
  5. 选择要建立交互式 Powershell 会话还是以远程方式调用 Windows Server 虚拟机上的命令

建立交互式 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 虚拟机上的命令

作为 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" 可获取日志事件列表。

后续步骤