Share via

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!

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Answer accepted by question author
  1. Rich Matheisen 48,036 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.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.