我正在使用以下PowerShell代码,我需要在if条件中检查其扩展名
foreach ($line in $lines) {
$extn = $line.Split("{.}")[1]
if ($extn -eq "xml" )
{
}
}
在字符串的情况下,是否有直接的方法来检查PowerShell脚本中的字符串扩展名?
答案 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)