Powershell 获得备用许可证

Powershell get spare licenses

我正在尝试通过 Get-MsolAccountSku 命令获取可用的备用许可证数量。

这是代码(输出如下)

$Licenses = Get-MsolAccountSku
$spare = Foreach ($License in $licenses)
{
  ($License.ActiveUnits - $License.ConsumedUnits)   
}

Get-MsolAccountSku | Select-Object -Property AccountSkuId,ActiveUnits,ConsumedUnits,@{L=’SpareLicenses’;E={$spare}}

我想在输出的右侧添加一列,以列出在 ForEach 循环中减法后可用的许可证数量。

ActiveUnits ConsumedUnits
----------- -------------
         30            26
       1601             1
         30            29
         25             0
          5             3
          1             0
      12550         12465
    1000000         12461
      12550         12466
      12555         12468
         31            19
      12550         12464

不需要您的 $spare 对象,只需更新 Select 进行计算...

Get-MsolAccountSku | 
Select-Object -Property AccountSkuId,ActiveUnits,ConsumedUnits,
@{L=’SpareLicenses’;E={$_.ActiveUnits - $_.ConsumedUnits}}

来自about Calculated Properties

The calculated property is defined by a hashtable containing key-value pairs that specify the name of the new property, an expression to calculate the value, and optional formatting information.

  • expression - A script block used to calculate the value of the new property.

按照您的代码,您应该更改脚本块的 foreach 循环:

$Licenses = Get-MsolAccountSku
$spare = { $_.ActiveUnits - $_.ConsumedUnits }

# $_ - References to each object being passed through the pipeline
# See about Automatic Variables for more information

Get-MsolAccountSku |
Select-Object -Property AccountSkuId,ActiveUnits,ConsumedUnits,@{
    Name = 'SpareLicenses'
    Expression = $spare
}