One of My Favorite PowerShell Functions


Summary: Ed Wilson, Microsoft Scripting Guy, discusses one of his favorite functions: Get-EnumValues.

Microsoft Scripting Guy, Ed Wilson, is here. Today I am working on my presentation for Atlanta TechStravaganza 2015, which will happen on August 21. It will be a really cool event, and the Scripting Wife and I are looking forward to attending it. Unfortunately we were unable to attend last year due to a scheduling conflict, so we are really looking forward to this year. It is always a great event with top-flight speakers.

Anyway, I am still messing around with my Windows PowerShell profile…

One of my favorite Windows PowerShell functions is one I wrote a while back. I call it the Get-EnumValues function. The reason I like it is because it will look up a .NET enum class and display the enum name and the enum value. This is cool because when I look up enums on the MSDN website, the enum names are listed, but not the numeric values—and sometimes I like to use the enum numeric value instead of the enum name.

Here is an example that uses the System.Management.Automation.ActionPreference enumeration. It is used to tell a Windows PowerShell cmdlet that is using the standard –ErrorAction parameter how to continue when an error arises. MSDN lists the names, but it does not list the numeric values.

I have seen something like the following:

Stop-Process –name Notepad –ErrorAction 0

But there is no documentation that tells me what a 0 means. By using my Get-EnumValue function, I can easily find what a 0 means (or what a 5 means):

Image of command output

By directly using the enum numeric value, I make it quicker to work from the Windows PowerShell command line. It is not easier to read, but readability is not the major issue when working interactively from the Windows PowerShell console. (However, readability is a major issue when writing a Windows PowerShell script.)

Here is my Get-EnumValues function:

Function get-enumValues

{

 # get-enumValues -enum "System.Diagnostics.Eventing.Reader.StandardEventLevel"

Param([string]$enum)

$enumValues = @{}

[enum]::getvalues([type]$enum) |

ForEach-Object {

$enumValues.add($_, $_.value__)

}

$enumValues

And here is the alias I created for that function:

Set-Alias -Name gev -Value Get-EnumValues | out-null

Here is my complete profile as shown in the Windows PowerShell console:

#——————————————————————————

#

# PowerShell console profile

# ed wilson, msft

#

# NOTES: contains five types of things: aliases, functions, psdrives,

# variables and commands.

# version 1.2

# 7/27/2015

# HSG 7-28-2015

#——————————————————————————

#Aliases

Set-Alias -Name ep -Value edit-profile | out-null

Set-Alias -Name tch -Value Test-ConsoleHost | out-null

Set-Alias -Name gfl -Value Get-ForwardLink | out-null

Set-Alias -Name gwp -Value Get-WebPage | out-null

Set-Alias -Name rifc -Value Replace-InvalidFileCharacters | out-null

Set-Alias -Name gev -Value Get-EnumValues | out-null

#Variables

New-Variable -Name doc -Value "$home\documents" `

   -Description "My documents library. Profile created" `

   -Option ReadOnly -Scope "Global"

if(!(Test-Path variable:backupHome))

{

 new-variable -name backupHome -value "$doc\WindowsPowerShell\profileBackup" `

    -Description "Folder for profile backups. Profile created" `

    -Option ReadOnly -Scope "Global"

}

#PS_Drives

New-PSDrive -Name Mod -Root ($env:PSModulePath -split ';')[0] `

 -PSProvider FileSystem | out-null

#Functions

Function Edit-Profile

{ ISE $profile }

Function Test-ConsoleHost

{

 if(($host.Name -match 'consolehost')) {$true}

 Else {$false}  

}

Function Replace-InvalidFileCharacters

{

 Param ($stringIn,

        $replacementChar)

 # Replace-InvalidFileCharacters "my?string"

 # Replace-InvalidFileCharacters (get-date).tostring()

 $stringIN -replace "[$( [System.IO.Path]::GetInvalidFileNameChars() )]", $replacementChar

}

Function Get-TranscriptName

{

 $date = Get-Date -format s

  "{0}.{1}.{2}.txt" -f "PowerShell_Transcript", $env:COMPUTERNAME,

  (rifc -stringIn $date.ToString() -replacementChar "-") }

Function Get-WebPage

{

 Param($url)

 # Get-WebPage -url (Get-CmdletFwLink get-process)

 (New-Object -ComObject shell.application).open($url)

}

Function Get-ForwardLink

{

 Param($cmdletName)

 # Get-WebPage -url (Get-CmdletFwLink get-process)

 (Get-Command $cmdletName).helpuri

}

Function BackUp-Profile

{

 Param([string]$destination = $backupHome)

  if(!(test-path $destination))

   {New-Item -Path $destination -ItemType directory -force | out-null}

  $date = Get-Date -Format s

  $backupName = "{0}.{1}.{2}.{3}" -f $env:COMPUTERNAME, $env:USERNAME,

   (rifc -stringIn $date.ToString() -replacementChar "-"),

   (Split-Path -Path $PROFILE -Leaf)

 copy-item -path $profile -destination "$destination\$backupName" -force

}

Function get-enumValues

{

 # get-enumValues -enum "System.Diagnostics.Eventing.Reader.StandardEventLevel"

Param([string]$enum)

$enumValues = @{}

[enum]::getvalues([type]$enum) |

ForEach-Object {

$enumValues.add($_, $_.value__)

}

$enumValues

}

#Commands

Set-Location c:\

If(tch) {Start-Transcript -Path (Join-Path -Path `

 $doc -ChildPath $(Get-TranscriptName))}

BackUp-Profile

Profile Week will continue tomorrow when I will talk about more cool stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

Comments (1)

Skip to main content