Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #requires -Version 3.0
- Set-StrictMode -Version Latest
- function Initialize-KBShortestScriptChallenge {
- <#
- .SYNOPSIS
- Initialize PowerShell environment for Shortest Script Challenge.
- .DESCRIPTION
- The Initialize-KBShortestScriptChallenge cmdlet removes all single character variables except those specified in ExcludeVariable parameter, switches off strict mode globally and clears all errors.
- .PARAMETER ExcludeVariable
- Specifies one or more single character variables that will be preserved.
- .EXAMPLE
- Initialize-KBShortestScriptChallenge -ExcludeVariable x, y, z
- This command initializes PowerShell environment for Shortest Script Challenge and removes all single character variables except x, y and z.
- #>
- [CmdletBinding()]
- param(
- [ValidateScript({$_.Length -eq 1})]
- [String[]]$ExcludeVariable = [String]::Empty
- )
- try {
- #Cache latest PowerShell build version
- if (-not (Get-Variable -Name KBLatestPowerShellBuildVersion -Scope Global -ErrorAction Ignore)) {
- Set-Variable -Name KBLatestPowerShellBuildVersion -Value $(Get-KBLatestPowerShellBuildVersion -ErrorAction Stop).Version -Scope Global -Option ReadOnly -Force
- }
- #Warn when initializing PowerShell environment for SSC on former version of PowerShell
- if ("v$($PSVersionTable.PSVersion)" -notmatch $Global:KBLatestPowerShellBuildVersion) {
- Write-Warning ("Initializing PowerShell environment for Shortest Script Challenge on former version of PowerShell ({0} < {1})" -f "v$($PSVersionTable.PSVersion)" , $Global:KBLatestPowerShellBuildVersion)
- }
- } catch {
- Write-Warning $_.Exception.Message
- } finally {
- #Extend HistoryInfo type data [/u/bis]
- Update-TypeData -TypeName 'Microsoft.PowerShell.Commands.HistoryInfo' -MemberType ScriptProperty -MemberName 'Duration' -Force -Value {
- $this.EndExecutionTime - $this.StartExecutionTime
- }
- Update-TypeData -TypeName 'Microsoft.PowerShell.Commands.HistoryInfo' -MemberType ScriptProperty -MemberName 'Length' -Force -Value {
- $this.CommandLine.Length
- }
- #Remove all single character variables except excluded
- foreach ($character in (65..90 | Where-Object {$_ -NotIn [int[]][char[]]$ExcludeVariable.ToUpper()})) {
- Remove-Variable ([char]$character) -Scope Global -Force -ErrorAction Ignore
- }
- #Switch off strict mode globally
- Set-PSDebug -Off
- #Clear any errors
- $Error.Clear()
- }
- }
Add Comment
Please, Sign In to add comment