Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get actual path from path with wildcard

When using Test-Path in an if statement, I am looking to get the path that the if statement succeeds with.

For example, these files exist in C:

C:\Test6_1_15.txt
C:\Test6_2_15.txt
C:\Test6_3_15.txt
C:\Test6_4_15.txt

what do I do in the "then" branch?

$Path = "C:\Test6_*_15.txt"
if (Test-Path $Path)
{
   # if test passes because there are 4 files that fit the test, but I want to be
   # able to output the file that made the if statement succeed. 
}
like image 941
user3585839 Avatar asked Dec 20 '22 03:12

user3585839


2 Answers

Sounds like you want Resolve-Path:

if(($Paths = @(Resolve-Path "C:\Test6_*_15.txt"))){
    foreach($file in $Paths){
        # do stuff
    }
} else {
    # Resolve-Path was unable to resolve "C:\Test6_*_15.txt" to anything
}
like image 98
Mathias R. Jessen Avatar answered Feb 20 '23 19:02

Mathias R. Jessen


You can do get-item $path, that will return actual file name(s) in its result.

like image 41
Vesper Avatar answered Feb 20 '23 18:02

Vesper