Write-Host
将自定义输出写入主机。
语法
Write-Host
[[-Object] <Object>]
[-NoNewline]
[-Separator <Object>]
[-ForegroundColor <ConsoleColor>]
[-BackgroundColor <ConsoleColor>]
[<CommonParameters>]
说明
Write-Host
cmdlet 自定义输出。
可以使用 ForegroundColor
参数指定文本的颜色,还可以使用 BackgroundColor
参数指定背景色。
使用分隔符参数可以指定要用于分隔显示对象的字符串。
特定结果取决于托管 PowerShell 的程序。
注意
从 Windows PowerShell 5.0 开始,Write-Host
是 Write-Information
的包装器。这允许你使用 Write-Host
向信息流发出输出。
这使 捕获 或 抑制 使用 Write-Host
写入的数据,同时保持向后兼容性。
$InformationPreference
首选项变量和 InformationAction
通用参数不会影响 Write-Host
消息。
此规则的例外是 -InformationAction Ignore
,它有效地抑制了 Write-Host
输出。 (请参阅“示例 5”)
示例
示例 1:写入控制台而不添加新行
Write-Host "no newline test " -NoNewline
Write-Host "second string"
no newline test second string
此命令使用 NoNewline
参数显示字符串“无换行测试”。
写入第二个字符串,但由于缺少分隔字符串的新行,它最终与第一行位于同一行。
示例 2:写入控制台并包含分隔符
Write-Host (2,4,6,8,10,12) -Separator ", +2= "
2, +2= 4, +2= 6, +2= 8, +2= 10, +2= 12
此命令显示 2 到 12 之间的偶数。
分隔符参数用于添加字符串 , +2= (comma, space, +, 2, =, space)
。
示例 3:使用不同的文本和背景色进行写入
Write-Host (2,4,6,8,10,12) -Separator ", -> " -ForegroundColor DarkGreen -BackgroundColor White
2, -> 4, -> 6, -> 8, -> 10, -> 12
此命令显示 2 到 12 之间的偶数。
它使用 ForegroundColor
参数输出“深绿色”文本和 BackgroundColor
参数来显示“白色”背景。
示例 4:使用不同的文本和背景色进行写入
Write-Host "Red on white text." -ForegroundColor red -BackgroundColor white
Red on white text.
此命令显示字符串“白色文本上的红色”。文本为“red”,由 ForegroundColor
参数定义。
背景为“white”,由 BackgroundColor
参数定义。
示例 5:禁止显示来自 Write-Host 的输出
# The following two statements can be used to effectively suppress output from Write-Host
Write-Host "I won't print" -InformationAction Ignore
Write-Host "I won't print" 6>$null
此命令显示字符串“白色文本上的红色”。文本为“red”,由 ForegroundColor
参数定义。
背景为“white”,由 BackgroundColor
参数定义。
参数
-BackgroundColor
指定背景色。 没有默认值。 此参数的可接受值为:
- 黑
- 深蓝
- 深绿色
- 深青色
- DarkRed
- DarkMagenta
- DarkYellow
- 灰色
- DarkGray
- 蓝
- 绿
- 青色
- 红
- 品红
- 黄色
- 白
类型: | ConsoleColor |
接受的值: | Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White |
Position: | Named |
默认值: | None |
必需: | False |
接受管道输入: | False |
接受通配符: | False |
-ForegroundColor
指定文本颜色。 没有默认值。 此参数的可接受值为:
- 黑
- 深蓝
- 深绿色
- 深青色
- DarkRed
- DarkMagenta
- DarkYellow
- 灰色
- DarkGray
- 蓝
- 绿
- 青色
- 红
- 品红
- 黄色
- 白
类型: | ConsoleColor |
接受的值: | Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White |
Position: | Named |
默认值: | None |
必需: | False |
接受管道输入: | False |
接受通配符: | False |
-NoNewline
输入对象的字符串表示形式串联成输出。 输出字符串之间不插入空格或换行符。 最后一个输出字符串之后不会添加换行符。
类型: | SwitchParameter |
Position: | Named |
默认值: | None |
必需: | False |
接受管道输入: | False |
接受通配符: | False |
-Object
要显示在主机中的对象。
类型: | Object |
Position: | 0 |
默认值: | None |
必需: | False |
接受管道输入: | True |
接受通配符: | False |
-Separator
指定要在主机显示的对象之间插入的分隔符字符串。
类型: | Object |
Position: | Named |
默认值: | None |
必需: | False |
接受管道输入: | False |
接受通配符: | False |
输入
可以通过管道将对象写入主机。
输出
None
Write-Host
将对象发送到主机。
它不返回任何对象。
但是,主机可能会显示 Write-Host
发送到它的对象。