Problem with Get-Childitem -include

Welcome Forums General PowerShell Q&A Problem with Get-Childitem -include

Viewing 1 reply thread
  • Author
    Posts
    • #213027
      Participant
      Topics: 4
      Replies: 4
      Points: 36
      Rank: Member

      Hello.  I’m trying to write a PowerShell script that will allow a user to pass in a parameter with multiple types of files they want to process (i.e. *.txt and *.docx).  When I run the Get-Childitem command with the -include option and manually type in the file types, it works file.  But when I try to supply a variable for the -include mask, it does not work (returns nothing).

      The problem only occurs when I’m using multiple file types
      $incFiles = “””*.txt””`, “”*.docx”””

      If I use a single file type, it works just fine.
      $incFiles = “*.txt”
      <pre>$incFiles = “”
      $incFiles = “””*.txt””`, “”*.docx”””
      Write-Host "Manual Method:" '"*.txt", "*.docx"'
      Write-Host "Calcul Method:" $incFiles

      Write-Host "nManual method works”`
      Get-ChildItem -path "C:\users\paul\Downloads" -Recurse -Include "*.txt", "*.docx"

      Write-Host "This does not work"
      Get-ChildItem -path "C:\users\paul\Downloads" -Recurse -Include $incFiles

      Write-Host "End"

      Results

      Manual Method: "*.txt", "*.docx"
      Calcul Method: "*.txt", "*.docx"

      Manual method works

      Directory: C:\users\paul\Downloads\Test2

      Mode LastWriteTime Length Name
      ---- ------------- ------ ----
      -a---- 3/28/2020 9:54 AM 0 File1.txt
      -a---- 3/28/2020 9:55 AM 0 File2.docx
      This does not work
      End

    • #213030
      Participant
      Topics: 4
      Replies: 2231
      Points: 5,414
      Helping Hand
      Rank: Community MVP

      Could you please format your code correctly as code using the code tags “PRE“? Thanks.

      The parameter -Include takes an array of file types or patterns. Read-Host creates a single string variable. If you want to use that input for multiple file types you want to process with the -Include parameter of Get-ChildItem you will have to use a loop to “collect” more than on file type or you have to ask the user to use a kind of delimiter and split the input in pieces to be able to provide it for the -Iclude parameter.

      To limit the possible errors you’ll get when you allow user input you could create an advanced function where you use the input validation for example with a validate set and try to use a predefined list of file types the user can choose from.

Viewing 1 reply thread
  • You must be logged in to reply to this topic.