Reading CSV Files from the Media Library with Sitecore Powershell Extension (SPE)

Some time ago I had a requirement while migrating site on different platform to Sitecore, to create bunch of redirects. Obvious approach here was to use Sitecore Powershell Extensions to accomplish this requirement. While solution is hosted on Azure and we do not have access to Kudu or App Service Editor I could not upload csv file without deployment. I came up with a solution to read file from Media Library. So here we go...

Csv file structure used in script:

       1. SiteName,OldUrl,NewUrl,IsPermament
       2. some name,some old url,some new url,1

Powershell script below:


  #get media item from media library called "test"
  $media = Get-Item -Path "/sitecore/media library/Default Website/test" 

  #get stream and save content to variable $content 
  [System.IO.Stream]$body = $media.Fields["Blob"].GetBlobStream() 
  try 
      $contents = New-Object byte[] $body.Length 
      $body.Read($contents, 0, $body.Length) | Out-Null 
  finally 
      $body.Close() 
   
  #convert to dynamic object 
  $csv = [System.Text.Encoding]::Default.GetString($contents) | ConvertFrom-Csv -Delimiter "," 
  $count = 1  foreach ( $row in $csv ) { 
       
      Write-Host "count: "$count
  
      #Create new item based on template
      $item = New-Item -Path master:$($row.ItemPath) -Name ($row.ItemName) -ItemType "/sitecore/templates/Feature/Redirects/Marketing Redirect" 
      try 
      { 
          if ($item) { 
              $item.Editing.BeginEdit() 
              $item["Site Name"= $row.SiteName 
              $item["Old Url"= $row.OldUrl 
              $item["New Url"= $row.NewUrl 
              $item["Is Permanent"= $row.IsPermanent 
              $item.Editing.EndEdit() | Out-Null 
          } 
           
          else { 
              Write-Host "Couldn't find: $($row.ItemPath)" 
          } 
          $count = $count + 1 
           
      } 
      catch 
      { 
          write-host "Failed to create Item: " $itemPath 
          write-host $_.Exception.Message 
          continue 
      } 
  }