Home > Mobile >  In Powershell, How to expand file globs passed to a script using a parameter?
In Powershell, How to expand file globs passed to a script using a parameter?

Time:03-05

Here's what I'm trying to do:

# FILE: something.ps1
param([string[]]$File)

foreach ($item in $File) {
    write-host $item
}

And here's what happens when I use this script:

PS> .\something.ps1 -File *.txt
*.txt

How to get Powershell to expaned the file globs passed in from the command line so that I get a list of "*.txt" files that I can loop over?

CodePudding user response:

Resolve-Path does pretty much exactly that. Just something to pay attention to, bare Resolve-Path returns PathInfo objects, but with the -Relative switch it returns strings.

 PS C:\> Resolve-Path "C:\*files*" | Select -ExpandProperty Path
 C:\Program Files
 C:\Program Files (x86)

PS C:\Windows\> Resolve-Path *syst* -Relative 
.\System
.\System32
.\SystemApps
.\SystemResources
.\SystemTemp
.\system.ini

CodePudding user response:

# File: sometime.ps1
param([string[]]$File)

foreach ($item in $File) {
    $r_path = Resolve-Path $item -ErrorAction SilentlyContinue
    if ($r_path -ne $null) {
        foreach ($r_item in $r_path) {
            $r_file = $r_item.Path
            write-host $r_item
        }
    }
}

# Notes: 
#
#  Resolve-Path will return three different types:
#     $null, [PathInfo], or [PathInfo[]]
#
# Luckly, the foreach is able to iterate over a 
#   scalar [PathInfo] object just as well as a 
#   Array of [PathInfo] objects ([PathInfo[]]).
#
#   Powershell does this by just returning the scalar 
#   object once in the foreach loop. So we don't need 
#   any special logic to detect between
#   scale and array forms of [PathInfo]
  • Related