-1

Have some simple script:

$sql = Get-ChildItem -Path "C:\files\" -Filter *.sql 

In C:/files/ can be:

1. No file. (my issue)

  1. One file (test.sql)

  2. Multiple files. (test1.sql , test2.sql , etc)

For 3 i'm using if ($sql.Count -gt 1 ) and its working fine. 2 - is not so relevant.

1st one is a problem - do I have any way (method property) to check and get error or "Exit 1" if file is not present at all at source? (without any if/else "magic") Now it's putting path string into $sql variable, when there are no any *.sql file in folder.

Sinai R.
  • 33
  • 10
  • `Now it's putting path string into $sql variable, when there are no any *.sql file in folder` I cannot replicate this, you should have an empty array if no files are found, therefore you should be able to exit using `if ($sql.count -eq 0)` – arco444 Aug 07 '17 at 13:45
  • @Sinai R. : What have you tried? Please post the code you wrote. – Manu Aug 07 '17 at 13:48
  • Hi, I think BenH've answered below. There are empty array. Its my problem. :) If I want to "Get" something and there are nothing, I suppose to see an error. Maybe there are another method to get files. Without if/else. That's a question. – Sinai R. Aug 07 '17 at 13:52

1 Answers1

1

Get-ChildItem doesn't error when there are no files matching the filter but simply returns an empty array. Because of this you cannot force a terminating error with -ErrorAction Stop

This mean that you will likely need to use a conditional. The simplest would be:

if (!($sql)) {throw 1}

An alternative would be:

$sql = Get-ChildItem -Path "C:\files\" -Filter *.sql 
Switch ($sql.count) {
    0 { throw 1}
    1 { "One Item" }
    {$_ -gt 1} { "Multiple Items" }
    default { "Invalid input" }
 }
BenH
  • 9,766
  • 1
  • 22
  • 35