Powershell - Checking if an Azure AD guest already exists - azure

We have a Powershell script that invites guests in bulk to Azure AD. The email addresses are contained in a CSV file.
It is all working well, but I would like to add functionality to check if the user already exists in the tenant, so that they don't receive a second invitation (it seems you can continue to invite already existing or already invited guests).
For a normal user like bob#company.com, with
$email = "bob#company.com"
I could simply use this:
Get-AzureADUser -ObjectId "$email"
Of course guests are formatted like john_gmail.com#EXT#tenant.onmicrosoft.com. Using that as the ObjectID does indeed work correctly, but of course in the CSV we would see john#gmail.com and so it fails to look up the user.
Is there some sensible way to convert john#email.com to john_gmail.com#EXT#tenant.onmicrosoft.com whilst doing this lookup? It needs to be seen as a normal email address later in the script when it actually invites them.
Thanks

Given that $email = "john#email.com" you can search for "john_gmail.com#EXT#tenant.onmicrosoft.com" like this:
Get-AzureADUser -ObjectId "$($email -replace "#", "_")#EXT##tenant.onmicrosoft.com"
or
Get-AzureADUser -ObjectId ($email.Replace("#","_") + "#EXT##tenant.onmicrosoft.com")
This doesn't change the value of $email while you can still search for the expanded term.

I've realised I can use
$email -replace "#", "_"
To get the output I want. I'll duplicate the variable to avoid causing issues or having to revert it later in the script.

Related

Azure PowerShell :: how to print a list of properties

I found on this post how to print the the Azure Subscription ID:
(Get-AzContext).Subscription.id
But if I look in the official documentation of the command Get-AzContext I don't see anywhere that the .Subscription.id or .id would print that information.
How the guy who replied to that question knew such information?
Where can I find a list of properties for each command?
Commmands like Get-AzContext | fl * or Get-AzContext | gm or get-help Get-AzContext -full don't provide such list.
I want to be able to see all properties provided by commands like Get-AzResource or Get-AzSqlDatabase or any other.
Problably not the cleanest way, but as I use this trick very often and since I shared to some teammates I noticed they are using it now I guess it worths sharing :) .
Use the convertto-json -depth xx (where xx is big enough for your need and depending on the objet's complexity) to get the whole view of an object
Then you can redirect to a file and look for what you need quite easily.
In case you run Get-AzContext | convertto-json -depth 10 you will find back the subscription and the ID.

Powershell script - How can I get this script to only output values that match a certain string

So basically I am current using this script that checks what license is assigned to each account in Azure AD
Connect-MsolService
$Users= Import-CSV C:\Users\Ark\Desktop\powershell\test01.csv
$Users|%{Get-MsolUser -UserPrincipalName $_.UPN|select userPrincipalNAme,#{n="Licenses Type";e={$_.Licenses.AccountSKUid}}}
The csv file that I am ingesting looks like this
|UserPrincipalName|
|:----------------------|
|test.user#test.com |
|test.user2#test.com |
|test.user1#test.com |
With this scripts it goes through and outputs the correct license info for each account, like so
|UserPrincipalName| Licenses Type
|:----------------------|:-------------
|test.user#test.com |testdomain:SPE_E3
|test.user2#test.com |testdomain:SPE_F1
|test.user1#test.com |testdomain:SPE_E3
Where I am stuck at is I would like for this to only output users that only have a specific type of license. For example if I would only want users that have a testdomain:SPE_E3 license assigned. What can I do to edit my script that would only output users for that specific license, like so
|UserPrincipalName| Licenses Type
|:----------------------|:-------------
|test.user#test.com |testdomain:SPE_E3
|test.user1#test.com |testdomain:SPE_E3
Try with the "Where-Object" filter as follows:
Where-Object {($_.licenses).AccountSkuId -match "SPE_E3"}

PowerShell: update O365 AD bulk attributes through csv file

We are trying to bulk update our Azure Active Directory. We have a excel csv list of UserPrincipalNames that we will update the Title, Department, and Office attributes
# Get List of Clinical CMs
$PATH = "C:\Users\cs\Documents\IT Stuff\Project\Azure AD Update\AD-Update-ClinicalCMs-Test.csv"
$CMs = Import-csv $PATH
# Pass CMs into Function
ForEach ($UPN in $CMs) {
# Do AD Update Task Here
Set-Msoluser -UserPrincipalName $UPN -Title "Case Manager" -Department "Clinical" -Office "Virtual"
}
The CSV:
User.1#domain.com
User.2#domain.com
User.3#domain.com
The Set-MsolUser command will work on its own, but it is not working as intended in this For loop. Any help or insight is greatly appreciated
As Jim Xu commented, here my comment as answer.
The input file you show us is not a CSV file, instead, it is a list of UPN values all on a separate line.
To read these values as string array, the easiest thing to is to use Get-Content:
$PATH = "C:\Users\cs\Documents\IT Stuff\Project\Azure AD Update\AD-Update-ClinicalCMs-Test.csv"
$CMs = Get-Content -Path $PATH
Of course, although massive overkill, it can be done using the Import-Csv cmdlet:
$CMs = (Import-Csv -Path $PATH -Header upn).upn

Powershell Search Outlook Email By Title and Extract Most Recent Excel (.xls) File

I am an intern at a testing organisation.
I am trying to automate a very long task and I'm using Powershell to do most of the work.
Task:
We have a corporate email and we receive a LOT of emails during the day. Of course, we have rules set up to make our lives a little more bearable.
Every day there are specific emails being sent to a folder "XYZ" and I want to search for the most recent email using the following criteria:
- Email Title
- Latest Email which contains the search string
Every one of those emails contains an Excel file. If the title of the body matches search criteria, I want to download the latest attachment. Unless there is a way to open and parse the file without downloading it.
I'm super new to Powershell but I have a programming background, so don't be pushed back to simplify yourselves down.
Best regards,
Alex
You'll need to do most of this yourself, but this is code from a similar script I have, i've broken it down to make it a bit more readable, should hopefully get you started.
#Params
$Account = "Mailbox.Searchme#contoso.com"
$Folder = "Inbox"
$SubjMatch = "Reports"
#Create outlook COM object to search folders
$Outlook = New-Object -ComObject Outlook.Application
$OutlookNS = $Outlook.GetNamespace("MAPI")
#Get all emails from specific account and folder
$AllEmails = $OutlookNS.Folders.Item($Account).Folders.Item($Folder).Items
#Filter to emails with attatchments and specific subject line (-match uses RegEx)
$ReportsEmails = $AllEmails | ? { ($_.Subject -match $SubjMatch) -and ($_.Attachements.Count -gt 0) }
#Grab the most recently recieved email
$LatestReportEmail = $ReportsEmails | Sort ReceivedTime | Select -Last 1
#Get the xlsx file(s) and save them
$LatestReportEmail.Attachments | ? {$_.FileName -match "\.xlsx$"} | % {
$_.SaveAsFile("C:\path\to\$($_.FileName)")
}
#Quit Outlook COM Object
$Outlook.Quit()
you should have Outlook closed before you try and run this, also this can be EXTREMELY slow on big folders (mostly the filter part for some reason), good luck.

Trying to Export a CSV list of users using Active Directory Module for Windows Powershell

So the below is where I'm at so far:
import-module activedirectory
$domain = "ourdomain"
Get-ADUser -Filter {enabled -eq $true} -Properties whenCreated,EmailAddress,CanonicalName |
select-object Name,EmailAddress,CanonicalName,whenCreated | export-csv C:\Data\test.csv
Unfortunately, when I run the above I get dates in two different formats in the CSV, e.g.:
01/01/2017
1/01/2017 8:35:56 PM
The issue this poses is that there isn't really a clean way to sort them. Excel's formatting doesn't change either of these formats to be more like the other, both because of the inclusion of time in one and not the other, and because the time-inclusive format doesn't use trailing zeroes in the single digit numbers, but the time-exclusive format does.
We have an existing script that captures users using the LastLogonTimestamp attribute that does this correctly by changing the bottom line to the following:
select-object Name,EmailAddress,CanonicalName,#{Name="Timestamp"; Expression={[DateTime]::FromFileTime($_.whenCreated).ToString('yyyy-MM-dd_hh:mm:ss')}}
For some reason this expression runs properly when we query the LastLogonTimestamp attribute, but when we run this version querying the whenCreated attribute, we get an entirely blank column underneath the Timestamp header.
I'm not particularly knowledgeable about PowerShell itself, and my colleague who had found the original script for the LastLogonTimestamp just found it online and adapted it as minimally as possible to have it work for us, so I don't know if something in this line would work properly with one of these attributes and not the other. It seems strange to me though that two attributes using dates in the same program would store them in different formats though, so I'm not convinced that's it.
In any case, any help anyone can offer to help us get a uniform date format in the output of this script would be greatly appreciated - it needn't have the time included if it's easier to do away with it, though if they're equally easy we may as well keep it.
whencreated is already a [DateTime]. Notice the difference between the properties when you run something like this:
Get-ADUser TestUser -Properties lastlogon,whenCreated | select lastlogon,whenCreated | fl
(Get-ADUser TestUser -Properties lastlogon).lastlogon | gm
(Get-ADUser TestUser -Properties whenCreated).whenCreated | gm
This means that you don't have to convert to a DateTime before running the toString() method.
select-object #{Name="Timestamp"; Expression={$_.whenCreated.ToString('yyyy-MM-dd_hh:mm:ss')}}

Resources