在powershell中更换字符串。这可能吗

时间:2017-11-07 13:22:02

标签: powershell

我在创建新页面时有以下Sharepoint PowerShell脚本。现在我想替换所有图像src。目前图像来源如下:

src="/kb/Group/PublishingImages/Pages/test2/1153210.png"
src="/kb/Group/PublishingImages/Pages/test3/11536.png"
src="/kb/Group/PublishingImages/Pages/main/3d.png"
src="/kb/Group/PublishingImages/Pages/detailed/list.png"

但我想在Pages之后删除文件夹名称 - 所以上面的内容将如下所示:

src="/kb/Group/PublishingImages/Pages/1153210.png"
src="/kb/Group/PublishingImages/Pages/11536.png"
src="/kb/Group/PublishingImages/Pages/ed.png"
src="/kb/Group/PublishingImages/Pages/list.png"

此标记将成为整个页面源代码的一部分。我不确定PowerShell是否允许我进行这种字符串替换?

1 个答案:

答案 0 :(得分:2)

使用类似的东西:

$Strings = @("src=""/kb/Group/PublishingImages/Pages/test2/1153210.png""",
"src=""/kb/Group/PublishingImages/Pages/test3/11536.png""",
"src=""/kb/Group/PublishingImages/Pages/main/3d.png""",
"src=""/kb/Group/PublishingImages/Pages/detailed/list.png""",
"src=""/kb/Group/PublishingImages/Pages/already_in_root.png""")

foreach ($String in $Strings){
    $String -replace '(.+Images/Pages).*?(/.*)','$1$2'
}

将输出

src="/kb/Group/PublishingImages/Pages/1153210.png"
src="/kb/Group/PublishingImages/Pages/11536.png"
src="/kb/Group/PublishingImages/Pages/3d.png"
src="/kb/Group/PublishingImages/Pages/list.png"
src="/kb/Group/PublishingImages/Pages/already_in_root.png"

您可以轻松调整正则表达式以匹配任何文件夹结构,或者从文件中读取$Strings