PowerShell – loop through files using wildcards in the filenames

22 December 2021

If you need to work with multiple files (e.g. log files) and want to identify them by using wildcards, you can take the below approach:

1 Identify the folder to work in, and add it to a variable. You can use .\ to use the current folder, or put a full path (e.g. C:\temp)

$folder=".\"

2 Identify the file format, with a wildcard, and add it to a variable

$filetypes="log*.txt"

3 Get a list of files, using Get-ChildItems and applying a filter using the variable from above

Get-ChildItem $folder -Filter $filetypes

If you run that, it will list your files, as shown below:

4 If you want to work with each file, you can pipe Get-ChildItems to a ForEach-Object loop, as shown below:

Get-ChildItem $folder -Filter $filetypes | Foreach-Object {
    $filepath=$_.FullName
}

The filepath, is each individual file, as you loop through them, so you can load the content, rename, move etc, based on what you’re trying to achieve.

For this demo, I’ll just use a Write-Host to list the file names, using the below code:

$folder=".\"
$filetypes="log*.txt"

Get-ChildItem $folder -Filter $filetypes | Foreach-Object {
    $filepath=$_.FullName | Write-Host
}

This then lists the files, as shown below:

If you wanted to load the content of those files, then you could use the below approach:

$folder=".\"
$filetypes="log*.txt"

Get-ChildItem $folder -Filter $filetypes | Foreach-Object {
    $filepath=$_.FullName

    Get-Content -Path $filepath | Write-Host
}

The output will then look like this:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.