PowerShell 函数和不同的参数
PowerShell Functions and varying parameters
在我的脚本的早期,我检查了在 运行 脚本时是否使用了参数“-Silent”。我的想法是让脚本的输出为零,如果它是的话,它将在我稍后拥有的每个 Write-Host 条目上进行检查。在我拥有的 每个 单个 Write-Host 上做 if-else 语句似乎有点重,所以我决定使用一个函数 - 像这样:
Function Silent-Write ([string]$arg1)
{
if ($silent -eq $false) {
if ($args -ieq "-nonewline") {
Write-Host "$arg1" -NoNewLine
}
elseif ($args -ieq "-foregroundcolor") {
Write-Host "$arg1" -ForegroundColor $args
}
else {
Write-Host "$arg1"
}
}
}
Silent-Write -ForegroundColor red "hello"
这行不通,但你明白了;除了传递我想要输出的文本外,Silent-Write 函数还应该考虑其他 Write-Host 参数。我认为这是一个非常简单的问题,但是我无法利用我所拥有的功能知识来解决这个问题。
在 PowerShell V3 中,您可以使用展开:
Function Silent-Write
{
if (!$silent) {
Write-Host @args
}
}
Silent-Write -ForegroundColor red "hello"
在我的脚本的早期,我检查了在 运行 脚本时是否使用了参数“-Silent”。我的想法是让脚本的输出为零,如果它是的话,它将在我稍后拥有的每个 Write-Host 条目上进行检查。在我拥有的 每个 单个 Write-Host 上做 if-else 语句似乎有点重,所以我决定使用一个函数 - 像这样:
Function Silent-Write ([string]$arg1)
{
if ($silent -eq $false) {
if ($args -ieq "-nonewline") {
Write-Host "$arg1" -NoNewLine
}
elseif ($args -ieq "-foregroundcolor") {
Write-Host "$arg1" -ForegroundColor $args
}
else {
Write-Host "$arg1"
}
}
}
Silent-Write -ForegroundColor red "hello"
这行不通,但你明白了;除了传递我想要输出的文本外,Silent-Write 函数还应该考虑其他 Write-Host 参数。我认为这是一个非常简单的问题,但是我无法利用我所拥有的功能知识来解决这个问题。
在 PowerShell V3 中,您可以使用展开:
Function Silent-Write
{
if (!$silent) {
Write-Host @args
}
}
Silent-Write -ForegroundColor red "hello"