我正在研究使用运行空间进行并行运行。目前,我正在尝试从我可能运行的任何脚本中获取消息,以帮助我诊断问题,其来源相同的流类型:详细流中的详细消息等。到目前为止,我可以获得警告和详细消息,但每当我尝试使用 Write-Error (或者甚至只是访问 ErrorRecord 对象属性)时,控制台都会锁定。
本文末尾有一个示例,它将演示我所看到的内容。目前,该脚本生成四个消息:
VERBOSE: This is a verbose message.
WARNING: This is a warning message.
System.Management.Automation.ErrorRecord
This is an error message.
如果您取消注释 $ps1.Streams.Error.add_DataAdded({})
scriptBlock 中的任何一条注释,它会在此时锁定。任何人都可以解释原因和/或给我一个解决方法/修复吗?
我正在追求这样的东西:
VERBOSE: This is a verbose message.
WARNING: This is a warning message.
C:\Work\me\PowerShell\Test-ReadPSDataStreams.ps1 : This is an error message.
At line:1 char:1
+ .\Test-ReadPSDataStreams.ps1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-ReadPSDataStreams.ps1
这是脚本:
$VerbosePreference = 'Continue'
$is1 = [InitialSessionState]::CreateDefault()
$rs1 = [RunspaceFactory]::CreateRunspace($is1)
$rs1.ApartmentState = 'STA'
$rs1.ThreadOptions = 'ReuseThread'
$rs1.Open()
$ps1 = [PowerShell]::Create()
$ps1.Runspace = $rs1
$ps1.Streams.Verbose.add_DataAdded({
Param (
[Object]$sender,
[System.Management.Automation.DataAddedEventArgs]$e
)
foreach ($item in $sender.ReadAll()) {
Write-Verbose $item.Message
}
})
$ps1.Streams.Warning.add_DataAdded({
Param (
[Object]$sender,
[System.Management.Automation.DataAddedEventArgs]$e
)
foreach ($item in $sender.ReadAll()) {
Write-Warning $item.Message
}
})
$ps1.Streams.Error.add_DataAdded({
Param (
[Object]$sender,
[System.Management.Automation.DataAddedEventArgs]$e
)
foreach ($item in $sender.ReadAll()) {
Write-Host $item.GetType()
Write-Host $item.ToString()
#Write-Host $item.ErrorDetails.Message
#Write-Error 'test'
#Write-Error $item.ToString()
}
})
[void]$ps1.AddScript({ $VerbosePreference = 'Continue' })
[void]$ps1.AddScript({ Write-Verbose 'This is a verbose message.' })
[void]$ps1.AddScript({ Write-Warning 'This is a warning message.' })
[void]$ps1.AddScript({ Write-Error 'This is an error message.' })
$ps1.Invoke()
如果有其他方法可以做到这一点,我愿意!
最佳答案
看看这是否有帮助:
看看这是否有帮助: http://mjolinor.wordpress.com/2014/06/03/invoke-scritptasync-v2/
如果我正确地阅读了问题,它的设计正是为了您描述的场景 - 在运行空间环境中测试脚本并能够在执行期间将诊断信息写入各种输出流,然后在执行完成后检索该信息以及已处置的运行空间。
关于powershell - 为什么我无法从 PowerShell.Streams.Error.add_DataAdded 写入错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27254198/