从c#运行Powershell脚本

Ioa*_*icu 9 c# powershell

我正在尝试从C#代码运行PowerShell脚本,但我遇到了一些(可能是环境)问题:

在我尝试运行它的机器上,会发生以下情况:

  1. PowerShell以Admin身份启动并加载
  2. PowerShell窗口立即关闭(显然)没有错误

笔记:

  • 该脚本有效.当我从ISE运行它时,它运行没有错误.
  • 如果我右键单击脚本并选择Run with PowerShell,即使我没有在脚本中更改它,我也会收到执行策略错误.

Set-ExecutionPolicy:Windows PowerShell已成功更新执行策略,但该设置被更具体范围内定义的策略覆盖.由于覆盖,您的shell将保留其当前有效的RemoteSigned执行策略.键入"Get-ExecutionPolicy -List"以查看执行策略设置.有关详细信息,请参阅"Get-Help Set-ExecutionPolicy".在行:1 char:46 + if((Get-ExecutionPolicy)-ne'AllSigned'){Set-ExecutionPolicy -Scope Process ... + ~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~ + CategoryInfo:PermissionDenied :( :) [Set-ExecutionPolicy],SecurityException + FullyQualifiedErrorId:ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

  • Get-ExecutionPolicy -List

         Scope                ExecutionPolicy
         -----                ---------------
     MachinePolicy              Unrestricted
        UserPolicy                 Undefined
           Process                    Bypass
       CurrentUser              Unrestricted
      LocalMachine              Unrestricted
    
    Run Code Online (Sandbox Code Playgroud)
  • 我认为这是环境因素:

    • 几天前它运行良好
    • 它在其他计算机上运行良好

这是我用来调用脚本的代码:

if (File.Exists("Start.ps1"))
{
    string strCmdText = Path.Combine(Directory.GetCurrentDirectory(), "Start.ps1");

    var process = System.Diagnostics.Process.Start(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe ", strCmdText);
    process.WaitForExit();
}
Run Code Online (Sandbox Code Playgroud)

脚本本身是无关紧要的,因为我已将其更改为简单

Write-Host "Hello"
$d=Read-Host
Run Code Online (Sandbox Code Playgroud)

我有同样的问题.

Ioa*_*icu 5

问题出在脚本的路径中。在这台特定的机器上有空格,而我没有处理。

窗口关闭得太快,看不到除设置外的任何错误

process.StartInfo.RedirectStandardOutput = true;
Run Code Online (Sandbox Code Playgroud)

帮助我抓住了它。

执行策略与我的错误无关。

要解决此问题,我更改了c#代码中的路径,如下所述:从“路径中包含非法字符”的位置在CMD.EXE中执行Powershell脚本

完整的代码:

if (File.Exists("Start.ps1"))
            {
                File.GetAttributes("Start.ps1");
                string strCmdText =   Path.Combine(Directory.GetCurrentDirectory(), "Start.ps1");
                var process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.FileName = @"C:\windows\system32\windowspowershell\v1.0\powershell.exe";
                process.StartInfo.Arguments = "\"&'"+strCmdText+"'\"";

                process.Start();
                string s = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                using (StreamWriter outfile = new StreamWriter("StandardOutput.txt", true))
                {
                    outfile.Write(s);
                }

            }
Run Code Online (Sandbox Code Playgroud)