Check file extension

折月煮酒 提交于 2019-12-07 01:48:52

问题


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?


回答1:


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 > 



回答2:


Use

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

See PowerShell Comparison Operators.



来源:https://stackoverflow.com/questions/28787364/check-file-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!