如何在 Windows PowerShell 中输出结果
-
PowerShell 中的
Write-Output
Cmdlet -
PowerShell 中的
Write-Host
Cmdlet -
PowerShell 中的
Write-Debug
Cmdlet -
PowerShell 中的
Write-Verbose
Cmdlet

将输出写入控制台是任何语言中的一个基本过程,因为它可以正确反馈给用户。然而,在 Windows PowerShell 中,有多种打印输出的方式。本文将区分多种 Write
cmdlet,并提供我们何时与何地使用它们的情况。
在讨论 cmdlet 之前,值得注意的是 Windows PowerShell 可以通过用双引号(""
)括起单行文本来输出内容。
示例代码:
"Hello World!"
输出:
Hello World!
由于字符串字面量表达式和隐含管道,这种语法在 Windows PowerShell 中是可能的。这种语法等同于以下示例代码。
示例代码:
"Hello World!" | Out-Host
另一方面,Out-Host
cmdlet 将对象发送到显示之前。
PowerShell 中的 Write-Output
Cmdlet
Windows PowerShell 中的第一个打印方法是 Write-Output
cmdlet。这个 cmdlet 是在我们的 PowerShell 脚本环境中打印的基本语法。我们可以将其比作许多语言的基本打印命令,例如 print
和 stdout
。
示例代码:
Write-Output "Hello World!"
输出:
Hello World!
PowerShell 中的 Write-Host
Cmdlet
Write-Host
cmdlet 是另一种打印方法,类似于前面的 Write-Output
方法。唯一的区别是它可以使用参数 -BackgroundColor
和 -ForegroundColor
输出不同的颜色。
PowerShell 中的 Write-Debug
Cmdlet
Write-Debug
cmdlet 也是 Windows PowerShell 中的另一个打印方法。然而,这通常用于在脚本环境中打印调试消息。这些消息默认情况下不显示,但可以通过使用变量 $debugPreference
显示。
示例代码:
Write-Debug "Error on line 1 but will silently continue."
$debugPreference = "Continue"
Write-Debug "Error on line 3 will now be displayed"
输出:
DEBUG: Error on line 3 will now be displayed
PowerShell 中的 Write-Verbose
Cmdlet
Write-Verbose
cmdlet 将文本写入 Windows PowerShell 的详细消息流。详细消息流旨在提供有关命令处理的更多信息。与 Write-Debug
类似,详细消息默认情况下不显示,但可以通过使用变量 $VerbosePreference
或者添加切换参数 -Verbose
来显示。
示例代码:
Write-Verbose -Message "This will not be displayed."
Write-Verbose -Message "This will be displayed" -Verbose
输出:
VERBOSE: This will be displayed
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn