Counter for dynamic variable name

Lanky Doodle 226 Reputation points
2023-09-06T16:34:46.83+00:00

Hi,

How can this be achieved. I have string values passed to a parameter of a function, and as you can see the allowable values match the start of the variable counters. So instead of this:

switch( $Result ) {
    "Info"    { $Script:InfoMsgCount++ }
    "Success" { $Script:SuccessMsgCount++ }
    "Warning" { $Script:WarningMsgCount++ }
    "Error"   { $Script:ErrorMsgCount++ }
} 

do this:

if( $Result -ne "Default ) { $ResultMsgCount++ }
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,328 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. MotoX80 32,911 Reputation points
    2023-09-06T22:31:03.0233333+00:00

    Try this.

    if( $Result -ne "Default" ) { Invoke-Expression ('$script:' + $Result + "MsgCount++")  }
    
    0 comments No comments