【问题标题】:Power shell script to search for a file and replace strings in that file用于搜索文件并替换该文件中的字符串的 Power shell 脚本
【发布时间】:2021-07-08 18:41:35
【问题描述】:
脚本通过此文件夹递归并查找名为“test”的文件
如果找到名为“test”的文件,它会在该文件中查找电子邮件地址 (test@email.com)
如果找到test@email.com,则将此字符串更改为itworks@email.com
写一条消息说“test" changed in [folder name]”(其中[文件夹名称] 是它找到“测试”文件的路径的名称)
我试过了:
Get-ChildItem -Path ‘C:\SCRIPT TEST ’ –Recurse|
Foreach-Object { Rename-Item $_.FullName ($_.FullName -replace "test@email.com","itworks@email.com ")}
【问题讨论】:
标签:
string
powershell
replace
directory
scripting
【解决方案1】:
我想您的文件有扩展名(test.txt、test.xml 等),否则将 -filter "test.*" 替换为 -filter "test"
解决方案 1:
#take only file where filename = test into your directory
Get-ChildItem "C:\SCRIPT TEST" -file -Recurse -filter "test.*" | %{
#get content of file
$content=get-content $_.FullName -raw
#if content have email searched, replace email and save into file
if ($content -clike "*test@email.com*")
{
$PathFile=$_.FullName
$content.Replace('test@email.com', 'itworks@email.com') | Set-Content $PathFile
"Test changed into the file '{0}'" -f $PathFile
}
}
【解决方案2】:
解决方案 2:
Get-ChildItem "c:\temp" -file -recurse -filter "test.*" | Select-String -Pattern 'test@email.com' -SimpleMatch -list | %{
$Path=$_.Path
$Content=(get-content $Path -raw).Replace('test@email.com', 'itworks@email.com')
$Content | Set-Content $Path -PassThru | %{"Test changed into the file '{0}'" -f $Path}
}