ZippingSitecoreLogsI?ve decided to 1-up the game from my previous post and zip something that isn?t really a real file but rather a blob in a Sitecore database. The script below is based heavily on the last post but instead of just zipping content of a flat folder traverses the Sitecore item tree and zips all files beneath the current folder.

If you have downloaded the 2.1 version of the Sitecore PowerShell Console from the Sitecore Marketplace you will actually have the script deployed on your system already.

Here?s how it looks like for your user in the Content Editor:

ZipAndDownloadContextMenu

The script that performs the operation looks as follows: Read the rest of this article »

Zip and Download Sitecore logs with PowerShell

There was a breaking change in the Console 2.1, if you’re using version 2.1 or newer use Download-File commandlet instad of the “Get-File” as shown in the code below.

LogFilesYou might have have found yourself hunting around in the Sitecore interface for something that would allow you to download all the the log files in a fast and convenient way once time or another. Have you found one? Me neither? but luckily I had the PowerShell console installed on my server so I started looking for a script to zip all files in a folder and luckily because we have a full PowerShell power in the box I could stand on the shoulders of giants and get the zipping part from Stack Overflow ? again (which is the majority of my script. The rest was super easy ? just call the function and download the file?

The only meaningful lines other than the copied function that I needed to use was calling it (?ZipFiles? – naturally) and then calling the new commandlet Get-File (that was added in the version 2.0 of the console). Obviously it?s good to let the user know what?s going on and cleaning up after yourself ? hence the furniture code around those.

Easy peasy? 

Cognifide?s PowerShell Console 2.0 available on Sitecore Marketplace. Go get your copy and? Happy scripting!

 

Now the script looks as follows

###########################################################################
#                                                                         #
# The script zips all log4Net files and allows users to download the zip. #
# It will show errors for logs currently opened by Sitecore for writing.  #
#                                                                         #
###########################################################################

#
# The ZipFiles function is based on noam's answer
# on the following Stack Overflow's page: http://bit.ly/PsZip
#
function ZipFiles( $zipArchive, $sourcedir )
{
    [System.Reflection.Assembly]::Load("WindowsBase,Version=3.0.0.0, `
        Culture=neutral, PublicKeyToken=31bf3856ad364e35") | Out-Null
    $ZipPackage=[System.IO.Packaging.ZipPackage]::Open($zipArchive, `
        [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite)
    $in = gci $sourceDir | select -expand fullName
    [array]$files = $in -replace "C:","" -replace "\\","/"
    ForEach ($file In $files) {
        $fileName = [System.IO.Path]::GetFileName($file);
            $partName=New-Object System.Uri($file, [System.UriKind]::Relative)
            $part=$ZipPackage.CreatePart("/$fileName", "application/zip", `
                [System.IO.Packaging.CompressionOption]::Maximum)
            Try{
                $bytes=[System.IO.File]::ReadAllBytes($file)
            }Catch{
                $_.Exception.ErrorRecord.Exception
            }
            $stream=$part.GetStream()
            $stream.Write($bytes, 0, $bytes.Length)
            $stream.Close()
    }
    $ZipPackage.Close()
}

# Get Sitecore folders and format the zip file name
$dateTime = Get-Date -format "yyyy-MM-d_hhmmss"
$dataFolder = [Sitecore.Configuration.Settings]::DataFolder
$logsFolder = [Sitecore.Configuration.Settings]::LogFolder
$myZipFile = "$dataFolder\logs-$datetime.zip"

# Warn that the used log files will fail zipping
Write-Host -f Yellow "Zipping files locked by Sitecore will fail." -n
Write-Host -f Yellow "Files listed below were used."

# Zip the log files
ZipFiles $myZipFile $LogsFolder

#Download the zipped logs
Get-File -FullName $myZipFile | Out-Null

#Delete the zipped logs from the server
Remove-Item $myZipFile

PS. The hardest part of the blog was to find and theme a nice image for it Puszczam oczko

figures_carrying_house_400_clr_12497Last night I needed to reproduce really quickly a site structure we will be moving from another CMS and create a matching item hierarchy in my Sitecore instance… I could face an hour or so of boring clicking and copying and pasting and hoping I’ve not missed anything or… I could write a short PowerShell script to do the work for me… Guess which path I chose?

Before you use the script you should customize the script parameters:

  • $sitemapUrl – url of the sitemap of the site you want to clone
  • $prefix – wither site root or a branch you want to copy
  • $postfix – if a site has postfixes like .php or .aspx you want to get rid of – define it here
  • $itemTemplate – the template that should be used for items the script will create

Or just run the script and enjoy the glorious cognifide.com page structure reproduced in your Sitecore… now how cool is THAT!?

Also… now that I’ve got your attention… Cognifide’s PowerShell Console 2.0 FINAL is now available on Sitecore Marketplace. Get your copy and… Happy Scripting!

# Script configuration
# --------------------

$sitemapUrl = "http://www.cognifide.com/sitemap";

$prefix = "http://www.cognifide.com/";
$postfix = ".aspx$"

$createAt = "master:/content/Home/"
$itemTemplate = "/templates/Sample/Sample Item"

#                    
# Script starts here 
# ------------------                   

# function to create items (creates parent recursively if needed)
function CreateItem ([string]$itemName) {
  $fullPath = "$createAt\$itemName"
  $parentPath = Split-Path $itemName -parent
  if(-not (Test-Path "$createAt\$parentPath")){
    if($parentPath.Length -gt 2){
      CreateItem $parentPath
    }
  }
  if(-not (Test-Path "$fullPath")){
    "Creating $fullPath"
    $item = New-Item -ItemType $itemTemplate -Name $itemName -Path $createAt
    $item."__Display name" = $itemName -split '[\\/]' | `
      Select -last 1 | `
      ForEach-Object { $_ -replace "-", " " }
  }
}

# Get the sitemap
[xml]$w = (new-object net.webclient).DownloadString($sitemapUrl);

# Get the urls frm the xml
$locations = $w.urlset.url | `
             Where-Object {$_.loc -match $prefix} | `
             Select-Object `
               loc, `
               @{Name="Path"; `
                 Expression = {$_.loc -replace $prefix,"" -replace $postfix,""}}

# send url's for creation
$locations | % { 
  $name = $_.Path.Trim('/')
  if(-not (Test-Path "$createAt/$name")){
    CreateItem $name
  }
}


Enjoy!