c# - 如何使用 C# 将参数传递给 PowerShell 脚本?

标签 c# powershell

我正在尝试使用 C# 执行 PowerShell 脚本

我的脚本需要参数才能运行,否则会抛出错误。

这是我的脚本的精简版本

param ($url)
if ($url -eq $null) {
    throw "No Url was provided" 
}

write-host "$url was the provided value"

现在,使用C#我尝试执行如下脚本

try {
    var defaultSessionState = InitialSessionState.CreateDefault();
    defaultSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

    using PowerShell ps = PowerShell.Create(defaultSessionState);

    ps.AddScript(@"d:\test.ps1");
    ps.AddParameter("url", "http://example.com/test/");
    ps.Runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "stop");
} 
catch (Exception e) {

}

但我不断收到未提供 URL 错误。如何正确地将参数传递给我的脚本,以及如何访问它?

最佳答案

AddScript() 用于执行原始代码 - D:\test.ps1 碰巧是有效代码,但它的意思更丰富用于将完整的独立脚本作为字符串放入。

您需要将脚本文件引用添加为命令,此时我们可以应用参数 - 为此,请改用 AddCommand():

using (PowerShell ps = PowerShell.Create(defaultSessionState))
{
    ps.AddCommand("d:\test.ps1");
    ps.AddParameter("url", "http://example.com/test/");
    ps.AddParameter("ErrorAction", "Stop");
    // or
    ps.Runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "stop");
}

关于c# - 如何使用 C# 将参数传递给 PowerShell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61880309/

相关文章:

azure - 想要在一个脚本中获取 blob 存储的所有详细信息

c# - 如何创建密码重置链接?

c# - 将长时间运行的任务与异步/等待模式结合起来的正确方法是什么?

c# - 这个 C# 代码是如何用函数式语言(F#?Haskel?)完成的

powershell - 如何在 Azure DevOps 中获取所有存储库

azure - 修改 Web.Config Azure PowerShell

c# - 如何同步 FileSystemWatcher

c# - 读取对象子属性的优雅方式

c++ - 构建 Qt-Static 5.3.2 时遇到问题

string - 在Powershell中将字符串变量作为参数传递