2016-11-23

Not long ago I had to work on a Site Collection creation PowerShell script that could be usable by any SharePoint user.
In order to make it as easy as I could for the user I looked for a way of not simply asking the user to enter manually the required information and just create the Site Collection.
Instead, I wanted to fetch information like a list of all available WebApps or Templates so the user (who might not know them by heart) could simply browse the list with the Up and Down arrows and just select the required one by pressing enter.

The most efficient way, to my mind, would be to display one choice at a time, on a single line, and this line would update when the user press Up or Down. After several hours of research on the Web, I couldn’t find anything that would do the trick, so I decided to try something by myself and share it if I found a smart efficient way to make it happen.

I came out with this piece of code that fetches a list of all the WebApps’ url and display them as mentioned, feel free to adapt it !

## Initiate Site Collection creation
Write-Host ” – New Site Collection creation – `n”
try{
## Fetch a list of all the Web Application available (except Central Admin)
$WebApps = Get-SPWebApplication | Select-Object url
$i=0
## Determine colors of user interface to permit highlighting
$fcolor = $host.UI.RawUI.ForegroundColor
$bcolor = $host.UI.RawUI.BackgroundColor
## Initiate infos gathering for Site creation
Write-Host “WebApp :”
## Write the first choice [0] in the array) a first time to avoid a blank before entering the loop
Write-Host “$($WebApps[$i].url) ” -nonewline -fore $bcolor -back $fcolor
## Display a dynamic list of WebApps, the user can navigate through by using Up and Down arrows
While ($key -ne 13) {
$pres = $host.ui.rawui.readkey(“NoEcho,IncludeKeyDown”)
$key = $pres.virtualkeycode
If (($key -eq 38) -and ($i -lt ($WebApps.count -1))) {$i++}
If (($key -eq 40) -and ($i -gt 0)) {$i–}
## This Write-Host overwrite the precedent one at each occurrence of the loop thus giving the illusion
## that the user is navigating in a drop-down menu
Write-Host “`r$($WebApps[$i].url) ” -nonewline -fore $bcolor -back $fcolor
}
$WebApp = $($WebApps[$i].url)
Write-Host `n
}
catch [Exception,{
Write-Host “Error :” $_.Exception.Message `n -foregroundcolor Red
}

The result looks like this
I hope this can be useful ! 😉

About the author 

Hamza Hassoun