Tuesday, January 11, 2011

Powershell Pause - Ask to Continue Script

I have been working on some SharePoint PowerShell scripts to automatically restore a SharePoint site collection (often to a different domain), add new users to the site, update master page, etc.

Because often I had one PowerShell script that did many things, sometimes, especially when developing them, I didn't actually want to perform every step of the script. So, one of the first things I did was create a function "AskToProceed" that would prompt me before each step, and I would have the option to perform that step, or skip it.

I have found this script to be particularly useful, and although simple, I thought I would share it.


# function AskToProceed
# Prompt user to proceed
# Parameters:
# $TextQuestion - question to pose
# $Default - default answer - should be 'y' or 'n'
function AskToProceed {
param ($TextQuestion, $Default)
Write-Host -NoNewline "$TextQuestion [y/n]($default): "
$ans = $host.UI.RawUI.ReadKey("IncludeKeyUp")
Write-Host
if ($ans.character -eq 13) {
if ($Default -eq "y") {
return $true
} else {
if ($Default -eq "n") {
return $false
}
}
} else {
if ($ans.character.ToString() -eq "y") {
return $true
} else {
if ($ans.character.ToString() -eq "n") {
return $false
}
}
}
# unknown response, ask again
return AskToProceed $TextQuestion $Default
}

Here's how you would invoke it-below is a script to restore a site collection backup file:

$SiteCollection="http://localhost/MySiteCol"
$SiteCollectionBackupFilename = "d:\backups\MySiteColBackup.bak"
# restore the site
if (AskToProceed "Restore site collection backup '$SiteCollectionBackupFilename' to $SiteCollection" "y") {
Restore-SPSite -Identity $SiteCollection -Path $SiteCollectionBackupFilename -Force
}

When ran in console, the following is displayed:
Ask to Proceed PowerShell Screen Shot

As you can see, it's waiting on my input. The only valid keys are:
  • 'y' - Performs the restore
  • 'n' - Skips the restore
  • [enter] - Performs default action-in this case, it's 'y' which I specified as a parameter

I also could choose to abort the script entirely by pressing [ctrl]-c.

Now I find myself always throwing an "if AskToProceed" check before all of my commands.

No comments:

Post a Comment