【问题标题】:How to concatenate 2 Write-Output on the same line?如何在同一行上连接 2 个写入输出?
【发布时间】:2019-07-18 08:52:28
【问题描述】:

我写了一个脚本,它可以在软件安装与否时返回给你。

我想给它一些颜色,但我不知道如何在与-NoNewline 相同的行上连接 2 个 Write-Output 仅适用于 Write-Host... 在这种情况下我不能使用:

# The function we use to give color

function Positive {
    process { Write-Host $_ -ForegroundColor Green }
    }

function Negative {
    process { Write-Host $_ -ForegroundColor Red }
    }

# Is the software installed?
# '0' = NO, is not installed
# '1' = YES, is installed

$Check = '1'

function Check_Installation($Check){
    if ($Check -eq '0') {return $response =  "No, is not installed" | Negative}
    elseif ($Check -eq '1') {return $response =  "Yes, is installed" | Positive}
    }

$First_Phrase =  "Let's check if the software is installed: "

Write-Output "$First_Phrase", "$response"

Check_Installation($Check)

我知道我可以与

连接
[string]::Concat("$First_Phrase", "$response")

但不工作。

【问题讨论】:

  • 如果你只是想在屏幕上写点东西,你应该使用Write-Host。特别是如果你想用另一种颜色。
  • 谢谢@Olaf,但如果您使用function,这不是它的工作方式,因为Write-Host只会在终端中写入而不遵守步骤
  • 但是Write-Host是拥有彩色文本的唯一方法。
  • 如果您在 Google 上搜索 powershell write-output colors,您会发现许多示例说明了这是如何实现的。但由于function,它们都不适用于我的情况。这就是我在 StackOverflow 上问的原因

标签: powershell scripting concatenation string-concatenation write-host


【解决方案1】:

这仅在控制台中有效,因为在 ISE 中更改前景色会为每一行更改它:

# The function we use to give color

function Set-Output {
    param ($colour, $str1, $str2)

    $t = $host.ui.RawUI.ForegroundColor
    $host.ui.RawUI.ForegroundColor = "$colour"

    $text = "$str1 $str2"

    Write-Output "$text"

    $host.ui.RawUI.ForegroundColor = $t

}

# Is the software installed?
# '0' = NO, is not installed
# '1' = YES, is installed

$Check = '1'

$First_Phrase =  "Let's check if the software is installed: "

Switch ($check) {
    ( 0 ) {Set-Output -colour RED -str1 $First_Phrase -str2 "No, is not installed" }
    ( 1 ) {Set-Output -colour GREEN -str1 $First_Phrase -str2  "Yes, is installed" }
}

Check_Installation($Check)

它所做的只是连接两个字符串并改变前景色。

【讨论】:

  • 这看起来很不错。所以没有办法只给Yes, is installedNo, is not installed上色?
  • 不幸的是,我不知道,除非您将它们放在不同的行上,否则每行的颜色将相同。 (stackoverflow.com/questions/3896258/…) 将让您了解Write-Output 的工作原理。如果您必须在同一行上使用不同的颜色,则必须使用 Write-Host-nonewline 参数
  • 顺便说一下不能使用write-host的原因是什么?
  • 这就是迫使我使用Write-Outputstackoverflow.com/questions/54344622/…的原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
相关资源
最近更新 更多