1

I'm writing a script for work - it is supposed to loop through a multi-lined csv file, and separate each row into its own separate csv. The issue I'm having is with this line:

$csvfile = Get-ChildItem -Path $baseDir* -Include *.csv

Here's a snippet of the section where this line is:

#  get script directory and add it to a variable
$baseDir = $PSScriptRoot
# Write-Host $baseDir

#  get a list of csv file names
    
$csvfile = Get-ChildItem -Path $baseDir* -Include *.csv

The problem is, the variable $csvfile remains empty, so nothing really happens in my script. When I change '$basedir' in the line with the actual path, it works. Through debugging, I know $basedir has a value in it (and it's correct - the actual path), so I'm not sure why the Get-ChildItem will work with the path, but not the variable.

Hope this explanation makes sense - I am the furthest thing from a programmer.

mklement0
  • 382,024
  • 64
  • 607
  • 775
jetrel
  • 11
  • 2

1 Answers1

0

Change $baseDir* to $baseDir\*, given that you want the -Include filter to apply to the child items (files and subdirectories) of $baseDir

  • By contrast, $baseDir* just looks for $baseDir itself, as well as any similarly named sibling directories, namely those whose name starts with the same name as that of the one identified by $baseDir; the resulting directories are reported as themselves, rather than having their child items enumerated, so the -Include pattern is matched against their names, which won't work.

Therefore:

$csvfile = Get-ChildItem -Path $baseDir\* -Include *.csv

Note that use of -Include indeed requires \* at the end of the input path, which is unfortunate, given that Get-ChildItem $baseDir by itself is enough to enumerate the child items of a directory; this answer explains the counterintuitive behavior of the -Include and -Exclude parameters.


The simpler - and also faster - alternative is to use the -Filter parameter, which doesn't require the trailing \*:

$csvfile = Get-ChildItem -LiteralPath $baseDir -Filter *.csv

Note that, unlike with -Include, the wildcard expressions supported by -Filter are not PowerShell's wildcards, and have legacy quirks; typically, that won't matter, but on occasion it does - see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    The ```\```, qualifies that one is a true qualified path name the other is a name variant of the pathname provided. See also the details that parameter binding has its particulars. [See details via this cmdlet](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/trace-command?view=powershell-7.2). If you did the same in cmd.exe ```dir D:\temp*``` vs ```dir D:\Temp\*``` the results would be the same; meaning one does not provide results, and the other does, because one is a name variant for the pathname, and the other is the content in a qualified pathname provided – postanote Oct 25 '22 at 04:29