2015-10-22

Regular checks before running Powershell script + Write-Error replacement

On occasion, one will produce the script that will not work in _ISE or on some particular version of Powershell. So, before allowing script to run, I always do several checks depending on the task at hand. Here's the code:

       
#region Check
if ($host.Name -ne 'ConsoleHost')
{
    #Running in ISE
    $host.UI.WriteErrorLine("`t Script can not be run in _ISE. Exiting.")
    Exit 1
}

if (($PSVersionTable).PSVersion.Major -lt 3) {
    $host.UI.WriteErrorLine("`t Script can not be run in PS 2. Exiting.")
    Exit 2
}

$clrV = 
  ((Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
  Get-ItemProperty -name Version,Release -EA 0 |
  Where { $_.PSChildName -match '^(?!S)\p{L}'} |
  Select Version | Sort Version -Desc | Select -First 1).Version).Split('.')[0]
if ( $clrV -lt 4) {
    $host.UI.WriteErrorLine("`t Script can not be run in .NET v"+$clrV+". Exiting.")
    Exit 3
}

Set-StrictMode -Version Latest
Set-PSDebug -strict

#endregion
       

Explanation:
  • Regions are great for increased readability, especially when script is big.
  • There are differences between Powershell Console and ISE (see points 3 and 4 for example):
    PS C:\Users\user> $host.Name
    ConsoleHost
    PS:ISE [BOX]> $Host.Name
    Windows PowerShell ISE Host
  • I have PS v3 on my laptop and PS v4 on my Labs servers thus not coding (or testing) for older versions.
  • Getting the .NET version could have been much simpler if it wasn't for the fact that [environment]::version will get deprecated soon:
    PS C:\Users\user> [environment]::version
    Major  Minor  Build  Revision
    -----  -----  -----  --------
    4      0      30319  34209
  • Set-PSDebug -strict is there so that engine can throw an exception if a variable is referenced before being assigned a value.
  • Using $host.UI.WriteErrorLine produces much cleaner output, imo, than Write-Error.

Happy coding!

No comments:

Post a Comment