6

I have some files in SP 2010 that are simply HTML, and I need to modify the contents of those files in a systematic manner.

Is there a good way to do this using powershell? Imagine that I want to find certain tags or text and replace them with something else, like replace "p" with "P".

3 Answers 3

9

There's probably a bunch of different ways to do this, but here's a snippet from some C# code that I wrote a while back converted to PowerShell. Hope it's along the lines of what you're looking for:

Start-SPAssignment -Global
$web = Get-SPWeb "http://sharepointdev:90"
$list = $web.Lists.TryGetList("Site Pages")
foreach ($file in $list.RootFolder.Files) 
{
    if ($list.ForceCheckout) { $file.CheckOut() } 
    $html = [System.Text.Encoding]::ASCII.GetString($file.OpenBinary())
    $html = $html.Replace("p", "P")
    $file.SaveBinary([System.Text.Encoding]::ASCII.GetBytes($html))
    if ($list.ForceCheckout) { $file.CheckIn() }
}
Stop-SPAssignment -Global
4
  • 1
    TIL about the Start-SPAssignment -Global. Neat...
    – tarjeieo
    Commented Aug 2, 2011 at 10:44
  • your replace statement would probably want to include "<p>","<P>" if you want to replace the tags.
    – user4308
    Commented Aug 2, 2011 at 13:15
  • The original question said "tags or text" and I just used his example for context.
    – Rob D'Oria
    Commented Aug 2, 2011 at 13:22
  • Thank you, this is a great example, got me pointed where I needed to go. Commented Aug 3, 2011 at 16:33
1

Since you're mentioning HTML files, you could also use the SPWeb.GetFileAsString() method to get the contents of the file and SPWeb.Files.Add(string, byte[], bool) to save the contents.

0

I came across this PowerShell function recently and thought it could be helpful for situations like the one you mention. I haven't actually used it yet, but it could be another option for you. http://blogs.msdn.com/b/powershell/archive/2008/12/25/get-markuptag.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.