![](/img/trans.png)
[英]How do you access underlying PowerShell runspace from C# Cmdlet?
[英]How to access underlying pipeline in Powershell Api C#
我需要访问刚通过Pwoershell.Create();
创建的底层Powershell默认管道Pwoershell.Create();
我需要停止该管道,以便脚本执行必须立即停止。
我知道我可以通过调用pipe.Invoke()创建Pipeline对象并执行脚本。 但是Pipeline对象没有给我Powershell实例提供的所有数据流。
powerShellInstance = PowerShell.Create();
powerShellInstance.Runspace = RunspaceFactory.CreateRunspace(iss)
以后我需要一点
powerShellInstance.GetPipeline().Stop() // something like this.
有什么我可以实现的目标吗?
编辑
例如,我有以下脚本。
Set-LinkParameter"withError" => This commandlet will throw error
Set-LinkParameter11 "Mistyped" "error" => Powershell will throw an error of invalid commandlet
Initialiize-Access => this is invalid here and this commandlet will throw error. Here it must not allow further script to execute.
Write-Host "This is test message for host"
Write-Information "test information"
Write-Error "Access denied." --> this is can be terminating error ( depends)
Write-Warning "This is test warning."
Write-Verbose "This is verbose message"
Write-Verbose "This is verbose message" -Verbose
Write-Debug "Test Debug message" -Debug
Write-Debug "wont appear at debug pipeline"
Write-Output @(1,2,3) -NoEnumerate | measure
在代码之前进行编辑(异步停止) 。
powerShellInstance.Streams.Error.DataAdded += OnError
OnError(sender,event)
{
//this would have been invoked asyncronously.
powerShellInstance.BeginStop(null,null);
}
不幸的是,您对原始问题的直接答案是不能。 没有通过PowerShell
类或其他方式获取当前运行的管道的公共可访问方式。 与Pipeline
交互的唯一方法是通过Runspace.CreatePipeline
创建它。 此外, Pipeline
API 在PowerShell Standard中不可用,最终将被删除。
修改后的问题(表述为“如何在发生错误后如何终止通过PowerShell
类调用的PowerShell脚本”)的答案是使用PowerShell.Stop()
但是,您已经注意到,这并不保证会终止。 这样做的原因是,在事件触发并调用PowerShell.Stop()
,PowerShell脚本可能已经移至下一个序列点。 如果下一个序列点是阻塞的方法调用,或者是未实现Cmdlet.StopProcessing
的cmdlet,则管道将不会停止直到完成。 如果它从未完成,那么PowerShell.Stop
永远不会完成。 除了终止该进程之外,没有其他解决方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.