【问题标题】:Call PowerShell script file with parameters in C#在 C# 中使用参数调用 PowerShell 脚本文件
【发布时间】:2014-07-03 21:52:20
【问题描述】:

真的在为此苦苦挣扎。我尝试了各种不同的方法,但似乎没有任何效果。

-使用 addScript:我收到一条错误消息,告诉我不能以这种方式调用参数,而应该使用像 ISE 这样的 UI?!

-使用 FilePath 参数,我找不到传递参数的正确方法(绑定问题)

这是我尝试过的最新版本,没有错误,但是脚本没有执行,没有任何反应......

我们将不胜感激。

runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
pipeline = runspace.CreatePipeline();

string script =
@"{param($merchantName, $appType, $gruntDirectory, $merchantInstanceDirectory, $editorConnectionString) "+
_config.MerchantInstance.Directory + @"\Generate_And_Compile_LESS.ps1"
+ " –merchantName $merchantName"
+ " –appType $appType"
+ " –gruntDirectory $gruntDirectory"
+ " -merchantInstanceDirectory $merchantInstanceDirectory"
+ " -editorConnectionString $editorConnectionString }";

Command compileCommand = new Command("Invoke-Command");
compileCommand.Parameters.Add("Scriptblock", ScriptBlock.Create(script));

var args = new List<string>();
args.Add(merchantName);
args.Add(appType.GetHashCode().ToString());
args.Add("'" + _config.Grunt.Directory + "'");
args.Add("'" + _config.MerchantInstance.Directory + "'");
args.Add("'" + _connectionStrings.AppConnectionString + "'");

compileCommand.Parameters.Add("ArgumentList", String.Join(",", args));

pipeline.Commands.Add(compileCommand);
Collection<PSObject> results = pipeline.Invoke();

【问题讨论】:

    标签: c# powershell


    【解决方案1】:

    您可以使用我个人刚刚测试过的这段代码。

    static void Main(string[] args)
    {
        PowerShell ps = PowerShell.Create();
        ps.AddScript(@"c:\test\test.ps1").AddParameter("param1", "paramvalue1");
        ps.Invoke();
    }
    

    这是我的测试脚本,位于c:\test\test.ps1。

    [CmdletBinding()]
    param (
        [string] $param1
    )
    Set-Content -Path $PSScriptRoot\test.txt -Value $param1;
    

    仅供参考,请确保启动 32 位 (x86) PowerShell,并将执行策略设置为无限制。 Visual Studio 是 32 位进程,默认调用 32 位 PowerShell 引擎。

    【讨论】:

    • 忘了说,我想使用管道对象,这样我就可以捕获脚本中抛出的特定错误。
    • ps = ps.AddScript(...).AddParameter(....) 对我来说效果更好
    猜你喜欢
    • 2012-05-02
    • 2013-03-23
    • 2020-12-04
    • 2021-10-11
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2018-02-20
    • 2011-06-27
    相关资源
    最近更新 更多