【问题标题】:Invoking powershell from C#从 C# 调用 powershell
【发布时间】:2019-07-17 04:18:58
【问题描述】:

我正在尝试从 c# wpf GUI 调用以前制作的 powershell 脚本

我找到了有关如何包含正确引用的说明,所以我确实有 System.Management.Automation 我尝试了多个不同的调用,并且我已经确认 powershell 文件在直接从 PowerShell 运行时有效。我正在使用一个简单的测试文件Add-Content -Path "C:\Test.txt" -Value "It Worked!"

我尝试使用完整路径和相对路径指定文件位置。

我已经确认在 C# 中我可以使按钮关闭窗口,所以我知道这个问题与调用 powershell 有关。

我也试过BeginInvoke()

    private void Btn_WU_Click(object sender, RoutedEventArgs e)
    {
        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            PowerShellInstance.AddScript(@". .\Scripts\Test.ps1").Invoke();
        }

    }

我现在只想让调用的 PowerShell 文件在 C: 中创建一个文件。

【问题讨论】:

  • Run Powershell from C#的可能重复
  • 不,我已经用 Default、ByPass 和 Unrestricted 进行了测试,结果都完全相同
  • PowerShellInstance.AddScript 接受一个字符串,即文字脚本。我相信您偶然告诉AddScript,实际的脚本文本是..\Scripts\Test.ps1。请参阅MS Docs 以供参考。

标签: c# powershell


【解决方案1】:

这样的东西应该更接近工作版本:

private void Btn_WU_Click(object sender, RoutedEventArgs e)
{
    using (PowerShell PowerShellInstance = PowerShell.Create())
    {
        var scriptContent = File.ReadAllText(@"full\path\to\your\script.ps1");
        PowerShellInstance.AddScript(scriptContent).Invoke();
    }
}

【讨论】:

    猜你喜欢
    • 2012-10-26
    • 2013-06-08
    • 2011-05-09
    • 2019-04-08
    • 2016-08-16
    • 2021-08-31
    • 2019-05-13
    • 2013-08-19
    • 1970-01-01
    相关资源
    最近更新 更多