约 2080 字

约 10 分钟

#PowerShell 的第一个脚本

#创建脚本文件

PowerShell 脚本是以 .ps1 为扩展名的文本文件。例如创建 hello.ps1:

> New-Item hello.ps1
> Set-Content hello.ps1 'Write-Output "Hello World"'

脚本内容也可以通过任意文本编辑器编写:

hello.ps1

Write-Output "Hello World"

#运行脚本

使用 pwsh 显式运行脚本:

> pwsh -File hello.ps1
Hello World

在当前会话中,也可以通过调用运算符 & 或点号 . 运行:

> & ./hello.ps1
Hello World
  • & 在新的作用域中运行脚本。
  • . 在当前作用域中运行脚本,脚本中定义的变量和函数会保留在当前会话中。

在 Linux 和 macOS 上,如果脚本第一行包含 shebang,并且文件具有可执行权限,可以直接运行:

hello.ps1

#!/usr/bin/env pwsh
Write-Output "Hello World"
$ chmod +x hello.ps1
$ ./hello.ps1
Hello World

#执行策略

Windows 上的 PowerShell 默认会限制脚本的执行。查看当前执行策略:

> Get-ExecutionPolicy

如果运行脚本时出现“禁止运行脚本”的错误,可以将当前用户的执行策略设置为 RemoteSigned:

> Set-ExecutionPolicy -Scope CurrentUser RemoteSigned

详见 执行策略。

#接收参数

脚本可以使用 param 块声明参数:

greet.ps1

param(
    [string]$Name = "World"
)

Write-Output "Hello $Name"

运行并传入参数:

> pwsh -File greet.ps1 -Name "PowerShell"
Hello PowerShell
  • [string] 指定参数类型。
  • = "World" 指定默认值。

#返回值与退出码

脚本可以使用 exit 设置退出码:

check.ps1

param([string]$Path)

if (Test-Path $Path) {
    Write-Output "存在:$Path"
    exit 0
}
else {
    Write-Output "不存在:$Path"
    exit 1
}
> pwsh -File check.ps1 -Path ./hello.ps1
存在:./hello.ps1
> $LASTEXITCODE
0
  • $LASTEXITCODE 保存上一个外部程序或脚本的退出码。
  • $? 表示上一条命令是否成功(True 或 False)。

#注释

PowerShell 支持两种注释:

# 单行注释

<#
    多行注释
    可以跨越多行
#>

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2