2

I have a variable in PowerShell that I use to create a list of other variables all set to zero like so:

$DivList= "A", "B", "C"
Foreach($Div in $DivList)
{
    New-Variable -Name "P1$div" -Value 0
    New-Variable -Name "E1$div" -Value 0
    New-Variable -Name "E3$div" -Value 0
}

I use these variables to do a count of what type of licenses we have. So I then iterate through each of the divisions, and I want to simply add 1 to the proper variable if the user has that license and is in that division. So if user John has a P1 license and is in Div A then Variable P1A should increment up by 1.

$Users = get-msoluser -MaxResults 3000

Foreach ($user in $users)
{
    if($user.licenses.AccountSkuID -eq $P1)
    {
        ForEach($Div in $DivList)
        {
            if($user.Department -like $Div)
            {
                Set-Variable -Name "P1$Div" -Value ++
                $P1$Div ++
            }
        }

Above I have both the set-variable command and I tried $p1$Div ++. I can't figure out how to make the variable increment up. The Set-Variable command always sets the variable like it is a string value, so it will set it to "++" instead of moving it from 0 to 1.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Guralchuk
  • 23
  • 2
  • 5

2 Answers2

2

I'd use a hash table for the counts, rather than discrete variables:

$DIVCounts = @{}
$DivList= "A","B","C"
Foreach($Div in $DivList)
{ 
  $DIVCounts["P1$div"] = 0
  $DIVCounts["E1$div"] = 0
  $DIVCounts["E3$div"] = 0
}

$Users = get-msoluser -MaxResults 3000 

Foreach ($user in $users)
{
    if($user.licenses.AccountSkuID -eq $P1)
    {
        ForEach($Div in $DivList)
        {
            if($user.Department -like $Div)
            {
                $DIVCountss["P1$Div"]++
            } 
        }
mjolinor
  • 66,130
  • 7
  • 114
  • 135
1

@mjolinor has a better approach so you should use that, but if you want to know why it's not working, it's because ++ is an operator and you're passing it into a cmdlet as a value.

You would actually have to do it like this with your approach:

$Users = get-msoluser -MaxResults 3000 

Foreach ($user in $users)
{
    if($user.licenses.AccountSkuID -eq $P1)
    {
        ForEach($Div in $DivList)
        {
            if($user.Department -like $Div)
            {
                #$newVal = (Get-Variable -Name "P1$Div").Value + 1
                #Set-Variable -Name "P1$Div" -Value $newVal
                ++(Get-Variable -Name "P1$Div").Value
                $P1$Div ++  
            } 
        }
    }
}

Edited thanks to PetSerAl's comment.

briantist
  • 45,546
  • 6
  • 82
  • 127