当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 在 PowerShell 中打印空行 [2 种方法]

作者:精品下载站 日期:2024-12-14 05:27:18 浏览:14 分类:玩电脑

在 PowerShell 中打印空行 [2 种方法]


[玩转系统] 在 PowerShell 中打印空行 [2 种方法]

在 PowerShell 中打印空行

我们有两条字符串类型的消息要在 PowerShell 控制台上打印,但在中间,我们还希望有一个空行以增加可读性。例如,我们希望得到如下结果:

我们的最终结果应该是这样的:

String Message 1 Goes Here.
It Must Be a Blank Line
String Message 2 Goes Here.

为了做到上面演示的那样,我们可以使用不同的方法。下面让我们逐一了解一下。

使用Write-Host Cmdlet

使用 Write-Host cmdlet 在 PowerShell 中打印空行。

使用写入主机 Cmdlet:

$string1 = "This is string one."
$string2 = "This is string two."
Write-Host $string1
Write-Host ""
Write-Host $string2

输出 :

This is string one.

This is string two.

首先,我们创建了包含字符串类型值的 $string1$string2 变量。然后,我们使用 Write-Host cmdlet 打印 $string1、使用空字符串的空行 ("") 和 $string2Write-Host cmdlet 将自定义输出打印到主机;这里,host 指的是你的 PowerShell 控制台。因此,我们利用此优势和空字符串 ("") 与此 cmdlet 一起在 PowerShell 中打印空行。

在上述解决方案中,我们必须使用三个 Write-Host cmdlet。但是,假设您必须使用两个 Write-Host cmdlet 来满足要求。这是以下解决方案会有所帮助的地方。

使用反引号转义换行符

使用反引号字符转义换行符以在 PowerShell 中打印空行。

使用反引号转义换行符:

$string1 = "This is string one."
$string2 = "This is string two."
Write-Host "$string1`n"
Write-Host $string2

输出 :

This is string one.

This is string two.

在这里,我们使用反引号在 PowerShell 中打印空行。

如何在 PowerShell 中打印空行:

Before talking about the code, remember one thing, the Write-Host not only print the customized output but also jump to the next line. So, to have a blank line between $string1 and $string2, we used the newline character (`n) with the first Write-Host cmdlet. It means we will automatically be on newline due to using Write-Host, and `n will add one blank line. Finally, the second Write-Host cmdlet will print the value of the $string2 variable.

Write-Host cmdlet 使用 ToString() 方法在 PowerShell 控制台上写入输出。

此 cmdlet 的主要目的是协助仅显示输出,这意味着我们可以使用它来打印空白行、彩色文本等。我们可以使用 -ForegroundColor 指定文本的颜色>-BackgroundColor 参数。我们还可以使用-Separator参数来分隔显示的内容。这些具体结果基于托管 PowerShell 的程序。我们用下面的例子来理解一下。

使用写入主机 Cmdlet:

$string1 = "This is string one."
$string2 = "This is string two."
$array = @($string1, $string2)
Write-Host $array -Separator "`n" -ForegroundColor DarkGreen -BackgroundColor White

输出:

[玩转系统] 在 PowerShell 中打印空行 [2 种方法]

与前面的示例一样,我们定义并初始化了 $string1$string2 变量。接下来,我们使用数组运算符 (@()) 创建一个数组,其中包含 $string1$string2 元素。然后,我们使用 Write-Host 在 PowerShell 控制台上进行打印。

请注意,我们使用了一个 Write-Host,因此我们不会自动换行。这就是为什么我们使用两个`n;第一个移动到下一行,第二个添加空行。此外,-ForegroundColor-BackgroundColor 用于设置前景色和背景色,如上面的输出所示。

这就是如何在 PowerShell 中打印空行。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯