此代码假定查找磁盘中的所有demo.txt并将其从“demo”更改为“demodemo997182625”,然后检查文件是否已更改
$found = 0;
$notfound = 0;
foreach ($file in Get-ChildItem -Path C:\ -Recurse -Filter demo.txt -ErrorAction SilentlyContinue )
{
(Get-Content $file).Replace("demo","demo997182625") | Set-Content $file
$x = (Get-Content $file).contain("demo997182625")
if($x -eq $null){
$found = 1 + $found;
}
else {
$notfound = 1 + $notfound;
}
}
Write-Host "Changed" $found;
Write-Host "Not Changed" $notfound;
1条答案
按热度按时间s8vozzvw1#
A few remarks on your code:
.Replace()
and.Contains()
string methods work case-sensitive, so.Replace("demo","demo997182625")
won't find and replace "Demo". To have it work case-insensitively, use the-replace
operator instead.-replace
), otherwise leave it beP.S. If your search string contains characters that in regex have special meaning (see table below), you need to escape these with a backslash when using regex operators
-replace
and-match
.Special Characters in Regex