【问题标题】:Start-Process is not recognized when running powershell script from C# code从 C# 代码运行 powershell 脚本时无法识别 Start-Process
【发布时间】:2018-06-05 23:39:47
【问题描述】:

我有以下代码通过执行 Powershell 脚本来停止 IIS 应用程序池:

        using (PowerShell ps = PowerShell.Create())
        {
            ps.AddScript("Set-ExecutionPolicy -Scope LocalMachine Unrestricted");
            string stopCommand = File.ReadAllText($"{scriptPath}StopIISPool.ps1");                
            ps.AddScript(stopCommand);
            ps.AddScript($"StopIISAppPool -StopScriptPath {scriptPath}IISStopCommand.ps1 -poolName {paths.IISAppPoolName}");
            ps.Invoke();

            Collection<ErrorRecord> errors = ps.Streams.Error.ReadAll();
        }

这里的 StopIISPool.ps1 包含以下 powershell 脚本:

    function StopIISAppPool
    {
        Param(
        [parameter(Mandatory=$true)]
        [string]$stopScriptPath,
        [parameter(Mandatory=$true)]
        [string]$poolName
        )
        process
        {
            PowerShell.exe -NoProfile -ExecutionPolicy Unrestricted -Command "&  {Start-Process PowerShell -windowstyle hidden -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -noexit -File $stopScriptPath -poolName $poolname' -Verb RunAs}";
        }
   }

这里的 stopScriptPath 是以下命令的路径,只有在提升权限的情况下才能正确执行:

    Param(
        [parameter(Mandatory=$true)]
        [string]$poolName
    )
    Stop-WebAppPool -Name $poolName;

以上 C# 代码在 ASP.NET Core 应用程序中运行。 当我在 Windows Server 2012 R2 上的 IIS 下部署应用程序并运行时,我在 ps.Invoke() 行上收到以下错误:

Start-Process 未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。

有人能解释一下为什么我会收到这个错误吗?

【问题讨论】:

  • 什么版本的powershell?在 powershell 窗口中键入 $PSVersionTable.PSVersion
  • Major 5,Minor 1,Build 16299,Revision 98,这是我的 Windows 10 Pro 的 powershell 版本,以上所有代码都可以正常工作。在Windows server 2012 R2上运行时出现错误,我猜powershell版本比较旧,我会在以后写版本。
  • PowerShell 版本为 4.0。当我从 PowerShell 运行脚本时它可以工作,但是当我从 C# 执行相同的脚本时,它给了我错误?问题可能来自PowerShell版本吗?
  • 我已经更新了我的 powershell 版本,但没有任何改变。
  • 在您的第二个脚本 IISStopCommand.ps1 中是否只包含类似 Stop-WebAppPool -Name "DefaultAppPool"

标签: c# powershell iis asp.net-core-2.0


【解决方案1】:

我已经解决了这个问题。其实我已经找到了解决方法。为了操作 IIS 应用程序池,我切换到 Windows 命令行而不是 PowerShell。 我使用了以下命令:

    C:\Windows\System32\inetsrv\appcmd start apppool /apppool.name:$poolName.

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多