我正在尝试使用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
答案 0 :(得分:2)
代替使用多个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
。使用-CaseSensitive
参数进行切换。
答案 1 :(得分:0)
我尝试了您的代码,它可以按预期工作(将$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"
}
}
}
答案 2 :(得分:0)
使用不区分大小写的字符,例如运算符-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
}
}
}