在PowerShell中增加动态变量

时间:2015-08-12 21:09:09

标签: powershell

我在PowerShell中有一个变量用于创建所有设置为零的其他变量列表,如下所示:

$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
}

我使用这些变量来计算我们拥有的许可类型。所以我然后遍历每个分区,如果用户拥有该许可并且在该分区中,我想简单地将1加到适当的变量中。因此,如果用户John拥有P1许可并且在Div A中,那么变量P1A应该增加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 ++
            }
        }

上面我有set-variable命令,我尝试了$ p1 $ Div ++。我无法弄清楚如何使变量递增。 Set-Variable命令总是将变量设置为字符串值,因此它将其设置为" ++"而不是将它从0移动到1。

2 个答案:

答案 0 :(得分:2)

我使用哈希表来计算,而不是离散变量:

$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"]++
            } 
        }

答案 1 :(得分:1)

@mjolinor有一个更好的方法,所以你应该使用它,但如果你想知道为什么它不起作用,那是因为++是一个运算符,你将它作为值传递给cmdlet。 / p>

你实际上必须用你的方法这样做:

$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 ++  
            } 
        }
    }
}

感谢PetSerAl的评论。