Guest User

Untitled

a guest
May 26th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. #requires -Version 3.0
  2. Set-StrictMode -Version Latest
  3.  
  4. function Initialize-KBShortestScriptChallenge {
  5. <#
  6. .SYNOPSIS
  7. Initialize PowerShell environment for Shortest Script Challenge.
  8. .DESCRIPTION
  9. The Initialize-KBShortestScriptChallenge cmdlet removes all single character variables except those specified in ExcludeVariable parameter, switches off strict mode globally and clears all errors.
  10. .PARAMETER ExcludeVariable
  11. Specifies one or more single character variables that will be preserved.
  12. .EXAMPLE
  13. Initialize-KBShortestScriptChallenge -ExcludeVariable x, y, z
  14.  
  15. This command initializes PowerShell environment for Shortest Script Challenge and removes all single character variables except x, y and z.
  16. #>
  17. [CmdletBinding()]
  18. param(
  19. [ValidateScript({$_.Length -eq 1})]
  20. [String[]]$ExcludeVariable = [String]::Empty
  21. )
  22.  
  23. try {
  24. #Cache latest PowerShell build version
  25. if (-not (Get-Variable -Name KBLatestPowerShellBuildVersion -Scope Global -ErrorAction Ignore)) {
  26. Set-Variable -Name KBLatestPowerShellBuildVersion -Value $(Get-KBLatestPowerShellBuildVersion -ErrorAction Stop).Version -Scope Global -Option ReadOnly -Force
  27. }
  28.  
  29. #Warn when initializing PowerShell environment for SSC on former version of PowerShell
  30. if ("v$($PSVersionTable.PSVersion)" -notmatch $Global:KBLatestPowerShellBuildVersion) {
  31. Write-Warning ("Initializing PowerShell environment for Shortest Script Challenge on former version of PowerShell ({0} < {1})" -f "v$($PSVersionTable.PSVersion)" , $Global:KBLatestPowerShellBuildVersion)
  32. }
  33. } catch {
  34. Write-Warning $_.Exception.Message
  35. } finally {
  36. #Extend HistoryInfo type data [/u/bis]
  37. Update-TypeData -TypeName 'Microsoft.PowerShell.Commands.HistoryInfo' -MemberType ScriptProperty -MemberName 'Duration' -Force -Value {
  38. $this.EndExecutionTime - $this.StartExecutionTime
  39. }
  40. Update-TypeData -TypeName 'Microsoft.PowerShell.Commands.HistoryInfo' -MemberType ScriptProperty -MemberName 'Length' -Force -Value {
  41. $this.CommandLine.Length
  42. }
  43.  
  44. #Remove all single character variables except excluded
  45. foreach ($character in (65..90 | Where-Object {$_ -NotIn [int[]][char[]]$ExcludeVariable.ToUpper()})) {
  46. Remove-Variable ([char]$character) -Scope Global -Force -ErrorAction Ignore
  47. }
  48.  
  49. #Switch off strict mode globally
  50. Set-PSDebug -Off
  51.  
  52. #Clear any errors
  53. $Error.Clear()
  54. }
  55. }
Add Comment
Please, Sign In to add comment