在 PowerShell 的命令输出中添加新行

  1. 在 PowerShell 中使用`n 的命令输出中添加新行
  2. 在 PowerShell 中使用外场分隔符 OFS
  3. 在 PowerShell 中使用 [Environment]::NewLine
在 PowerShell 的命令输出中添加新行

PowerShell 包含一组可以自定义输出内容的特殊字符序列。这些序列通常称为转义序列。它们以反引号字符 ` 开头并且区分大小写。

转义序列的一些示例是 `0`a`b`e`f`n`r 等。转义序列仅在用双引号 " " 括起来时才被解释。

本文将讨论在 PowerShell 中向命令输出添加新行的不同方法。

在 PowerShell 中使用`n 的命令输出中添加新行

`n 字符在输出中的字符之后插入一个新行或换行符。

Write-Host "This tutorial teaches you to add`na new line in PowerShell."

输出:

This tutorial teaches you to add
a new line in PowerShell.

你可以使用多个 `n 字符来添加多行。

Write-Host "This tutorial`nteaches you to add`n`n`nmultiple lines in PowerShell."

输出:

This tutorial
teaches you to add


multiple lines in PowerShell.

在 PowerShell 中使用外场分隔符 OFS

外场分隔符 OFS 允许你指定字符来分隔数组的元素。有效值是字符串,因此应将元素转换为字符串。

首先,你必须在 OFS 变量中定义一个分隔符。你必须设置两个 `n 作为分隔符才能添加单行。

$OFS="`n`n"
$color = 'red', 'blue', 'green', 'yellow'
"$($color)"

输出:

red

blue

green

yellow

在 PowerShell 中使用 [Environment]::NewLine

你还可以使用 [Environment]::NewLine 对象在命令输出中添加新行。

$new = [Environment]::NewLine
$color | ForEach {"$_$new"}

输出:

red

blue

green

yellow

[Environment]::NewLineSort-Object 一起使用的另一个示例。Sort-Object cmdlet 有助于按属性值升序或降序对对象进行排序。

以下命令获取计算机上所有已安装程序的名称,为每个程序的名称添加一个新行,然后对其进行排序。

$new = [Environment]::NewLine
Get-ChildItem HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall | ForEach{ $_.GetValue("DisplayName")} | Sort-Object | ForEach{"$_$new"}

输出:

Tools for .Net 3.5

AnyDesk

ASUS Aac_NBDT HAL

ASUS AURA Display Component

ASUS AURA Headset Component

ASUS Framework Service

ASUS Framework Service
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Rohan Timalsina
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website