2013-06-12 13 views
19

Próbuję nauczyć się wywoływać cmdlety PS z C# i spotkałem się z klasą PowerShell. To działa dobrze dla podstawowych zastosowań, ale teraz chciałem wykonać to polecenie PS:Wywoływanie cmdlets powershell z C#

Get-ChildItem | where {$_.Length -gt 1000000} 

Próbowałem to poprzez budowanie klasy PowerShell, ale nie wydaje się to zrobić. To jest mój kod do tej pory:

PowerShell ps = PowerShell.Create(); 
ps.AddCommand("Get-ChildItem"); 
ps.AddCommand("where-object"); 
ps.AddParameter("Length"); 
ps.AddParameter("-gt"); 
ps.AddParameter("10000"); 


// Call the PowerShell.Invoke() method to run the 
// commands of the pipeline. 
foreach (PSObject result in ps.Invoke()) 
{ 
    Console.WriteLine(
     "{0,-24}{1}", 
     result.Members["Length"].Value, 
     result.Members["Name"].Value); 
} // End foreach. 

Zawsze otrzymuję wyjątek, kiedy to uruchomię. Czy jest możliwe uruchomienie cmdletu Where-Object w ten sposób?

Odpowiedz

18

Length, -gt i 10000 nie są parametrami do Where-Object. Jest tylko jeden parametr, FilterScript w pozycji 0, o wartości typu ScriptBlock, który zawiera wyrażenie.

PowerShell ps = PowerShell.Create(); 
ps.AddCommand("Get-ChildItem"); 
ps.AddCommand("where-object"); 
ScriptBlock filter = ScriptBlock.Create("$_.Length -gt 10000") 
ps.AddParameter("FilterScript", filter) 

Jeśli masz bardziej złożone oświadczenia, które trzeba rozkładać, należy rozważyć użycie tokenizera (dostępny w v2 lub później), aby zrozumieć strukturę lepiej:

# use single quotes to allow $_ inside string 
PS> $script = 'Get-ChildItem | where-object -filter {$_.Length -gt 1000000 }' 
PS> $parser = [System.Management.Automation.PSParser] 
PS> $parser::Tokenize($script, [ref]$null) | select content, type | ft -auto 

Ten zrzuca się następujące informacje. Nie jest tak bogaty jak parser AST w wersji 3, ale nadal jest przydatny:

 
    Content     Type 
    -------     ---- 
    Get-ChildItem   Command 
    |      Operator 
    where-object   Command 
    -filter  CommandParameter 
    {     GroupStart 
    _      Variable 
    .      Operator 
    Length     Member 
    -gt     Operator 
    1000000     Number 
    }      GroupEnd 

Mam nadzieję, że to pomoże.

+0

Ach, świetnie, rozumiem. Dzięki za wyjaśnienie i kod :) – NullPointer

+1

Nie ma za co. – x0n

+1

+1 Thx guy, już szukają wieków później – algorhythm

Powiązane problemy