我正在嘗試將我的腳本的輸出通過管道傳輸到一個單獨的方法,并嘗試在那里分離錯誤流。這里是pipeline.ps1
Function MyLogs{
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline=$True)]
[String[]] $Log
)
Begin {
Write-Verbose "initialize stuff"
# code to initialize stuff
}
Process {
Write-Output " $Log"
}
End {
# code to clean stuff
}
}
#--- pipe the script output to it
& .\MyScript.ps1 | MyLogs
這是MyScript.ps1
Write-Output "********** This is a normal text message ************* `n`r "
# this would create a divide by zero error
1/0
Write-Warning "example warning"
Write-Output "after the errors"
該呼叫& .\MyScript.ps1 | MyLogs不會將錯誤流通過管道傳輸到,MyLogs()但是錯誤將顯示在控制臺中:
PS D:\Learn\powershell> .\pipelines.ps1
VERBOSE: initialize stuff
********** This is a normal text message *************
Attempted to divide by zero.
At D:\Learn\powershell\MyScript.ps1:3 char:1
1/0
~~~
CategoryInfo : NotSpecified: (:) [], RuntimeException
FullyQualifiedErrorId : RuntimeException
WARNING: example warning
after the errors
如果我愿意& .\MyScript.ps1 *>&2 | MyLogs,錯誤流將被讀取為普通文本,我無法弄清楚如何errors將normal text.
uj5u.com熱心網友回復:
主要是,您需要將所有流( *>&1) 或至少將錯誤流重定向到成功流( 2>&1),以便您的函式可以捕獲來自管道的物件。此外,您的函式的引數應該采用[object]or[object[]]而不是,[string[]]以便您可以參考來自管道的物件型別。
最后,借助-is型別比較運算子和開關,您可以創建一個不錯的日志記錄功能。
using namespace System.Management.Automation
function MyLogs {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline = $True)]
[object] $Log
)
begin {
# code to initialize stuff
}
process {
# this could be reduced to:
# `@{ $Log.GetType().Name = $Log }`
switch($Log) {
{ $_ -is [ErrorRecord] } {
@{ 'Error Record' = $_ }
break
}
{ $_ -is [WarningRecord] } {
@{ 'Warning Record' = $_ }
break
}
{ $_ -is [VerboseRecord] } {
@{ 'Verbose Record' = $_ }
break
}
{ $_ -is [InformationRecord] } {
@{ 'Information Record' = $_ }
break
}
Default {
@{ 'Success Stream' = $_ }
}
}
}
end {
# code to clean stuff
}
}
& {
Write-Output 'This is a normal text message'
1/0
Write-Host 'Information here...'
Write-Warning 'example warning'
Write-Output 'after the errors'
Write-Verbose 'Hello world!' -Verbose
} *>&1 | MyLogs
我會把它留給你作為練習的進一步更新,這是你可以從這個例子中得到的輸出:
Name Value
---- -----
Success Stream This is a normal text message
Error Record Attempted to divide by zero.
Information Record Information here...
Warning Record example warning
Success Stream after the errors
Verbose Record Hello world!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444147.html
