2013-04-11 53 views
1

我寫了2個應用程序之一與C#和另一個與PowerShell 1.0,在我的代碼的某些點我想傳遞一個字符串,表明服務器名稱從我的C#應用​​程序到我寫的PowerShell腳本文件,怎麼做我發了?我如何接受它?如何將字符串參數從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。

+0

嘗試從PowerShell文件中除去「write-host $ username」行的所有內容 – laszlokiss88 2013-04-11 12:39:18

+0

當您運行該命令時會發生什麼? PowerShell腳本是不是完全運行,或者輸出錯誤,或者根本沒有輸出,或者......?如果您直接從PowerShell運行PowerShell腳本,它可以工作嗎? – 2013-04-11 14:44:38

+0

我發現一個答案是這樣的: 轉到開始菜單並搜索「Windows PowerShell ISE」。 右鍵單擊x86版本,然後選擇「以管理員身份運行」。 在頂部,粘貼Set-ExecutionPolicy RemoteSigned;運行腳本。選擇「是」。 但現在我得到了一個新問題。現在我得到: 無法找到接受參數'$ null'的位置參數。 有什麼想法? – woolford 2013-04-11 14:53:27

回答

1

我有PowerShell 2.0和3.0但不是1.0的機器,所以我的結果可能會有所不同。當我在我的PowerShell 3.0箱運行你的代碼,我得到:

,提示用戶的命令失敗,因爲主機程序或 命令類型不支持用戶交互。嘗試支持用戶交互的主機程序 (如Windows PowerShell控制檯 或Windows PowerShell ISE),並從不支持用戶交互的 命令類型(如Windows PowerShell工作流)中刪除與提示相關的命令。

它不喜歡寫主機,所以我改變你的腳本

param([string]$Username) 

Get-Date 
Get-ChildItem -Path $userName 

獲取最新的,這樣我可以看到一些輸出,而不取決於參數和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); 

而且其運行沒有任何錯誤,並顯示該文件夾的內容,在兩個辣妹2和3

對於信息,如果你只設置執行策略對於當前進程,您不需要運行提升,因此我可以在代碼中執行此操作。

相關問題