簡體   English   中英

替換目錄中所有文件的文本

[英]Replace the text for all files in a Directory

我編寫了以下條件腳本,以遍歷目錄中的文件並僅在文件包含“健康”一詞時替換所有文件中的一個文本。

cd -Path "\\shlhfilprd08\Direct Credits\Temp2"
ForEach ($file in (Get-ChildItem -Path "\\shlhfilprd08\Direct Credits\Temp2"))
{
$filecontent = Get-Content -path $file -First 1
if($filecontent -like '*Health*'){$filecontent = $filecontent -replace 'TEACHERF','UniHlth '}
Set-Content $file.PSpath -Value $filecontent 
}

我遇到了兩個問題,例如

  1. 如果($ filecontent般的“ 健康 ”),它被替換第一原料和刪除其他行的字連同replace.I不希望這種情況發生
  2. 我將設置內容設置為路徑被拒絕,錯誤信息為文件內容不包含運行狀況文本

你可以試試這個嗎

cd -Path "\\shlhfilprd08\Direct Credits\Temp2"
$configFiles = Get-ChildItem . *.config -rec
foreach ($file in $configFiles)
 {
  (Get-Content $file.PSPath) |
   Foreach-Object { $_ -replace "TEACHERF", "UniHlth " } |
   Set-Content $file.PSPath
}

我會嘗試的; 它在一個小文件中對我有用(將一些數據的小副本復制到新文件夾中並在其中進行測試)

$path = "\\shlhfilprd08\Direct Credits\Temp2"
$replace ="TEACHERF" #word to be replaced
$by = "UniHlth " #by this word (change $replace by $by)


gci $path -file | %{
    foreach($line in $(Get-content $_.Fullname)){
        if($line -like $replace){
            $newline = $line.Replace($($replace),$($by))
            Set-Content $_.FullName $newline
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM