wickjon
wickjon

Reputation: 920

Check file extension

I am using the following PowerShell code and I need to check its extension in an if condition

foreach ($line in $lines) {
    $extn = $line.Split("{.}")[1]
    if ($extn -eq "xml" )
    {
    }
}

Is there a straightforward way to check string extensions in PowerShell script in case of strings?

Upvotes: 13

Views: 50515

Answers (2)

Martin Prikryl
Martin Prikryl

Reputation: 202320

You can use -Like operator:

if ($line -Like "*.xml")
{
    ...
}

See PowerShell Comparison Operators.

Upvotes: 16

user2555451
user2555451

Reputation:

You can simply use the GetExtension function from System.IO.Path:

foreach ($line in $lines) {
    $extn = [IO.Path]::GetExtension($line)
    if ($extn -eq ".xml" )
    {
    }
}

Demo:

PS > [IO.Path]::GetExtension('c:\dir\file.xml')
.xml   
PS > [IO.Path]::GetExtension('c:\dir\file.xml') -eq '.xml'
True
PS > [IO.Path]::GetExtension('Test1.xml') # Also works with just file names
.xml    
PS > [IO.Path]::GetExtension('Test1.xml') -eq '.xml'
True    
PS > 

Upvotes: 29

Related Questions