Check file extension

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

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

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

+6
source share
2 answers

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 > 
+11
source

Using

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

See PowerShell comparison operators .

+7
source

Source: https://habr.com/ru/post/983158/


All Articles