Dennis
Dennis

Reputation: 83

My code will not write "No files to process"

My code will not display "No files to process" on the screen. It is supposed to count the files in a directory and if there are none then it should display "No files to process" and then exit.

# Function Measure, counts files to see if there are any to process.
Function Measure
{
$Measure = ( Get-ChildItem C:\temp\BDMDump\ | Measure-Object ).Count
    If ($Measure = "0") 
            {Write-Host "No files to process"|Exit} 
    else
            {Write-Host "There are files to process.."}
}

I expect to see "No files to process".

Upvotes: 2

Views: 79

Answers (2)

kuzimoto
kuzimoto

Reputation: 184

There are 4 issues here:

  1. You are using the '=' which is only used for assignment. Use '-eq for comparison.
  2. You are enclosing your integer with quotes, converting it into a string. Just remove the quotes.
  3. As mentioned by ineedalife, you're piping to Exit. You should instead use a semi-colon and the return keyword ; return to exit the function. Even this is probably not needed if the function doesn't do anything else.
  4. You are trying to use "Measure" as the function's name. This is an alias to Measure-Object! Simply change the name to something else, like "Measure-Files"

Additionally, you could remove | Measure-Object because the object System.IO.FileInfo which is returned by Get-ChildItem already has a "Count" method.

Here's a revised copy of your code with all the changes:

Function Measure-Files {
  $Measure = Get-ChildItem "C:\temp\BDMDump\"
  If ($Measure.Count -eq 0) 
  { Write-Host "No files to process"; return } 
  else
  { Write-Host "There are files to process.." }
}

Upvotes: 5

ineedalife
ineedalife

Reputation: 107

There are 3 problems
1. Exit can not be Piped to. If you want to exit the session useExit-PSSession this will close the window.
2. "Is equal to" should be changed from = to -eq
3. "0" should be changed to 0 as it is an integer

If ($Measure -eq 0) 
   {Write-Host "No files to process"|Exit-PSSession} 
    else
        {Write-Host "There are files to process.."}

Upvotes: 0

Related Questions