使用 C# 中的参数调用 PowerShell 脚本文件 [英] Call PowerShell script file with parameters in C#

查看:56
本文介绍了使用 C# 中的参数调用 PowerShell 脚本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

真的很挣扎.我尝试了各种不同的方法,但似乎没有任何效果.

Really struggling with this. I have tried various different way, but nothing seems to work.

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

-using addScript: I get an error telling me that I can't call parameters this way an should use a UI like ISE ?!

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

-using FilePath parameter, I can't find the right way to pass the arguments (trouble binding)

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

This is the latest version I tried, and is lifting no errors, but the script is not executed, nothing happens...

非常感谢您的帮助.

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

推荐答案

你可以使用我刚刚测试过的这段代码.

You can use this code, which I personally just tested.

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

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

Here is my test script, located in c:\test\test.ps1.

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

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

FYI, make sure that you launch 32-bit (x86) PowerShell, and set the execution policy to Unrestricted. Visual Studio is a 32-bit process, and invokes the 32-bit PowerShell engine by default.

这篇关于使用 C# 中的参数调用 PowerShell 脚本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆