[英]How to call powershell script with configfile,parameters in c#
[英]Call PowerShell script file with parameters in C#
真的為此苦苦掙扎。 我嘗試了各種不同的方法,但是似乎沒有任何效果。
-using 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();
您可以使用我親自測試過的這段代碼。
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引擎。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.