简体   繁体   中英

Call PowerShell script file with parameters in C#

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

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

-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...

Help would be much appreciated.

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM