PExec在执行后没有退出



我正在用c#编写一个程序,可以在远程计算机上创建用户。实际上,它已经完成并起作用了。但是我有一个小问题。

在c#中,我使用PowerShell来运行脚本,然后运行peexec,它在远程计算机上执行批处理文件。

c#:

private void executeScripts()
{
string _dirPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string _sPath = Path.GetDirectoryName(_dirPath) + @"ExecuteScriptsFileToExecute.ps1";
string _scriptPath = "& '" + _sPath + "'";
using (PowerShellProcessInstance pspi = new PowerShellProcessInstance())
{
string psfn = pspi.Process.StartInfo.FileName;
psfn = psfn.ToLowerInvariant().Replace("\syswow64\", "\sysnative\");
pspi.Process.StartInfo.FileName = psfn;
using (Runspace r = RunspaceFactory.CreateOutOfProcessRunspace(null, pspi))
{
r.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = r;
ps.AddScript(_scriptPath);
ps.Invoke();
}
}
}
}
PS脚本:
#
# First there are some Copy-Items to the remote Computer
#
# Execute Above copied Bat File on remote Computer
[string] $IPAddress = "\" + $XmlFile.ComputerSettings.LastChild.ChildNodes[1].InnerText
$PsTools = "PsTools"
$PsToolsPath = Join-Path -path $ScriptParent -childpath $PsTools
& $PsToolsPathPsExec.exe $IPAddress /accepteula -i -s -u $Login -p $LoginPassword Powershell  C:PathToBatFileExecute.bat > log.txt
Exit

我在我的程序中使用这个PExec 3次,创建用户,更新用户和删除用户,我只是执行不同的文件,脚本或批处理文件。而且效果很好。

但是对于上面的脚本,PExec执行所有操作但不退出。它也不记录任何东西。我也用-d开关试过,但也不起作用。我还在批处理文件中放置了exit/b,但没有运气。

当在Powershell中手动运行脚本时,它工作,它执行并退出,但当在我的程序中运行它时,它不工作。

等待一段时间后,我的c#返回一个超时的异常结束退出。

有人看到我做错了吗?

Powershell类本身有一个叫做Stop()的方法,可以很容易地阻止这个。

如果你想异步执行,这里有一个实现的例子:

using(cancellationToken.Register(() => powershell.Stop())
{
await Task.Run(() => powershell.Invoke(powershellCommand), cancellationToken);
}

最新更新