I've got a variable that I am trying to define in PSCustomObject but it always errors out and will not populate the IsLicesned custom object, the UPN and Department are fine.
$Report = [PSCustomObject]@{
Upn = $ADuser.UserPrincipalName
DEpartment = $ADUser.Department
IsLicensed = $False}
If ($license | where {$_.CapabilityStatus -eq "enabled"}){
**IsLicensed** = $True} <-- trying to define this variable
If I go old school it works:
$CSV = "c:\2022-02-11_UPNreport.csv"
$ImportCSV = import-csv $CSV
$report = @()
foreach ($user in $ImportCSV){
$ADUser = Invoke-Command -scriptblock {Get-AzureADUser -Filter "userprincipalname eq '$($user.UserPrincipalName)'"}
$license = Invoke-Command -scriptblock {Get-AzureADUser -Filter "userprincipalname eq '$($user.UserPrincipalName)'" | select -ExpandProperty AssignedPlans}
$user = New-Object psobject
$user | Add-Member -MemberType NoteProperty -Name UserPrincipalName -Value $null
$user | Add-Member -MemberType NoteProperty -Name Department -Value $null
$user | Add-Member -MemberType NoteProperty -Name IsLicensed -Value $False
$user.userprincipalname = $ADUser.userprincipalname
$user.department = $ADUser.Department
If ($license | where {$_.CapabilityStatus -eq "enabled"}){
$user.IsLicensed = $True}
$report = $user
}
$Report
CodePudding user response:
I'm not sure I understand the uses of Invoke-Command
they seem to be pointless, on the other hand adding elements ( =
) to a fixed collection (@()
) is slow (exponentially slow), see this answer for details.
$CSV = "c:\2022-02-11_UPNreport.csv"
$ImportCSV = Import-Csv $CSV
$report = foreach ($user in $ImportCSV.UserPrincipalName) {
Get-AzureADUser -Filter "userprincipalname eq '$user'" |
Select-Object UserPrincipalName, Department, @{
Name = 'IsLicensed' # -eq can act as a filter when LHS is Array.
Expression = { [bool]($_.AssignedPlans.CapabilityStatus -eq 'Enabled') }
}
}
$report
For the expression on the calculated property, consider these examples:
-eq
filters the array on the Left-Hand side where the elements are equal to Enabled, if no element is found the result is$null
:
'Enabled', 'Disabled' -eq 'Enabled' # => Enabled
'Disabled', 'Disabled' -eq 'Enabled' # => $null
- Any string that is not empty (
[string]::Empty
or''
) when converted to boolean will be$true
, in that sense, using the examples above:
[bool]('Enabled', 'Disabled' -eq 'Enabled') # => True
[bool]('Disabled', 'Disabled' -eq 'Enabled') # => False
CodePudding user response:
Try this
$Report = [PSCustomObject]@{
Upn = $ADuser.UserPrincipalName
Department = $ADUser.Department
IsLicensed = $license.CapabilityStatus -contains "enabled"
}