gpt4 book ai didi

c# - 从 C# 运行 Powershell 脚本

转载 作者:太空狗 更新时间:2023-10-29 17:56:04 26 4
gpt4 key购买 nike

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

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

  1. PowerShell 以管理员身份启动并加载
  2. PowerShell 窗口立即(显然)无错误关闭

注意事项:

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

Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of RemoteSigned. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more information please see "Get-Help Set-ExecutionPolicy". At line: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
  • 我认为这是环保的,因为:

    • 几天前运行良好
    • 在其他电脑上运行良好

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

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();
}

脚本本身是无关紧要的,因为我已经把它改成了一个简单的

Write-Host "Hello"
$d=Read-Host

我也有同样的问题。

最佳答案

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

窗口关闭太快,看不到任何错误,但设置

process.StartInfo.RedirectStandardOutput = true;

帮我捕获了它。

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

为了修复它,我更改了 C# 代码中的路径,如下所述:Executing a Powershell script in CMD.EXE from a location with "Illegal characters in path"

完整代码:

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);
}

}

关于c# - 从 C# 运行 Powershell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30844292/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com