我們有一個包含3000多個正在遷移到SharePoint站點的HTML文件的目錄,我們需要清理一些數據。在Powershell中替換多個字符串的正確語法
具體情況:
- 文件約1/3的包括XML頭
<?xml version="1.0" encoding="utf-8"?>
SharePoint可並不喜歡。我們計劃只刪除該標題行。 - 每個文件都有指向兩個備用相關主頁鏈接
foo1.htm
或foo.htm
的「HOME」的javascript參數。我們想要將兩者都改爲絕對鏈接http:\\sharepoint.site\home.aspx
- 每個文件還有一個javascript鏈接參數「顯示」,我們只是想通過將其更改爲
''
來隱藏它。
這裏是我的功能至今:
function scrubXMLHeader {
$srcfiles = Get-ChildItem $backupGuidePath -filter "*htm.*"
$srcfilecount = (Get-ChildItem $backupGuidePath).Count
$selfilecount = $srcfiles.Count
# Input and Ouput Path variables
$sourcePath = $backupGuidePath
$destinationPath = $workScrubPath
"Input From: $($sourcePath)" | Log $messagLog -echo
" Output To: $($destinationPath)" | Log $messageLog -echo
#
$temp01 = Get-ChildItem $sourcePath -filter "*.htm"
foreach($file in $temp01)
{
$outfile = $destinationPath + $file
$content = Get-Content $file.Fullname | ? {$_ -notmatch "<\?xml[^>]+>" }
Set-Content -path $outfile -Force -Value $content
}
}
我想下面的兩個編輯添加到每個文件:
-replace '("foo.htm", "", ">", "Home", "foo1.htm")', '("http:\\sharepoint.site\home.aspx", "", ">", "Home", "http:\\sharepoint.site\home.aspx")
-replace 'addButton("show",BTN_TEXT,"Show","","","","",0,0,"","","");', ''
我不知道如何將這些合併成一個單一語句,所以我打開文件,執行更改,保存並關閉文件,而不是三個單獨的打開編輯 - 保存/關閉事務。我也不確定,用所有的引號和逗號,逃避這些角色的最好方法,或者圍繞整個字符串的單引號是否足夠。
理解到「asking regexes to parse arbitrary HTML is like asking Paris Hilton to write an operating system, it's sometimes appropriate to parse a limited, known set of HTML」,但在我的工具包,PowerShell的限制,我想了解兩個-replace
行添加到現有的$content
變量......在大括號內用逗號分隔的最好方法?互相傳送?
下面是這些最佳策略嗎?還是有更好的?
$content = Get-Content $file.Fullname | ? {$_ -notmatch "<\?xml[^>]+>",
-replace '("foo.htm", "", ">", "Home", "foo1.htm")', '("http:\\sharepoint.site\home.aspx", "", ">", "Home", "http:\\sharepoint.site\home.aspx"),
-replace 'addButton("show",BTN_TEXT,"Show","","","","",0,0,"","","");', '' }
每次[解析HTML使用正則表達式(http://stackoverflow.com/a/1732454/1630171),一名女生死於某處。 [適當的工具](http://stackoverflow.com/a/20644942/1630171)在您的處置。使用它們。 –
保存CATGIRLS!不幸的是,我的工具集擴展到PowerShell v1.0;我處於用戶區域,並且鎖定了比我想要做的更多的工作。我敢肯定,如果IT能夠找到一種方法從Win7中解脫PS來阻止我使用它,他們會。沒有提到的適當工具可以提供給我,因爲我沒有適當的權限......不要讓我開始。 – dwwilson66
'Tidy'是用於美化代碼的可選項。其餘內置於Windows/PowerShell中。 –