繁体   English   中英

Power shell 脚本搜索文件并替换该文件中的字符串

[英]Power shell script to search for a file and replace strings in that file

该脚本遍历此文件夹并查找名为“test”的文件
如果找到名为“test”的文件,它会在该文件中查找 email 地址 (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 ")}

我想你的文件有一个扩展名(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:

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}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM