从ASP.NET异步调用powershell脚本
本文关键字:powershell 脚本 调用 异步 ASP NET | 更新日期: 2023-09-27 17:53:25
尝试在ASP中异步调用powershell脚本。. NET IHttHandler
,我在http://msdn.microsoft.com/en-us/library/ee706580(v=vs.85).aspx上偶然发现了这个例子。我自己的代码是这样的:
using (PowerShell powershell = PowerShell.Create()) {
powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}");
PSDataCollection<PSObject> output = new PSDataCollection<PSObject>();
output.DataAdded += delegate(object sender, DataAddedEventArgs e) {
PSDataCollection<PSObject> myp = (PSDataCollection<PSObject>)sender;
Collection<PSObject> results = myp.ReadAll();
};
powershell.InvocationStateChanged += delegate(object sender, PSInvocationStateChangedEventArgs e) {
if (e.InvocationStateInfo.State == PSInvocationState.Completed) {
// Clean up
}
};
IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output);
}
不幸的是,powershell脚本显然没有被执行。任务管理器中没有powershell进程。
我在DataAdded
和IncovationStateChanged
处理程序中设置断点。第一个从来没有被调用,第二个显示,e.InvocationStateInfo.State
从来没有变成Completed
,而是以Stopped
结束。
我做错了什么?
这适用于控制台应用程序:
using (PowerShell powershell = PowerShell.Create())
{
powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}");
var output = new PSDataCollection<PSObject>();
output.DataAdded += delegate(object sender, DataAddedEventArgs e)
{
Console.WriteLine(output[e.Index]);
var myp = (PSDataCollection<PSObject>)sender;
Collection<PSObject> results = myp.ReadAll();
};
powershell.InvocationStateChanged += delegate(object sender, PSInvocationStateChangedEventArgs e)
{
if (e.InvocationStateInfo.State == PSInvocationState.Completed)
{
// Clean up
}
};
IAsyncResult asyncResult = powershell.BeginInvoke<PSObject, PSObject>(null, output);
asyncResult.AsyncWaitHandle.WaitOne();
}
如果您稍后不以某种方式同步或返回并等待调用完成,PowerShell引擎将关闭,因为powershell.Dispose()
在超出using {}
作用域时被调用。