ZetCode

PowerShell 字符串

最后修改:2025 年 2 月 15 日

在本文中,我们将介绍 PowerShell 中的字符串。

字符串创建

我们可以在 PowerShell 中使用单引号或双引号创建字符串。

strings1.ps1
$str1 = 'This is a string.'
$str2 = "This is also a string."

在此程序中,我们创建了两个字符串:$str1$str2

PS C:\> .\strings1.ps1

我们运行脚本,没有看到任何输出。字符串只有在我们明确要求时才会显示。

字符串显示

我们可以使用 Write-Output cmdlet 显示字符串的内容。

strings2.ps1
$str1 = 'This is a string.'
Write-Output $str1
PS C:\> .\strings2.ps1
This is a string.

字符串连接

我们可以使用 + 运算符连接字符串。

strings3.ps1
$str1 = 'This is a string.'
$str2 = 'This is another string.'

$str3 = $str1 + ' ' + $str2
Write-Output $str3
PS C:\> .\strings3.ps1
This is a string. This is another string.

字符串插值

字符串插值是一种功能,它允许我们将表达式嵌入到字符串字面量中进行求值。

strings4.ps1
$name = 'John Doe'
Write-Output "Hello, $name!"
PS C:\> .\strings4.ps1
Hello, John Doe!

字符串操作

PowerShell 提供了许多用于操作字符串的方法。

strings5.ps1
$str = 'This is a string.'

# Length
Write-Output $str.Length

# Uppercase
Write-Output $str.ToUpper()

# Lowercase
Write-Output $str.ToLower()

# Trim
Write-Output $str.Trim()
PS C:\> .\strings5.ps1
21
THIS IS A STRING.
this is a string.
This is a string.

来源

PowerShell 文档

在本文中,我们介绍了 PowerShell 中的字符串。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在教学编程方面拥有十多年的经验。

列出 所有 PowerShell 教程