user5462886
user5462886

Reputation:

powershell dir gets an error when looping thru the results

This one alone does work. If I try HandleReport -ReportName "123456.pdf" it says matches

function HandleReport 
{
  param ( [string] $ReportName = "" )

       if ( $ReportName  -match "(\d{6})." ) {
         $Result = $_ + " matches ..."
         write $Result
       }
}

Now I call it from a function which reads a directory:

for ($i=0; $i -lt $EventTypes.length; $i++) {
    # $FU_Dir is correct and does exist.
    dir $FU_Dir | foreach {
       $ReportName = $_.name
       HandleReport -ReportName $ReportName
   }
}   

Now I get:

Method invocation failed because [System.IO.FileInfo] doesn't contain a method named 'op_Addition'. At line:6 char:24 + $Result = $_ + <<<< " matches ..." + CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound matches ...

maybe the $_.name does not give back a string?

Upvotes: 1

Views: 119

Answers (1)

arco444
arco444

Reputation: 22871

I'm not sure what the purpose of $_ is in the function. You already pass a string to the function so it should work if you change it to:

function HandleReport 
{
  param ([string] $ReportName = "")

       if ($ReportName -match "(\d{6})." ) {
         $Result = "$ReportName matches ..."
         Write-Output $Result
       }
}

Upvotes: 2

Related Questions