约 2221 字

约 11 分钟

#字符串与插值

#简介

字符串是 PowerShell 中最常用的数据类型之一。PowerShell 支持单引号、双引号、here-string 等多种写法,并提供了丰富的插值和格式化能力。

#单引号与双引号

单引号字符串是字面量,其中的变量不会被替换;双引号字符串会进行插值:

> $name = "PowerShell"
> 'Hello $name'
Hello $name
> "Hello $name"
Hello PowerShell

如果字符串本身包含引号,可以使用另一种引号包裹,或使用转义:

> 'It''s fine'
It's fine
> "He said `"hi`""
He said "hi"

#插值语法

简单的变量可以直接写在双引号中。当变量名后面紧跟其他字符时,需要用 ${} 明确边界:

> $name = "PS"
> "${name}7"
PS7

$() 用于插入表达式的结果:

> "Time: $(Get-Date -Format 'HH:mm')"
Time: 09:30
> "Sum: $(2 + 3)"
Sum: 5

#转义字符

反引号 ` 是 PowerShell 的转义字符:

转义序列含义
`n换行
`t制表符
`r回车
`"双引号
`$美元符号
``反引号本身
> "Line1`nLine2"
Line1
Line2
> "Price: `$10"
Price: $10

#Here-string

多行文本可以使用 here-string。双引号版本支持插值:

$text = @"
Hello, $name
Today is $(Get-Date -Format 'yyyy-MM-dd')
"@

单引号版本不进行插值:

$raw = @'
Hello, $name
No interpolation here.
'@

#格式化

-f 运算符按占位符格式化字符串:

> "{0} is {1} years old" -f "Tom", 18
Tom is 18 years old
> "{0:N2}" -f 3.14159
3.14
> "{0:yyyy-MM-dd}" -f (Get-Date)
2026-11-02

-join 将集合连接为字符串,-split 将字符串拆分为数组:

> @("a", "b", "c") -join ","
a,b,c
> "a,b,c" -split ","
a
b
c

#常用字符串方法

字符串对象提供了许多方法:

> $s = "  Hello World  "
> $s.Trim()
Hello World
> $s.Trim().ToUpper()
HELLO WORLD
> "PowerShell".Substring(0, 5)
Power
> "PowerShell".Replace("Shell", "Tip")
PowerTip
> "a-b-c".Split("-")
  • Trim() 去除首尾空白。
  • ToUpper()、ToLower() 转换大小写。
  • Substring()、Replace()、Split() 用于截取、替换和拆分。
  • 使用 Get-Member 可以查看字符串的全部成员,详见 Get-Member 帮助手册。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2