Powershell脚本在C#中使用System.Diagnostics.Process.Start运行时无法加载模块?

时间:2019-02-08 06:46:33

标签: c# powershell system.diagnostics windows-scripting

使用System.Diagnostics.Process.Start运行PS脚本时,由于未加载PowerShell模块,因此脚本会失败,但是在服务器上手动执行时,同一脚本会成功运行, 下面是我的C#代码段,

string ExecPath = @"C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe";
System.Diagnostics.Process exeProcess =
    new System.Diagnostics.Process
    {
        StartInfo =
        {
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            FileName = ExecPath
        }
    };
exeProcess.StartInfo.Arguments = string.Format(" -NoLogo -Sta -NoProfile -NonInteractive -executionpolicy RemoteSigned -File D:\MyPowerShell.ps1");
exeProcess.Start();

异常在下面,

Import-Module : The specified module 'ServerManager' was not loaded 
because no valid module file was found in any module directory.
At D:\MyPowerShell.ps1:9 char:1
+ Import-Module ServerManager
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (ServerManager:String) , FileNot 
   FoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

我尝试导入具有完整路径的模块,但是由于相同的异常而失败。 如何使脚本像手动运行一样工作?

0 个答案:

没有答案