2014-07-10 30 views
3

Invoke-MyFunction是我寫的一個命令行開關,它接受輸入文件並進行更改,並在指定位置創建新的輸出文件。如果我打開我的桌面,進口MyCommandlet.ps1在PowerShell中,並運行PowerShell命令行開關被調用但沒有響應

Invoke-MyFunction -InputPath path\to\input -OutputPath path\to\output 

一切正常。但是,當我嘗試使用下面的代碼從C#程序導入和調用該命令時,commandlet不會運行,不記錄輸出並且不會生成輸出文件。它不會拋出CommandNotFoundException,所以我假定PowerShell對象識別我的commandlet。但我不明白爲什麼它不執行它。

//set up the PowerShell object 
    InitialSessionState initial = InitialSessionState.CreateDefault(); 
    initial.ImportPSModule(new string[] { @"C:\path\to\MyCommandlet.ps1" }); 
    Runspace runspace = RunspaceFactory.CreateRunspace(initial); 
    runspace.Open(); 
    PowerShell ps = PowerShell.Create(); 
    ps.Runspace = runspace; 

    //have MyFunction take input and create output 
    ps.AddCommand("Invoke-MyFunction"); 
    ps.AddParameter("OutputPath", @"C:\path\to\output"); 
    ps.AddParameter("InputPath", @"C:\path\to\input"); 
    Collection<PSObject> output = ps.Invoke(); 

此外,調用MyFunction後,PowerShell對象ps無法執行任何其他命令。即使是已知的。

+1

我試着調用'Copy-Item'而不是'Invoke-MyFunction',它的工作原理。所以我認爲關於'Invoke-MyFunction'的一些事情正在引發這個問題。 – dmeyerson

回答

2

這個工作對我來說:

//set up the PowerShell object 
var initial = InitialSessionState.CreateDefault(); 
initial.ImportPSModule(new string[] { @"C:\Users\Keith\MyModule.ps1" }); 
Runspace runspace = RunspaceFactory.CreateRunspace(initial); 
runspace.Open(); 
PowerShell ps = PowerShell.Create(); 
ps.Runspace = runspace; 

//have MyFunction take input and create output 
ps.AddCommand("Invoke-MyFunction"); 
ps.AddParameter("OutputPath", @"C:\path\to\output"); 
ps.AddParameter("InputPath", @"C:\path\to\input"); 
var output = ps.Invoke(); 
foreach (var item in output) 
{ 
    Console.WriteLine(item); 
} 

隨着一個MyModule.ps1:

function Invoke-MyFunction($InputPath, $OutputPath) { 
    "InputPath is '$InputPath', OutputPath is '$OutputPath'" 
} 

有一件事確實讓我失敗是上的Visual Studio 2013(也許2012也一樣)任何CPU應用程序實際上都將在64位操作系統上運行32位。您必須爲PowerShell x86設置執行策略才能執行腳本。嘗試在管理模式下打開PowerShell x86 shell並運行Get-ExecutionPolicy。如果它設置爲Restricted,則使用Set-ExecutionPolicy RemoteSigned來允許腳本執行。

+0

對我來說,問題就是MyCommandlet.ps1中的錯誤,而不是我的C#代碼。我沒有注意到的是,Invoke-MyFunction只有在從某個目錄調用時才起作用(因爲它依賴的某些文件位於該目錄中)。從C#調用它,工作目錄是錯誤的,這就是它失敗的原因。更改命令行以便可以從任何地方調用它是解決方案。 – dmeyerson

+0

很高興聽到你明白了。 –

相關問題