我们有一个包含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中。 –