检查文件扩展名

时间:2015-02-28 21:52:20

标签: powershell file-extension

我正在使用以下PowerShell代码,我需要在if条件中检查其扩展名

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

在字符串的情况下,是否有直接的方法来检查PowerShell脚本中的字符串扩展名?

2 个答案:

答案 0 :(得分:16)

您只需使用System.IO.Path中的GetExtension功能:

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

演示:

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 > 

答案 1 :(得分:8)

使用

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

请参阅PowerShell Comparison Operators