PowerShell Get-ChildItem -Include with variables with commas

t_technet 20 Reputation points
2023-05-15T23:09:10.9166667+00:00

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* )
$childItems

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 )
$childItems

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 )
$childItems  

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

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

Accepted answer
  1. Rich Matheisen 45,906 Reputation points
    2023-05-16T02:08:12.3733333+00:00

    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
    2024-04-09T17:59:32.56+00:00

    Hi,

    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.