Wednesday, October 10, 2012

Powering-up The PowerShell

I have never, ever...ever-ever-ever used PowerShell before as I tend to hate all things programming. I've created basic batch files to delete backups, but those are relatively straightforward. For the task I was trying to tackle today, we need to download the differential backup files for one of our databases, unzip them, and then load them into SQL. I wrote this PowerShell script to do everything except the last part (loading into SQL), but tomorrow is a new day. Just a quick note beforehand- you have to use a program like 7-Zip for .bak files because the built-in extractor will not work (trust me, I tried). This is being done on Windows Server 2008 R2 using the latest version of PowerShell. &lf; > I am sure there is a prettier way to do this, but it works and I've got time to refine if it need be.


I have never, ever...ever-ever-ever used PowerShell before as I tend to hate all things programming. I've created basic batch files to delete backups, but those are relatively straightforward.

For the task I was trying to tackle today, we need to download the differential backup files for one of our databases, unzip them, and then load them into SQL. I wrote this PowerShell script to do everything except the last part (loading into SQL), but tomorrow is a new day.

Just a quick note beforehand- you have to use a program like 7-Zip for .bak files because the built-in extractor will not work (trust me, I tried). This is being done on Windows Server 2008 R2 using the latest version of PowerShell.


Set-Location -Path E:\folder\$dtoday

$dToday = Get-Date -Format "yyyyMMdd"

New-Item E:\folder\$dtoday -type directory -Force

$WebClient = New-Object System.Net.Webclient

$source = "http://www.SiteIWantToDownloadFrom.com"

$destination = "E:\folder\$dtoday\Diff.zip"

$WebClient.Credentials = New-Object System.Net.NetworkCredential("username","password")

$WebClient.DownloadFile($source,$destination)

$shell=new-object -com shell.application

$CurrentLocation=get-location

$CurrentPath=$CurrentLocation.path

$Location=$shell.namespace($CurrentPath)

C:\7z.exe x $destination -pMy7zipPassword -oE:\folder\$dtoday </script>

I am sure there is a prettier way to do this, but it works and I've got time to refine if it need be.

No comments:

Post a Comment