PowerShell:更改默认输出cmdlet



各位下午好,很抱歉标题写得不好,我不知道该怎么写。

如果可能的话(没有一堆If/Elseswitch语句(,我想做的是更改用于输出文本的cmdlet的使用方式。我有一个日志记录模块,我已经写了,正在努力输入到我的脚本中。但是,我想在我的脚本中添加一个switch参数(即-EnableLogging(,当被调用时,它会使用我的日志记录模块,而不是Write-OutputWrite-Host作为示例。

每次我想输出到控制台时,如果不进行If/ElseSwitch检查该标记是否已启用,这可能吗?

没有太多代码可看,但是:

.script.ps1 -EnableLogging
use Write-Log (my module, instead of Write-Output)

.script.ps1
use Write-Output (instead of Write-Log)

我很好奇,除了对每个输出进行更改/指定之外,是否还有其他方法可以更改/指定

.script.ps1 -EnableLogging
Switch($PSBoundParameters.ContainsKey('EnableLogging'){
true {Write-Log "hello world"}
false {Write-Output "hello world"}
}

如果我理解正确,这可能会达到你想要的效果,基本上你会在每个输出行上使用| & $command,但是;命令";只检查一次。下面是我的意思的一个例子:

function Testing {
param([switch] $EnableLogging)
$command = 'Write-Output'
if($EnableLogging.IsPresent) {
$command = 'Write-Host'
}
'Hello World!' | & $command
0..5 | ForEach-Object { "$_. Testing..." } | & $command
}

现在我们可以测试它是否工作,如果-EnableLogging不存在,我们应该能够捕获输出,换句话说,Write-Output正在使用,否则Write-Host:

# works, output is captured in `$tryCapture`
$tryCapture = Testing
# also works, output goes directly to Information Stream
$tryCapture = Testing -EnableLogging

最新更新