> For the complete documentation index, see [llms.txt](https://docs.verge.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.verge.io/learn-the-platform/zh/mo-kuai-8-kai-fa-yu-devops/03-powershell-module.md).

# PowerShell 模块（PSVergeOS）

**PSVergeOS** 是一个跨平台的 PowerShell 模块，提供 **200 多个 cmdlet** 用于通过 REST API 管理 VergeOS 基础设施。如果你的团队已经在使用 PowerShell 管理 Windows Server、Active Directory 或 VMware，PSVergeOS 让你可以将这些相同的工作流和脚本模式扩展到 VergeOS —— 并且完全支持管道、Tab 补全，以及熟悉的 `动词-名词` cmdlet 命名约定。

## 需求与安装

| 要求             | 版本                  |
| -------------- | ------------------- |
| **PowerShell** | 7.4 或更高版本           |
| **VergeOS**    | 26.0 或更高版本          |
| **平台**         | Windows、macOS、Linux |

### 从 PowerShell Gallery 安装（推荐）

```powershell
Install-Module -Name PSVergeOS -Scope CurrentUser
```

### 手动安装（开发）

```powershell
git clone https://github.com/verge-io/PSVergeOS.git
Import-Module ./PSVergeOS/PSVergeOS.psd1
```

### 验证安装

```powershell
Get-Module PSVergeOS -ListAvailable
Get-Command -Module PSVergeOS | Measure-Object  # 应显示 200+ 个 cmdlet
```

## 身份验证

PSVergeOS 支持多种身份验证方式，以适应不同环境 —— 从交互式管理员会话到完全自动化的流水线。

### 交互式凭据

连接时提示输入用户名和密码：

```powershell
Connect-VergeOS -Server "vergeos.example.com"
# 交互式提示凭据
```

### PSCredential 对象

为非交互式脚本安全地存储凭据：

```powershell
$cred = Get-Credential
Connect-VergeOS -Server "vergeos.example.com" -Credential $cred
```

### API 令牌

在自动化流水线中使用预先生成的 API 令牌：

```powershell
Connect-VergeOS -Server "vergeos.example.com" -Token $env:VERGEOS_TOKEN
```

### 自签名证书

适用于使用自签名证书的实验室和开发环境：

```powershell
Connect-VergeOS -Server "192.168.1.100" -Token $token -SkipCertificateCheck
```

{% hint style="warning" %}
仅在 `-SkipCertificateCheck` 测试环境中使用。在生产系统中，请配置有效的 SSL 证书。
{% endhint %}

## 多服务器管理

PSVergeOS 可以管理 **多个 VergeOS 系统** ，并且只需一个 PowerShell 会话。使用 `-PassThru` 参数来捕获连接对象，并使用 `-Server` 参数来指定目标系统：

```powershell
# 连接到多个系统
$prod = Connect-VergeOS -Server "prod.vergeos.local" -Token $env:PROD_TOKEN -PassThru
$dev  = Connect-VergeOS -Server "dev.vergeos.local"  -Token $env:DEV_TOKEN  -PassThru

# 查询特定服务器上的 VM
Get-VergeVM -Server $prod
Get-VergeVM -Server $dev

# 切换默认连接
Set-VergeConnection -Server "prod.vergeos.local"
```

这对 **MSP** 尤其有价值，因为它们需要管理多个客户环境，或在不同的生产和开发 VergeOS 集群之间切换。

## cmdlet 类别

该模块将 200+ 个 cmdlet 组织为功能类别。每个类别都涵盖完整的 CRUD 生命周期以及特定资源操作。

| 类别          | 说明                            |
| ----------- | ----------------------------- |
| **连接**      | 连接、断开连接、管理服务器连接               |
| **虚拟机**     | 生命周期、电源控制、快照、磁盘、NIC、克隆        |
| **网络**      | 虚拟网络、防火墙规则、DNS、DHCP、诊断        |
| **VPN**     | IPSec 连接/策略、WireGuard 接口/对等节点 |
| **NAS 与存储** | NAS 服务、卷、CIFS/NFS 共享、快照、同步    |
| **租户**      | 配置、快照、存储/网络块分配                |
| **用户与组**    | 账户管理、权限、API 密钥                |
| **系统**      | 集群、节点、许可证、设置                  |
| **证书**      | SSL 证书管理                      |
| **标签**      | 资源标签和分类                       |
| **Webhook** | 事件驱动的自动化挂钩                    |
| **监控与任务**   | 告警、日志、异步任务跟踪                  |
| **备份与灾难恢复** | 快照配置文件、云快照、站点管理、同步            |
| **文件与媒体**   | ISO 管理、文件上传                   |
| **资源组**     | 逻辑资源分组                        |

### VPN cmdlet（IPSec 与 WireGuard）

VPN 类别值得特别关注——PSVergeOS 为 IPSec 和 WireGuard VPN 实现都提供完整管理：

**IPSec：**

* `New-VergeIPSecConnection` / `Get-VergeIPSecConnection` / `Remove-VergeIPSecConnection`
* `New-VergeIPSecPolicy` / `Get-VergeIPSecPolicy` / `Remove-VergeIPSecPolicy`

**WireGuard：**

* `New-VergeWireGuardInterface` / `Get-VergeWireGuardInterface` / `Remove-VergeWireGuardInterface`
* `New-VergeWireGuardPeer` / `Get-VergeWireGuardPeer` / `Remove-VergeWireGuardPeer`

## 管道支持

PSVergeOS 最大的优势之一是 **完整的 PowerShell 管道支持**。cmdlet 接受管道输入并生成管道输出，从而支持用于批量操作的简洁单行命令：

```powershell
# 停止所有开发环境 VM
Get-VergeVM -Name "Dev-*" | Stop-VergeVM -Confirm:$false

# 为所有生产 VM 创建快照
Get-VergeVM -Name "Prod-*" | ForEach-Object {
    New-VergeVMSnapshot -VMName $_.Name -Name "Daily-$(Get-Date -Format 'yyyyMMdd')"
}

# 为特定网络中的所有 VM 开机
Get-VergeVM | Where-Object { $_.Network -eq "app-network" } | Start-VergeVM
```

管道支持使 PSVergeOS 对以下场景特别有效： **计划维护** 任务，与 Windows 任务计划程序或 Linux cron 作业集成。

## 实际示例

### 带保留策略的批量快照

```powershell
# 连接到 VergeOS 系统
Connect-VergeOS -Server "vergeos.example.com" -Token $env:VERGEOS_TOKEN

# 为所有正在运行的生产 VM 创建快照，并保留 24 小时
$vms = Get-VergeVM -Name "Prod-*" | Where-Object { $_.PowerState -eq "Running" }

foreach ($vm in $vms) {
    $snapshot = New-VergeVMSnapshot -VMName $vm.Name `
        -Name "Nightly-$(Get-Date -Format 'yyyyMMdd-HHmm')" `
        -Retention 86400
    Write-Host "已为 $($vm.Name) 创建快照：$($snapshot.Name)"
}

Write-Host "已完成 $($vms.Count) 个快照"
```

### VM 清单 CSV 导出

```powershell
# 将完整的 VM 清单导出为 CSV 用于报告
Get-VergeVM | Select-Object Name, PowerState, RAM, CPUCores, OS,
    @{N='DiskGB'; E={[math]::Round($_.DiskSize / 1GB, 2)}},
    Created, Description |
    Export-Csv -Path "vm-inventory-$(Get-Date -Format 'yyyyMMdd').csv" -NoTypeInformation

Write-Host "清单已导出到 vm-inventory-$(Get-Date -Format 'yyyyMMdd').csv"
```

### 使用防火墙规则创建网络

```powershell
# 创建一个带 DHCP 和防火墙规则的内部网络
$network = New-VergeNetwork -Name "web-tier" `
    -NetworkAddress "10.20.1.0/24" `
    -IPAddress "10.20.1.1" `
    -DHCPEnabled $true

# 添加防火墙规则
New-VergeNetworkRule -Network $network.Name `
    -Name "Allow HTTPS" -Action Accept -Protocol TCP -DestPort 443

New-VergeNetworkRule -Network $network.Name `
    -Name "Allow SSH" -Action Accept -Protocol TCP -DestPort 22

# 应用规则并启动
Invoke-VergeNetworkApplyRules -Network $network.Name
Start-VergeNetwork -Name $network.Name

Write-Host "网络 '$($network.Name)' 已联机并应用了防火墙规则"
```

### 多租户资源报告

```powershell
# 生成所有租户的资源汇总
$report = @()

foreach ($tenant in Get-VergeTenant) {
    $tenantVMs = Get-VergeVM -Tenant $tenant.Name
    $report += [PSCustomObject]@{
        Tenant    = $tenant.Name
        VMCount   = $tenantVMs.Count
        TotalRAM  = ($tenantVMs | Measure-Object -Property RAM -Sum).Sum
        TotalCPU  = ($tenantVMs | Measure-Object -Property CPUCores -Sum).Sum
        Running   = ($tenantVMs | Where-Object PowerState -eq "Running").Count
        Stopped   = ($tenantVMs | Where-Object PowerState -ne "Running").Count
    }
}

$report | Format-Table -AutoSize
$report | Export-Csv "tenant-report.csv" -NoTypeInformation
```

### WireGuard VPN 设置

```powershell
# 在外部网络上创建一个 WireGuard 接口
$wgInterface = New-VergeWireGuardInterface -Network "External" `
    -Name "Remote-Access" `
    -IPAddress "10.100.0.1/24" `
    -ListenPort 51820

# 为远程用户添加一个对等节点
New-VergeWireGuardPeer -Interface $wgInterface.Name `
    -Name "Engineer-1" `
    -AllowedIPs "10.100.0.2/32" `
    -AutoGenerateConfig $true

# 应用网络规则
Invoke-VergeNetworkApplyRules -Network "External"
```

## 与任务计划程序集成

PSVergeOS 脚本可自然集成到计划任务系统中，实现无人值守自动化：

**Windows 任务计划程序：**

```powershell
# 保存为 C:\Scripts\nightly-snapshot.ps1
Import-Module PSVergeOS
Connect-VergeOS -Server "vergeos.local" -Token $env:VERGEOS_TOKEN -SkipCertificateCheck
Get-VergeVM -Name "Prod-*" | ForEach-Object {
    New-VergeVMSnapshot -VMName $_.Name -Name "Nightly-$(Get-Date -Format 'yyyyMMdd')" -Retention 86400
}
Disconnect-VergeOS
```

**Linux cron（PowerShell 7.4+）：**

```bash
# 每天凌晨 2:00 运行
0 2 * * * /usr/bin/pwsh -File /opt/scripts/nightly-snapshot.ps1
```

## 常见使用场景

### 批量 VM 操作

使用管道单行命令停止、启动、创建快照或迁移多个 VM。非常适合维护窗口。

### 基础设施报告

将 VM 清单、资源使用情况和配置数据导出为 CSV，用于审计和容量规划。

### 网络自动化

以编程方式创建网络、配置 DHCP、管理防火墙规则并设置 VPN 隧道。

### 计划维护

与任务计划程序或 cron 集成，用于自动快照、清理和合规性检查。

{% hint style="info" %}
**来自 VMware 或 Nutanix？**

PSVergeOS 使用标准的 PowerShell `动词-名词` 约定，因此肌肉记忆可以直接沿用 — `Get-VM | Stop-VM` 变成 `Get-VergeVM | Stop-VergeVM`。身份验证支持交互式提示、 `PSCredential` 对象以及 API 令牌，因此你已经用于非交互式自动化的相同脚本模式也适用于这里。要从单个会话管理多个 VergeOS 系统，请在每个 cmdlet 上传递 `-Server` 以便针对特定连接。
{% endhint %}

## 其他资源

* [GitHub 仓库](https://github.com/verge-io/PSVergeOS) — 源代码、问题和 16 个示例脚本
* [PowerShell Gallery](https://www.powershellgallery.com/packages/PSVergeOS) — 最新版本和安装信息
* [PowerShell 7.4 文档](https://learn.microsoft.com/en-us/powershell/) — PowerShell 运行时参考


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.verge.io/learn-the-platform/zh/mo-kuai-8-kai-fa-yu-devops/03-powershell-module.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
