SlideShare una empresa de Scribd logo
1 de 13
Using enums in Powershell
Jason
Enum
 Enums are a very useful way to encode "options" in .NET programming.
 They offer a mechanism to represent a fixed set of known values, named in
a developer-friendly way.
Using enums in Powershell
 Let's start examining this support by looking at the DayOfWeek enum.
PS> $now = Get-Date
PS> $now.DayOfWeek
Thursday
PS> $now | Get-Member DayOfWeek
TypeName: System.DateTime
Name MemberType Definition
---- ---------- ----------
DayOfWeek Property System.DayOfWeek DayOfWeek {get;}
Possible enum values
PS> [Enum]::GetNames( [System.DayOfWeek] )
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Creating enum instances
 The most direct way is to use the same "::" syntax used when accessing
static .NET
 Another option is to cast a string containing a valid enum name into the
enum type:
PS> $enumVal = [System.DayOfWeek]::Monday
PS> $enumVal = [System.DayOfWeek]::Sunday
PS> $enumVal = [System.DayOfWeek] 'Sunday'
Defining new enum types
 Let's look at how to define a brand new enum type within your Powershell
script
PS> $enumVal = [System.DayOfWeek] 'Sunday'
Add-Type -TypeDefinition @"
public enum SimpleEnumType
{
Value1,
Value2,
Value3
}
"@
PS> [SimpleEnumType]::Value1
Value1
Add-Type
 The Add-Type cmdlet lets you define a .NET Framework class in your
Windows PowerShell session
Add-Type -TypeDefinition
PS>$source = @"
public class BasicTest
{
public static int Add(int a, int b)
{
return (a + b);
}
public int Multiply(int a, int b)
{
return (a * b);
}
}
"@
C:PS> Add-Type -TypeDefinition $source
Add-Type -path
Add-Type -Path C:TempBasicTest.dll
Add-Type -Path C:TempBasicTest.cs
Defining new enum types
 If you don't give enum names explicit values, they will be automatically
numbered starting from 0.
PS> [SimpleEnumType]::Value1 -as [int]
0
PS> [SimpleEnumType]::Value2 -as [int]
1
PS> [SimpleEnumType]::Value3 -as [int]
2
Defining new enum types
 You can also define specific integer values for each enum value
Add-Type -TypeDefinition @"
public enum ExplicitEnumType
{
None = 0,
Value1 = 1,
Value2 = 10,
Value3 = 100
}
"@
PS> [ExplicitEnumType]::Value2 -as [int]
10
Defining new enum types
 If you want to provide explicit support for bitwise combinations of values
Add-Type -TypeDefinition @“
[System.Flags]
public enum FlagsEnumType
{
None = 0,
Value1 = 1,
Value2 = 2,
Value3 = 4
}
"@
PS> [FlagsEnumType] "Value1, Value3"
Value1, Value3
Reference
 Using enums in Powershell
 http://latkin.org/blog/2012/07/08/using-enums-in-powershell/
 MSND Add-Type
 http://technet.microsoft.com/en-us/library/hh849914.aspx

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Sequence Types in Python Programming
Sequence Types in Python ProgrammingSequence Types in Python Programming
Sequence Types in Python Programming
 
Open course(programming languages) 20150225
Open course(programming languages) 20150225Open course(programming languages) 20150225
Open course(programming languages) 20150225
 
codin9cafe[2015.02.25]Open course(programming languages) - 장철호(Ch Jang)
codin9cafe[2015.02.25]Open course(programming languages) - 장철호(Ch Jang)codin9cafe[2015.02.25]Open course(programming languages) - 장철호(Ch Jang)
codin9cafe[2015.02.25]Open course(programming languages) - 장철호(Ch Jang)
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Pipes and filters
Pipes and filtersPipes and filters
Pipes and filters
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
1. python
1. python1. python
1. python
 
Class 7a: Functions
Class 7a: FunctionsClass 7a: Functions
Class 7a: Functions
 
Unix Tutorial
Unix TutorialUnix Tutorial
Unix Tutorial
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
Python overview
Python   overviewPython   overview
Python overview
 
Teeing Up Python - Code Golf
Teeing Up Python - Code GolfTeeing Up Python - Code Golf
Teeing Up Python - Code Golf
 
Functions
FunctionsFunctions
Functions
 
lab4_php
lab4_phplab4_php
lab4_php
 
Java 1-contd
Java 1-contdJava 1-contd
Java 1-contd
 
Java chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and useJava chapter 6 - Arrays -syntax and use
Java chapter 6 - Arrays -syntax and use
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 

Destacado (7)

Tipo music-ui-規劃原則
Tipo music-ui-規劃原則Tipo music-ui-規劃原則
Tipo music-ui-規劃原則
 
2013 jsdc webworker
2013 jsdc webworker2013 jsdc webworker
2013 jsdc webworker
 
Ken 20150306 心得分享
Ken 20150306 心得分享Ken 20150306 心得分享
Ken 20150306 心得分享
 
Learning tech week_1_james
Learning tech  week_1_jamesLearning tech  week_1_james
Learning tech week_1_james
 
mongoose
mongoosemongoose
mongoose
 
Introduction of lambda expression and predicate builder
Introduction of lambda expression and predicate builderIntroduction of lambda expression and predicate builder
Introduction of lambda expression and predicate builder
 
Raphael JavaScript Library
Raphael JavaScript LibraryRaphael JavaScript Library
Raphael JavaScript Library
 

Similar a Powershell enum

define a class name Employee whose objects are records for employee..pdf
define a class name Employee whose objects are records for employee..pdfdefine a class name Employee whose objects are records for employee..pdf
define a class name Employee whose objects are records for employee..pdf
fashioncollection2
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
ICADCMLTPC
 

Similar a Powershell enum (20)

Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
The Power of PowerShell: Advanced
The Power of PowerShell: Advanced The Power of PowerShell: Advanced
The Power of PowerShell: Advanced
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4
 
Getters_And_Setters.pptx
Getters_And_Setters.pptxGetters_And_Setters.pptx
Getters_And_Setters.pptx
 
Lecture 6 Enumeration in java ADVANCE.pptx
Lecture 6 Enumeration in java ADVANCE.pptxLecture 6 Enumeration in java ADVANCE.pptx
Lecture 6 Enumeration in java ADVANCE.pptx
 
define a class name Employee whose objects are records for employee..pdf
define a class name Employee whose objects are records for employee..pdfdefine a class name Employee whose objects are records for employee..pdf
define a class name Employee whose objects are records for employee..pdf
 
C# p8
C# p8C# p8
C# p8
 
C# p9
C# p9C# p9
C# p9
 
Developer Guide
Developer GuideDeveloper Guide
Developer Guide
 
Methods.ppt
Methods.pptMethods.ppt
Methods.ppt
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
Sharable_Java_Python.pdf
Sharable_Java_Python.pdfSharable_Java_Python.pdf
Sharable_Java_Python.pdf
 
Class 10
Class 10Class 10
Class 10
 
Getting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem SolvingGetting Started - Console Program and Problem Solving
Getting Started - Console Program and Problem Solving
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
 
java script
java scriptjava script
java script
 
Chap1 array
Chap1 arrayChap1 array
Chap1 array
 
2. Create a Java class called EmployeeMain within the same project Pr.docx
 2. Create a Java class called EmployeeMain within the same project Pr.docx 2. Create a Java class called EmployeeMain within the same project Pr.docx
2. Create a Java class called EmployeeMain within the same project Pr.docx
 
ARRAYS.ppt
ARRAYS.pptARRAYS.ppt
ARRAYS.ppt
 

Más de LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection &amp; activator
Reflection &amp; activatorReflection &amp; activator
Reflection &amp; activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Powershell enum

  • 1. Using enums in Powershell Jason
  • 2. Enum  Enums are a very useful way to encode "options" in .NET programming.  They offer a mechanism to represent a fixed set of known values, named in a developer-friendly way.
  • 3. Using enums in Powershell  Let's start examining this support by looking at the DayOfWeek enum. PS> $now = Get-Date PS> $now.DayOfWeek Thursday PS> $now | Get-Member DayOfWeek TypeName: System.DateTime Name MemberType Definition ---- ---------- ---------- DayOfWeek Property System.DayOfWeek DayOfWeek {get;}
  • 4. Possible enum values PS> [Enum]::GetNames( [System.DayOfWeek] ) Sunday Monday Tuesday Wednesday Thursday Friday Saturday
  • 5. Creating enum instances  The most direct way is to use the same "::" syntax used when accessing static .NET  Another option is to cast a string containing a valid enum name into the enum type: PS> $enumVal = [System.DayOfWeek]::Monday PS> $enumVal = [System.DayOfWeek]::Sunday PS> $enumVal = [System.DayOfWeek] 'Sunday'
  • 6. Defining new enum types  Let's look at how to define a brand new enum type within your Powershell script PS> $enumVal = [System.DayOfWeek] 'Sunday' Add-Type -TypeDefinition @" public enum SimpleEnumType { Value1, Value2, Value3 } "@ PS> [SimpleEnumType]::Value1 Value1
  • 7. Add-Type  The Add-Type cmdlet lets you define a .NET Framework class in your Windows PowerShell session
  • 8. Add-Type -TypeDefinition PS>$source = @" public class BasicTest { public static int Add(int a, int b) { return (a + b); } public int Multiply(int a, int b) { return (a * b); } } "@ C:PS> Add-Type -TypeDefinition $source
  • 9. Add-Type -path Add-Type -Path C:TempBasicTest.dll Add-Type -Path C:TempBasicTest.cs
  • 10. Defining new enum types  If you don't give enum names explicit values, they will be automatically numbered starting from 0. PS> [SimpleEnumType]::Value1 -as [int] 0 PS> [SimpleEnumType]::Value2 -as [int] 1 PS> [SimpleEnumType]::Value3 -as [int] 2
  • 11. Defining new enum types  You can also define specific integer values for each enum value Add-Type -TypeDefinition @" public enum ExplicitEnumType { None = 0, Value1 = 1, Value2 = 10, Value3 = 100 } "@ PS> [ExplicitEnumType]::Value2 -as [int] 10
  • 12. Defining new enum types  If you want to provide explicit support for bitwise combinations of values Add-Type -TypeDefinition @“ [System.Flags] public enum FlagsEnumType { None = 0, Value1 = 1, Value2 = 2, Value3 = 4 } "@ PS> [FlagsEnumType] "Value1, Value3" Value1, Value3
  • 13. Reference  Using enums in Powershell  http://latkin.org/blog/2012/07/08/using-enums-in-powershell/  MSND Add-Type  http://technet.microsoft.com/en-us/library/hh849914.aspx