2011-09-21 168 views
0

下面是代碼:PowerShell腳本問題

static String checkBackUp() 
{ 
    Runspace runspace = RunspaceFactory.CreateRunspace(); 

    runspace.Open(); 

    Pipeline pipeline = runspace.CreatePipeline();      
    pipeline.Commands.Add("Get-WBSummary"); 
    pipeline.Commands.Add("Out-String"); 

    Collection<PSObject> results = new Collection<PSObject>(); 
    try 
    { 
     results = pipeline.Invoke(); 
    } 
    catch (Exception ex) 
    { 
     results.Add(new PSObject((object)ex.Message)); 
    } 

    runspace.Close(); 

    StringBuilder stringBuilder = new StringBuilder(); 
    foreach (PSObject obj in results) 
    { 
     stringBuilder.AppendLine(obj.ToString()); 
    } 

    return stringBuilder.ToString(); 
} 

的問題是,這個運行的每個cmdlet(如Get-Process例如),但是當我嘗試驗證一個備份的情況下(Get-WBSummary),它吐出出現以下錯誤:

The term 'Get-WBSummary' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

但是,當我將命令直接放入PowerShell中時,它會執行該命令。我已經嘗試添加一個管理單元,但這不起作用。

我在這裏做錯了什麼?

回答

1

Get-WBSummary不是常規的內置Powershell cmdlet。你需要做的

Add-PSSnapin Windows.ServerBackup

在代碼中的某個點的運行空間被初始化後。

+0

就像我說我的問題,我沒有:),它並沒有幫助。我有這樣的: 流水線pipeline = runspace.CreatePipeline(); (「Add-Pssnapin」Windows.serverbackup「); 命令addSnapin =新命令(」Add-PSSnapin「); addSnapin.Parameters.Add(」Name「,」Windows.serverbackup「); pipeline.Commands.Add pipeline.Commands.Add(addSnapin); –

0

您必須創建初始會話狀態並添加管理單元。這裏是如何做到這一點

initialSession = InitialSessionState.CreateDefault(); 
initialSession.ImportPSModule(new[] {"Path\to\module\here"});