How can I pass a specific item property to a variable in PowerShell? - azure

I'm currently working on a script to manage Azure AD (as opposed to the console GUI) and am having issues at one particular part. I'm trying to do an 'add user to group' module, but with Add-AzureADGroupMember requiring the group ObjectId and not display name, it's not initially user-friendly.
Here's what I tried initially:
>> $UPN = "someuser#domain.com"
>> $Selected = "Group Display Name"
>> $Group = Get-AzureADGroup -Filter "DisplayName eq '$Selected'" -All $true | Select-Object -Property ObjectID
>> Add-AzureADGroupMember -ObjectID $Group -RefObjectID $UPN
The problem I have with this, is that $Group is returning '#{ObjectId=fba435cc-913c-46a0-9932-17c01733e143}' as opposed to '{fba435cc-913c-46a0-9932-17c01733e143}'
Is there a better way I can pass the group's ObjectID to a variable? I'd like for users to be able to select the display name and have the variable return the objectID.

To get just the value of a property, use ForEach-Object -MemberName instead of Select-Object -Property:
$Group = Get-AzureADGroup -Filter "DisplayName eq '$Selected'" -All $true | ForEach-Object -MemberName ObjectID

Related

azure ad group name and member count

i have a lots of azure ad group with this format "AA - BB - xxx" where xxx can be anything.
i am trying to do a report on how many members in this azure ad group by display the azure ad group name and the number of its members.
i know to do 1 group is using this:
(Get-AzureADGroupMember -all 1 -ObjectId "xxxxx").count
how do i do lots of group with same group naming format to display its name and number of members?
thanks.
You need to first get all groups with such a name and then loop over the resulting list like:
$result = Get-AzureADGroup -Filter "startswith(DisplayName, 'AA - BB -')" -All $true | ForEach-Object {
[PsCustomObject]#{
Group = $_.DisplayName
MemberCount = #(Get-AzureADGroupMember -ObjectId $_.ObjectId -All $true).Count
}
}
# output on screen
$result | Format-Table -AutoSize
# save as Csv file
$result | Export-Csv -Path 'X:\PathTo\GroupMemberCount.csv' -NoTypeInformation
Apparently, the startswith() Filter on Get-AzureADGroup does not always return the wanted results (depending on the version of the OData language??).
In that case do
$result = Get-AzureADGroup | Where-Object {$_.DisplayName -like 'AA - BB -*'} | ForEach-Object {...}

list all vendors in azure ad who had logged/never logged in the past 24 hours

I wrote a script to list all vendors in the azure ad to check if they are working or not. the script find the logged in users for the past day and if there is a record it should print, if there is no record and the vendor did not logged in or work it should print no login records. but my script is not working well any one can help?
###########################Here is the code ##################
#get azure ad users
$AzADUsers = get-azureaduser
#start for loop
foreach ($user in $AzADUsers){
#list attributes
$dp = $user.DisplayName
$company = $user.CompanyName
# list of contractors/vendors who didn't log in during the day.
if ($company -eq "Vendor Resource - companyname1" -or $company -eq "Vendor Resource - companyname2" -or $company -eq "Vendor Resource - companyname3") {
#check if they logged in the past 24 hours
$SetDate = (Get-Date).AddDays(-1);
$SetDate = Get-Date($SetDate) -format yyyy-MM-dd
$AllSiginLogs = Get-AzureADAuditSignInLogs -Filter "createdDateTime gt $SetDate"
$LoginRecord = $AllSiginLogs | Sort-Object CreatedDateTime -Descending
if($LoginRecord.Count -gt 0){
$lastLogin = $LoginRecord[0].CreatedDateTime
}
else{
$lastLogin = 'no login record | Sick'
}
Write-Host "Last logon time : " $lastLogin $dp $company
Write-Host " "
}
}
in addition to our discussion:
Currently you loop through the $AzAdUsers and query foreach the SignInLogs. But you do not filter the SignInLogs for the specific user, you query all the time the same information and select the latest entry from that log, but it has no relation to the current user.
You have to filter the SignInLog for the specific user, e.g.:
$AllSiginLogs = Get-AzureADAuditSignInLogs -filter "Id eq '$($user.Id)' and createdDateTime gt $SetDate"
After that you could do:
$attrsht = #{
userId=$User.id
DisplayName=$user.displayname
LastSignIn=$LoginRecord.CreatedDateTime
}
new-object -typename psobject -property $attrsht
Btw. the AzModule will be replaced by the microsoft.graph modules. So it might be the right time to do the switch, which you have to do in any case until 2024.
If you do so, you can directly get the lastSignInDateTime from the user object:
#Switch to beta API
select-mgprofile -name beta
$lastSignIn = get-mguser -userId $user.id -Property signinactivity
$lastSignIn.LastSignInDateTime
In regards to you latest comment:
once again, if you want to know the last signInDateTime for a specific user you have to filter for that user id. if you filter by companyname you will probably get several users back and then you have to loop over this array of users and query the signInLog foreach user. the problem you are facing is that you miss to specify consistensylevel and countvariable, e.g.:
$company = "MyCompanyName"
$users = Get-MgUser -filter "companyname eq '$company'" -ConsistencyLevel eventual -CountVariable $null -property Id,CompanyName,DisplayName
select-mgprofile -Name beta
$lastSignInDateTime = #(
foreach ($user in $users){
$LoginRecord = get-mguser -userId $user.id -Property signinactivity
$attrsht = #{
userId=$User.id
DisplayName=$user.displayname
CompanyName=$user.CompanyName
LastSignIn=$LoginRecord.signinactivity.LastSignInDateTime
}
new-object -typename psobject -property $attrsht
}
)
You need to have the MgGraph module installed to run the above mentioned cmdlets -> install-module microsoft.graph
More information in regards to consistensylevel:
https://devblogs.microsoft.com/microsoft365dev/build-advanced-queries-with-count-filter-search-and-orderby/

Can't add device to Azure Active Directory because it has two Object IDs

When I try to add the device looping through a txt file, it says its already a member. When I check the members in the group, nothing changes. From what I've researched, this is due to hybrid setup with on-prem and Azure AD, but I would like to add the devices to the Azure group.
$azgroup = "myGroup"
$machines = get-content ".\deviceList.txt"
write-host "Getting Object ID of group.." -ForegroundColor Green
$objid = (get-azureadgroup -Filter "DisplayName eq '$azgroup'" ).objectid
write-host "Getting group members (We dont want duplicates!).." -ForegroundColor Cyan
$members = Get-AzureADGroupMember -ObjectId $objid -all $true | select displayname
foreach ($machine in $machines) {
$refid = Get-AzureADDevice -Filter "DisplayName eq '$machine'"
$result = ""
$result = ($members -match $machine)
if($result -eq ""){
try{
Write-host "Adding " $refid.displayname -ForegroundColor Cyan
Add-AzureADGroupMember -ObjectId $objid -RefObjectId $refid.objectid[0]
}
catch{
write-host "An error occured for " $refid.displayname -ForegroundColor Red
}
}
else
{
write-host $machine " is already a member" -ForegroundColor Green
}
}
I tried treating the specific ObjectID as an array but neither worked to add to Azure AD group
Add-AzureADGroupMember -ObjectId $objid -RefObjectId $refid.objectid[0]
If the AzureAD module doesn't work within a hybrid infrastructure, is there any way to bulk add devices to a group in Azure AD?
Here is the working solution. Ok so due to each device having more than one reference IDs, I just treated like an array. This is the part of my code I had to change:
[String]$refid = (Get-AzureADDevice -Filter "DisplayName eq '$machine'")[0].ObjectId
I misplaced the my index ([0]) and placed it after the property, not before it. Then I made sure it outputed a string for good measure, although you can check this with the .gettype() method. Because the on-premise DC and Azure sync, you can use these Device reference IDs interchangeably. It also didnt help outputting a custom error at first, thats what I get for copy-pasting part of someone else's code...

Powershell: Get-AzureADGroupMember doesnt give me the whole list

I want to sync two AzureAD Groups, so I read out both groups with Get-AzureADGroupMember.
The Problem is, I only get 103 People out of the group instead of 615...
What Can I do, to get the whole list out of the groups?
Thanks in advance,
Robin
Yes, you need the -All parameter. Otherwise there is a limitation on the number of members the Get-AzureADGroupMember will return.
For anyone else running into this issue, the command is like this:
(Get-AzureADGroup -Filter "DisplayName eq 'GroupName'" -All $true | Get-AzureADGroupMember -All $true).Count
Alternatively, to store the output in variables for later use:
$AzureADGroup = Get-AzureADGroup -Filter "DisplayName eq 'GroupName'" -All $true
$AzureADUsers = $AzureADGroup | Get-AzureADGroupMember -All $true
$AzureADGroupCount = $AzureADUsers | Measure-Object
See for reference: https://techcommunity.microsoft.com/t5/Azure-Active-Directory/Azure-AD-Dynamic-Groups-Display-Membership-and-count-members/td-p/69657

Example of Get-AzureADUser [-Filter <String>] command

Command: Get-AzureADUser [-Filter ] command
msdn says Parameters
-Filter
Specifies an oData v3.0 filter statement. This parameter controls which objects are returned.
how to set filter to get the same result as Azure module v1 commands
Get-MsolUser -All| Where-Object {$_.isLicensed -eq "True"}| Select-Object UserPrincipalName -ExpandProperty Licenses|Select-Object UserPrincipalName -ExpandProperty ServiceStatus|Where-Object {$_.ProvisioningStatus -eq "Success" -and $_.ServicePlan.ServiceName -like "MCO*"}|select UserPrincipalName -Unique
I have searched all over the place to find a proper example of setting filter but could not and i ended up here.
I am basically trying to convert my Azure module v1 commands to Azure module v2 commands.
A few examples of Get-AzureADUser [Filter] command are as below:
Get-AzureADUser -Filter "DisplayName eq 'Juv Chan'"
Get-AzureADUser -Filter "DisplayName eq 'Juv Chan' and UserType eq 'Member'"
This is following the oData 3.0 Filter semantics as specified here.
Note that the Get-AzureADUser cmdlet is only returning 4 fields:
Object Id, Display Name, UserPrincipalName, UserType
Hence, it is not possible to create an equivalent v2 command using the cmdlet above for your v1 command above.
The version of AzureAD PowerShell v2 module tested for the above is 2.0.0.33.
https://www.powershellgallery.com/packages/AzureAD/2.0.0.33
get-azureaduser -all $true -Filter "startswith(UserPrincipalName,'JohnAdam')"
or use variable
get-azureaduser -all $true -Filter "UserPrincipalName eq '$userPrincipalName'"
This seems to do it
Get-AzureADUser -All $true|select UserPrincipalName -ExpandProperty AssignedPlans|Where-Object {$_.CapabilityStatus -eq "Enabled" -and $_.Service -eq "MicrosoftCommunicationsOnline"} |select UserPrincipalName -Unique

Resources