[英]passing parameters with c# to powershell
我試圖將字符串從我的C#應用程序傳遞到我的Powershell腳本。
我不斷收到錯誤消息:“找不到一個接受參數'$null'
位置參數
我該怎么辦?
我的C#代碼:
public void PowerShell()
{
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
Pipeline pipeline = runspace.CreatePipeline();
String scriptfile = @"c:\test.ps1";
Command myCommand = new Command(scriptfile, false);
CommandParameter testParam = new CommandParameter("username", "serverName");
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
Collection<PSObject> psObjects;
psObjects = pipeline.Invoke(); <---error- "A positional parameter cannot be found that accepts argument '$null'"
runspace.Close();
}
我的PowerShell代碼:
Out-Host $username
您的PS腳本沒有參數,僅使用變量。 因此,請嘗試以下操作:
Param($username)
Write-Output $username
請注意,在您的情況下,Out-Host是不可接受的,因為它試圖將參數輸出到調用范圍,而不是簡單地將一些內容寫入輸出流。
另外,您可以在運行空間中設置變量,因此它將在不帶參數的腳本中可用:
runspace.SessionStateProxy.SetVariable("username", "SomeUser");
(必須在runspace.Open()之后和pipeline.Invoke()之前完成)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.