更改 return 数据的颜色
Change color on return data
我正在尝试修改一个脚本,该脚本应该列出一个域中的所有计算机,如果有人登录到该计算机,它应该显示该帐户的用户名。
脚本运行良好,但我遇到了一些审美问题。有没有办法将 return 数据(对于那些在线的计算机和服务器)变成另一种颜色?
这是我当前的脚本:
function Check-Domain {
Get-ADComputer -Filter * |
Select-Object -ExpandProperty Name |
ForEach-Object {
$computer = $_
$pingme = Test-Connection -ComputerName $computer -Quiet -Count 1
if ($pingme -eq $true) {
Invoke-Command -ComputerName $computer -ScriptBlock {
Get-WmiObject Win32_ComputerSystem |
Select-Object Username, Name }
} else {
Write-Host "$computer - OFF" -ForegroundColor Red
}
} | Format-Table
}
您可以编辑这部分 - 这会将 Invoke-Command
的结果存储在一个变量中,并使用 Write-Host
:
以您喜欢的颜色输出它
if ($pingme -eq $true) {
$result = Invoke-Command -ComputerName $computer -ScriptBlock {
Get-WmiObject Win32_ComputerSystem | Select-Object Username, Name
}
Write-Host $result -ForegroundColor Green
}
当然,这很简单。只需将命令包裹在子表达式中,然后像使用离线服务器一样使用 Write-Host
。
{Write-Host $(Invoke-Command -ComputerName $computer -ScriptBlock { Get-WmiObject win32_computersystem | Select-Object username, name}) -ForegroundColor Green}
它将首先执行 $()
中的脚本,然后将其输出应用到 Write-Host
以便您可以根据需要对其进行格式化。为了输出的一致性,尤其是当它只是向主机输出文本时,我个人喜欢使用格式化字符串。当与 Write-Host
的 -NoNewLine
开关结合使用时,您可以获得一些非常清晰的结果。
我正在尝试修改一个脚本,该脚本应该列出一个域中的所有计算机,如果有人登录到该计算机,它应该显示该帐户的用户名。
脚本运行良好,但我遇到了一些审美问题。有没有办法将 return 数据(对于那些在线的计算机和服务器)变成另一种颜色?
这是我当前的脚本:
function Check-Domain {
Get-ADComputer -Filter * |
Select-Object -ExpandProperty Name |
ForEach-Object {
$computer = $_
$pingme = Test-Connection -ComputerName $computer -Quiet -Count 1
if ($pingme -eq $true) {
Invoke-Command -ComputerName $computer -ScriptBlock {
Get-WmiObject Win32_ComputerSystem |
Select-Object Username, Name }
} else {
Write-Host "$computer - OFF" -ForegroundColor Red
}
} | Format-Table
}
您可以编辑这部分 - 这会将 Invoke-Command
的结果存储在一个变量中,并使用 Write-Host
:
if ($pingme -eq $true) {
$result = Invoke-Command -ComputerName $computer -ScriptBlock {
Get-WmiObject Win32_ComputerSystem | Select-Object Username, Name
}
Write-Host $result -ForegroundColor Green
}
当然,这很简单。只需将命令包裹在子表达式中,然后像使用离线服务器一样使用 Write-Host
。
{Write-Host $(Invoke-Command -ComputerName $computer -ScriptBlock { Get-WmiObject win32_computersystem | Select-Object username, name}) -ForegroundColor Green}
它将首先执行 $()
中的脚本,然后将其输出应用到 Write-Host
以便您可以根据需要对其进行格式化。为了输出的一致性,尤其是当它只是向主机输出文本时,我个人喜欢使用格式化字符串。当与 Write-Host
的 -NoNewLine
开关结合使用时,您可以获得一些非常清晰的结果。