Share via


PowerShell Snippets Pt. 1

Below are a number of PowerShell snippets that I have find useful. This is just part 1. I will add more along the way.

Running as Admin

Often you need your script to run as admin - with this function you can check before hand that this is actually the case.

 function Check-RunningAsAdmin 
{ 
 $id=[System.Security.Principal.WindowsIdentity]::GetCurrent() 
 $principal=New-ObjectSystem.Security.Principal.WindowsPrincipal($id) 
 $administrator=[System.Security.Principal.WindowsBuiltInRole]::Administrator 
 $elevated=$principal.IsInRole($administrator) 
 if (!$elevated) 
 { 
 throw "You need to start PowerShell as Administrator to run this script" 
 } 
}

Comparison Operators

Just for reference if you are used to e.g. .NET operators it can be difficult to remember to PowerShell equivalent.

-eq Equal to -lt Less than -gt Greater than -ge Greater than or Eqaul to -le Less than or equal to -ne Not equal to

Logical Operators

Just for reference if you are used to e.g. .NET operators it can be difficult to remember to PowerShell equivalent.-not Not ! Not -and And -or Or

Support for "-WhatIf" and "-Confirm"

WhatIf and Confirm are commands for testing scripts without actually running it. Using the -WhatIf switch, you get to preview what will happen.

 function Start-VisualStudio2012 
{ 
 [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Low")] 
 
 param ( 
 [parameter(Mandatory=$true)] 
 [bool]$WaitForProcess 
 ) 
 
 PROCESS 
 { 
 $visualStudioPath="${env:ProgramFiles(x86)}Microsoft Visual Studio 12.0Common7IDEdevenv.exe" 
 $visualStudioWorkingDir="${env:ProgramFiles(x86)}Microsoft Visual Studio 12.0Common7IDE" 
 
 if($pscmdlet.ShouldProcess("Visual Studio 2012")) 
 { 
 if($WaitForProcess) 
 { 
 Start-Process-FilePath$visualStudioPath-Wait-WorkingDirectory$visualStudioWorkingDir 
 } 
 else 
 { 
 Start-Process-FilePath$visualStudioPath-WorkingDirectory$visualStudioWorkingDir 
 } 
 } 
 else 
 { 
 #WhatIf code here 
 Write "Launch process $visualStudioPath" 
 } 
 } 
}

Running this code with -WhatIf:

Setting $ConfirmPreference = "Low" will cause a confirmation prompt:

Inside the function you can of course change the ConfirmImpact depending on what the impact is of what you are trying to do.