[英]How to send a string parameter from c# to powershell?
我要用c#編寫2個應用程序,而用powershell 1.0編寫另一個應用程序,在我的代碼中,我想傳遞一個字符串,該字符串指示從我的c#應用程序到我編寫的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();
runspace.Close();
和我的powershell腳本
param([string]$Username)
write-host $username
我想念什么? 我對Powershell有點陌生。
我的計算機上安裝了PowerShell 2.0和3.0,但沒有安裝1.0,因此我的結果可能有所不同。 在PowerShell 3.0框上運行您的代碼時,我得到:
由於主機程序或命令類型不支持用戶交互,因此提示用戶的命令失敗。 嘗試使用支持用戶交互的主機程序(例如Windows PowerShell控制台或Windows PowerShell ISE),並從不支持用戶交互的命令類型(例如Windows PowerShell工作流)中刪除與提示相關的命令。
它不喜歡Write-Host,所以我將您的腳本更改為
param([string]$Username)
Get-Date
Get-ChildItem -Path $userName
Get-Date,這樣我就可以看到一些輸出,而不必依賴於參數和使用該參數的GCI。 我將您的代碼修改為如下所示:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
using (var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
{
runspace.Open();
String scriptfile = @"..\..\..\test.ps1";
String path = @"C:\Users\Public\";
var pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(new Command("Set-ExecutionPolicy RemoteSigned -Scope Process", true));
pipeline.Invoke();
pipeline = runspace.CreatePipeline();
var myCommand = new Command(scriptfile, false);
var testParam = new CommandParameter("username", path);
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
var psObjects = pipeline.Invoke();
foreach (var obj in psObjects)
{
Console.WriteLine(obj.ToString());
}
runspace.Close();
}
Console.WriteLine("Press a key to continue...");
Console.ReadKey(true);
並且它運行無誤並在PoSh 2和3上顯示了文件夾內容。
有關信息,如果您只為當前流程設置執行策略,則無需運行提升權限,因此我可以用代碼來實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.