Powershell脚本无法通过Asp.net网页执行

时间:2018-08-17 11:24:14

标签: c# asp.net powershell

当我通过命令窗口运行时,Powershell脚本工作得很好。但是通过asp.net网页却没有。任何人都可以给出故障排除的提示...运行Windows 10

using System.Management.Automation;
using System.Management.Automation.Runspaces;

            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript("powershell.exe -ExecutionPolicy Unrestricted -file D:\\Files\\Scripts\\Script20180817.ps1 -FilePath " + file);
            pipeline.Invoke();
            runspace.Close();

1 个答案:

答案 0 :(得分:0)

AddScript需要代码。您可以通过以下方法来解决此问题:将脚本读入内存,将其传递,然后使用AddParameter传递-FilePath。您对运行空间没有任何幻想,因此我减少了代码的可读性:

using System.IO;
using System.Management.Automation;

string scriptPath = @"D:\Files\Scripts\Script20180817.ps1";
string file = "TBD?";

string script = File.ReadAllText(scriptPath);
using (PowerShell ps = PowerShell.Create())
{
    ps.AddScript(script).AddParameter('FilePath', file);
    ps.Invoke();
}