D G
D G

Reputation: 11

You cannot call a method on a null-valued expression. Powershell scripting

Actually I wanted to extract values from log file and save it in csv file

This the log file

Started : tue May 17 10:38:27 1990
Source : A:\Live
Dest : X:\Copy\Dest\
Files : *.
Options : . /COPY:DAT /R:1000000 /W:3
New Dir : 3 W:\Live
New File : 100.0 m randomfile.100M.xyz 0.0%

List item

0.0%
0.0%
,,,,
,,,,
100%

          Total      Remaining      copied       Extracted
         

Disc: 1 1 0 0
Files : 3 3 0 0
Name : 300.00 m 300.00 m 0 0
Times : 0:00:47 0:00:46 0:00:00 0:00:00

Speed : 1224242 Bytes/sec. Speed : 3233.5920 MegaBytes/min.

Ended : tue May 11:39:15 1990

I want to get it in below format

started,source,Dest,speed,ended

tue May 17 10:38:27 1990, A:\Live, X:\Copy\Dest, 1224242 Bytes/sec,3233.5920 MegaBytes/min, tue May 11:39:15 19

But I am get the output as below:

Started","Source","Dest","Ended","Speed"

,"",,"Wed Mar 17 13","W"

"c",".",". /COPY",,"\Test"

,,,,
,,,,
,,,,
,,,,
,,,
"1 1 0 0 0 0","3 3 0 0 0 0" "300.00 m 300.00 m 0 0 0 0","0","6703735 Bytes/sec.","383.590 MegaBytes/min.","tue May 11 39"

Program

Param($textlogfile = "Path")   

    $collection=@() 
    
    ###trim the white spaces lines from the structured text###
    
    $content = (gc $textlogfile ) | ? {$_.trim() -ne "" }   
    for($i=0;$i -lt $content.length;$i=$i+5)   
    {  
     $Started = $content[$i]  
    $started = $Started -split ":" |Select-Object -Index 1 |ForEach-Object Trim     
    $Source = $content[$i+1]  
    $Source = $Source -split ":" |Select-Object -Index 1 |ForEach-Object Trim  
    $Dest = $content[$i+2]  
    $Dest = $Dest -split ":" |Select-Object -Index 1 |ForEach-Object Trim  
    $Ended = $content[$i+3]  
    $Ended = $Ended -split ":" |Select-Object -Index 1 |ForEach-Object Trim  
    $Speed = $content[$i+4]  
    $Speed = $Speed -split ":" |Select-Object -Index 1 |ForEach-Object Trim  
    $coll = "" | select Started,Source,Dest,Ended,Speed  
    $coll.Started = $Started  
    $coll.Source = $Source  
    $coll.Dest = $Dest  
    $coll.Ended = $Ended  
    $coll.Speed = $Speed  
    $collection +=$coll   
    }  
    $collection | export-csv Path -notypeinformation 

Could you please help me to get desired op Please help me as I am new to using of powershell

Upvotes: 1

Views: 352

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174990

PowerShell is trying to invoke Trim() on the result of this expression: (":")[1], believing it to be the right-hand operand of the -split operation.

Change the whole line to:

$Ended = $Ended -split ":" |Select-Object -Index 1 |ForEach-Object Trim

This way, no error occurs if $Ended doesn't have any :'s (you just end up with $null instead)

Upvotes: 1

Related Questions