PowerShell: How do I append data to an existing file in SharePoint with a new line and quotes?

A recent proejct required the injection of some runtime data in my require js configuration file. The following code allowed me to inject the new values into the file.

$site = Get-SPSite "http://mysite"

$file = $site.RootWeb.GetFile("/Style Library/myfile.js")

if (($file -ne $null) -and ($file.Exists -eq $true))
{
$binaryAsIs = $file.OpenBinary()

$asciiEncoding = New-Object -TypeName System.Text.UTF8Encoding
$asIs = $asciiEncoding.GetString($binaryAsIs)

        # This is the text to append to the top.
        # `r`n will create a crlf (new line)
        # $([char]34) will embed a double quote in the text

$new = "// Here is some next text `r`n //and here is text in $([char]34)quotes([char]34)`r`n"
$newFile = $new + $asIs

$binaryToBe = $asciiEncoding.GetBytes($newFile)

$file.CheckOut()
$file.SaveBinary($binaryToBe)
$file.CheckIn("")
$file.Publish("")
}

$site.Dispose()

Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

Error deploying Nintex workflow: An item with the same key has already been added