2014-02-11 42 views
1

我需要在PowerShell中編寫一個腳本,該腳本將搜索文件夾,僅查找HTML文件,並用新標記替換指定的某一行標記。在PowerShell中查找僅有的HTML文件並替換其中的標記

這是我到目前爲止有:

$filePath = 'C:\Users\bettiom\Desktop\schools\alex\Academics' 
$processFiles = Get-ChildItem -Exclude *.bak -Filter *.htm -Recurse -Path $filePath 

$query = '<html>' 
$replace = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' 

foreach ($file in $processFiles) { 
    $file | Copy-Item -Destination "$file.bak" 

    $arrayData = Get-Content $file 
    for ($i=0; $i -lt $arrayData.Count; $i++) { 
     if ($arrayData[$i] -match $query) { 
       $arrayData[$i+1] = $arrayData[$i+1].Replace($query,$replace) 
     } else { } 
    } 
    $arrayData | Out-File $file -Force 
} 

一切似乎工作,直到foreach循環,它然後就沒有執行過該行。

任何幫助將非常感謝。

在此先感謝。

回答

1

您正在使用不應該使用的管道,並避免它們在實際有益處。試試這個:

$filePath = 'C:\Users\bettiom\Desktop\schools\alex\Academics' 

$srch = '<html>' 
$repl = '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">' 

Get-ChildItem -Exclude *.bak -Filter *.htm -Recurse -Path $filePath | % { 
    $file = $_.FullName 
    Copy-Item $file "$file.bak" 
    (Get-Content $file) -replace $srch, $repl | Out-File $file -Force 
}