【问题标题】:PExec doesn't exit after execute执行后 PExec 不退出
【发布时间】:2021-11-17 12:41:50
【问题描述】:

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

在 C# 中,我使用 PowerShell 运行脚本,然后运行 ​​Pexec,在远程计算机上执行批处理文件。

C#:

private void executeScripts()
    {
        string _dirPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
        string _sPath = Path.GetDirectoryName(_dirPath) + @"\ExecuteScripts\FileToExecute.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
& $PsToolsPath\PsExec.exe $IPAddress /accepteula -i -s -u $Login -p $LoginPassword Powershell  C:\Path\ToBatFile\Execute.bat > log.txt

Exit

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

但是使用上面的脚本,PExec 执行所有操作但不退出。 Neiter 会记录一些东西。 我也尝试使用 -d 开关,但这也不起作用。我还在批处理文件中放了一个出口 /b,但没有运气。

当从 Powershell 手动运行脚本时,它可以工作,它会执行并退出,但是当从我的程序运行它时它不会。

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

有人看到我做错了吗?

【问题讨论】:

  • 你有一个 C# 应用程序、powershell 脚本和一个批处理文件,所有这些都在这里发挥作用......你能全部用 C# 编写吗?
  • 不幸的是没有 -.- 但一切都很好,除了那个小东西。
  • 您正在使用 /I 开关,该开关用于交互。删除那个
  • 那么你为什么不使用 WinRM for PowerShell 开始呢? Invoke-Command -ComputerName <hostname> -Command {<script>}

标签: c# powershell batch-file script


【解决方案1】:

Powershell 类本身有一个名为 Stop() 的方法,可以很容易地阻止它。

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

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

【讨论】:

  • 感谢那个答案,我搜索了类似的东西:)
猜你喜欢
  • 2014-11-04
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2015-10-31
  • 2021-01-24
  • 1970-01-01
  • 2014-03-16
  • 1970-01-01
相关资源
最近更新 更多