jladd
jladd

Reputation: 368

C# execute Powershell

So a while back I wrote a Powershell script that would Parse an IIS Log and then do some stuff (email, create a report, and other nifty stuff). Well I am working on excuting that from a C# console app. Before I post my code I just wanted to make one thing clear, i would like to try and stay away from log parser to parse this log cause of many reasons but one specifically, why use something when you can write something else to your liking ;). So here is my code

PS Script:

    $t1 =(get-date).AddMinutes(-10)
    $t2 =$t1.ToUniversalTime().ToString("HH:mm:ss")
    $IISLogPath = "C:\inetpub\logs\LogFiles\W3SVC1\"+"u_ex"+(get-date).AddDays(-3).ToString("yyMMdd")+".log" 
    $IISLogFileRaw = [System.IO.File]::ReadAllLines($IISLogPath) 
    $headers = $IISLogFileRaw[3].split(" ") 
    $headers = $headers | where {$_ -ne "#Fields:"} 
    $IISLogFileCSV = Import-Csv -Delimiter " " -Header $headers -Path $IISLogPath 
    $IISLogFileCSV = $IISLogFileCSV | where {$_.date -notlike "#*"} 
    $tape = $IISLogFileCSV | Format-Table time,s-ip,cs-uri-stem |  Out-Host

C# app thus far:

    Runspace runSpace = RunspaceFactory.CreateRunspace();
        runSpace.Open();
        Pipeline pipeline = runSpace.CreatePipeline();
        pipeline.Commands.AddScript(@"D:\PS-Scripts\IIS\IISLogScan.ps1");
        Collection<PSObject> results = pipeline.Invoke();
        foreach (PSObject obj in results)
        {
            Console.WriteLine(results);

        }
        Console.ReadLine();

Now when I run my App it just sits and doesnt display anything and i Set my breakpoints and it says that there is nothing to display within my foreach which i am completely hung up on cause running my ps1 script it works perfectly and shows many lines. Any insight anyone can give would be great.

Upvotes: 0

Views: 887

Answers (1)

CB.
CB.

Reputation: 60958

Try changing in .ps1 file:

$global:tape =$IISLogFileCSV | Format-Table time,s-ip,cs-uri-stem

and in c#

pipeline.Commands.AddScript(@"D:\PS-Scripts\IIS\IISLogScan.ps1");
pipeline.Commands.AddScript("$tape");
pipeline.Commands.AddScript("out-string");

or in .ps1:

$tape =$IISLogFileCSV | Format-Table time,s-ip,cs-uri-stem
$tape

and in c#

pipeline.Commands.AddScript(@"D:\PS-Scripts\IIS\IISLogScan.ps1");
pipeline.Commands.AddScript("out-string");

Upvotes: 1

Related Questions