Problem with a variable - New to this

Welcome Forums General PowerShell Q&A Problem with a variable - New to this

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 7 years ago.

  • Author
  • #5511

    Points: 0
    Rank: Member

    by Captainu at 2013-02-05 04:05:12

    I am looking at PowerShell for the first time and do not have a scripting background.

    I am trying to create a small script to search for file types using variables. What I have so far is:

    $Folder = N:\Users
    $Ext = *.doc,*.exe
    Get-ChildItem $Folder -Recurse -Include $Ext

    If I run this I get nothing. If I only have one file extension in $Ext it works. If I type the extensions instead of using a variable it works. How can I put multiple extensions in the variable?

    Im not looking for a script, I am doing this to learn more.



    by John.A.Mello at 2013-02-05 05:55:13

    In order for the variable to know it has multiple entries you'll need to separate them with either to single or double quotes. So either :
    $Ext = "*.doc","*.exe"
    $Ext = '*.doc','*.exe'

    Single quotes (' ') means to treat the enclosed information as a string
    Double qoutes (" ")does the same thing but will extract values from variables if present. So if you did
    $Ext = "*.doc","*.exe","$Folder"
    the variable will have the following values :

      You can verify that the variable has multiple values be testing if it's an array
      $Ext -is [array]
      If True, you have multiple values. If False it has 1 value or is empty.

      by ArtB0514 at 2013-02-05 09:30:54

      Likewise, you also have to put quote marks around the folder variable for it to work:
      $Folder = "N]

      A final note: Once you have the quote marks correct, your query will work, but only because you are using the -Recurse switch. If you were searching only a single folder, then you would have to include a wildcard character in order to get results.
      Get-ChildItem $Folder\* -Include $Ext
      The documentation for this is not easy to find -- it's in the examples for Get-Help Get-ChildItem:

      C:\PS>get-childitem c:\windows\logs\* -include *.txt -exclude A*

      This command gets the .txt files in the Logs subdirectory, except for those whose names start with the letter A. It uses the wildcard character (*) to indicate the contents of the Logs subdirectory, not the directory container. Because the command does not include the Recurse parameter, Get-ChildItem does not include the contents of the current directory automatically; you need to specify it.

    The topic ‘Problem with a variable - New to this’ is closed to new replies.