PowerShell Get-ChildItem -Include with variables with commas

t_technet 20 Reputation points

Hello, I'm a newbie and probably doing something wrong.

If I do this in PowerShell:

$childItems = ( Get-ChildItem -Path $somePath -Name -Directory -Include foo*,bar* )

Everything works out just fine and the second line prints out a bunch of directories that it found. No problem.

However, if I take the same inclusions and put them into a variable and feed the -Include parameter that variable:

$inclusions = 'foo*,bar*'
$childItems = ( Get-ChildItem -Path $somePath -Name -Directory -Include $inclusions )

it no longer works. Then, $childItems ends up having nothing in it.

The weird thing is that if I take out the comma in $inclusions and everything to the right of it, it will work fine for just the one inclusion:

$inclusions = 'foo*'
$childItems = ( Get-ChildItem -Path $somePath -Name -Directory -Include $inclusions )

The same happens with the -Exclude parameter, as well. Would love some help to know what I'm doing wrong. Thanks!

A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,223 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,416 Reputation points

    This: $childItems = Get-ChildItem -Path $somePath -Name -Directory -Include foo*,bar* works because the "-Include" takes a list of strings, and the comma is a list (array) operator. In other words foo*,bar* becomes @("foo*", "bar*").

    When you enclose foo*,bar* in quotes you get a single literal value that will include 'foo' at the beginning followed by any number of characters followed by a comma followed by 'bar' which is followed by any number of characters.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Wrzesinski Jarek 0 Reputation points


    You can try converting your include string into array of strings:

    [string[]]$SearchPattern = ".txt,.json" -split ","

    Get-ChildItem -Path $Path -Include $SearchPattern

    It works in ma case.