我试图使用powershell脚本在字符串中查找子字符串。实际上,我正在逐行读取一个文件,其中包含数千条路径。我正在过滤来自文件的每个路径。路径过滤器在路径中查找子字符串。但是当子字符串是Contains
或Sroot
时,TRoot
函数返回false。
以下是我的示例代码。
foreach($line in Get-Content $filePath)
{
# Line can contain
# $line = $/Patil/TEMP/PRoot/Digvijay/Patil/1.png
# $line = $/Patil/TEMP/SRoot/Digvijay/Patil/2.png
# $line = $/Patil/TEMP/TRoot/Digvijay/Patil/3.png
if($line)
{
if($line.Contains('RRoot')) # This condition works properly
{
# Process Rroot here
}
if($line.Contains('SRoot')) # This condition fails.
{
# Process SRoot here
}
if($line.Contains('TRoot')) # This condition fails.
{
# Process TRoot here
}
}
}
输入文件如下:
$/Patil/TEMP/PRoot/Digvijay/Patil/1.png
$/Patil/TEMP/SRoot/Digvijay/Patil/2.png
$/Patil/TEMP/TRoot/Digvijay/Patil/3.png
$/Patil/TEMP/WRoot/Digvijay/Patil/3.png
而不是使用多个IF
Root
确定的字母控制的开关$Matches[1]
重新调用:$filePath = '.\files.txt'
Get-Content $filePath | Where-Object {$_ -match '([PST])Root'} | ForEach-Object {
$line = $_
switch ($Matches[1]){
'P' {'{0}={1}' -f $_,$line} # code in {} to execute on P
'S' {'{0}={1}' -f $_,$line} # code in {} to execute on S
'T' {'{0}={1}' -f $_,$line} # code in {} to execute on T
}
}
样本输出:
P=P:/TEMP/PRoot/Digvijay/Patil/1.png
S=S:/TEMP/SRoot/Digvijay/Patil/2.png
T=T:/TEMP/TRoot/Digvijay/Patil/3.png
PS:-match
运算符和switch语句默认情况下不区分大小写,
改变这种行为使用-cmatch
resp。用-CaseSensitive
参数切换。
我尝试了你的代码,它按预期工作(将$line.Contains('RRoot')
更改为$line.Contains('PRoot'
)以匹配输入示例)。
我认为你可能会遇到一个案例敏感问题。我建议您尝试将tolower()
函数应用于字符串,然后与小写字符串进行比较:
foreach($line in Get-Content $filePath)
{
# Line can contain
# $line = P:/TEMP/PRoot/Digvijay/Patil/1.png
# $line = S:/TEMP/SRoot/Digvijay/Patil/2.png
# $line = T:/TEMP/TRoot/Digvijay/Patil/3.png
if($line)
{
$lineLower=$line.tolower()
if($lineLower.Contains('proot')) # This condition works properly
{
Write-Host "PRoot"
}
if($lineLower.Contains('sroot')) # This condition fails.
{
Write-Host "SRoot"
}
if($lineLower.Contains('troot')) # This condition fails.
{
Write-Host "TRoot"
}
}
}
使用不区分大小写的运算符-ilike
foreach($line in Get-Content $filePath)
{
# Line can contain
# $line = P:/TEMP/PRoot/Digvijay/Patil/1.png
# $line = S:/TEMP/SRoot/Digvijay/Patil/2.png
# $line = T:/TEMP/TRoot/Digvijay/Patil/3.png
if($line)
{
if($line -ilike "*RRoot*")) # This condition works properly
{
# Process Rroot here
}
if($line -ilike "*SRoot*")) # This condition fails.
{
# Process SRoot here
}
if($line -ilike "*TRoot*")) # This condition fails.
{
# Process TRoot here
}
}
}