How do I create an enum with string integers in PowerShell?

0
18
Asked By TechieExplorer42 On

I'm working with some code generated automatically through the openapi-generator-cli, but I'm hitting a snag with an enum definition. PowerShell seems to throw an error since it doesn't accept integers as enum labels. I'm trying to figure out how to create an enum that uses string representations of integers instead. For instance, I have the enum defined as follows:

enum SerialInterfaceV130BitRate {
# enum value: "1200"
1200
# enum value: "2400"
2400
# enum value: "4800"
4800
# enum value: "9600"
9600
# enum value: "19200"
19200
# enum value: "38400"
38400
# enum value: "57600"
57600
# enum value: "115200"
115200
# enum value: "230400"
230400
}

I get a ParserError that indicates a missing closing '}' in the statement. I've also tried changing the format to '1200' or '1200'=1200, but those didn't work either. What am I missing?

4 Answers

Answered By ScriptingGuru On

Could you explain how you're trying to use the enum? You have the option to either set the number as the value directly or cast the enum to an integer. Although, editing might not help if the enum's design is incorrect.

TechieExplorer42 -

I tried to adapt the suggestions but keep running into the same parser error. Here’s what I modified:
```powershell
enum SerialInterfaceV130BitRate {
'1200'
'2400'
'4800'
'9600'
'19200'
'38400'
'57600'
'115200'
'230400'
}
```
Nothing seems to fix the missing closing bracket issue!

Answered By CodeMaster33 On

You should use .value__ to access the integer of an enum. For example:

```powershell
enum SerialInterfaceV130BitRate {
V1200 = 1200
V2400 = 2400
V4800 = 4800
V9600 = 9600
V19200 = 19200
V38400 = 38400
V57600 = 57600
V115200 = 115200
V230400 = 230400
}

$ByName = [SerialInterfaceV130BitRate]::V230400
$ByInt32 = [SerialInterfaceV130BitRate] 230400
$AsInt = ([SerialInterfaceV130BitRate] 230400).value__
```
This way, you can work around the issue and play with the values as needed!

ScriptyDude99 -

In theory, you could try using
```powershell
[SerialInterfaceV130BitRate] 1200 -eq 1200
```
That should return true without needing to convert it to an integer.

Answered By DevProX On

It's crucial to remember that enum labels in .NET must adhere to naming conventions, meaning they can't be purely numeric. If you're looking for a collection of values, you might want to consider using an array instead. For stricter typing, using a `HashSet` could be a good alternative!

Answered By PowerShellWhiz On

I think the issue lies in naming conventions—enum identifiers can't start with numbers, similar to variable naming rules in C#. You might want to rethink how you're defining them.

CuriousCoder -

That makes sense! I’ll brainstorm a workaround for the identifiers.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.