Query ObjectId of ConditionalAccessLocationCondition - azure

I am writing a script to write to Azure, I basically want to find a user, create a network location, create a conditional access policy. This is what I have so far. The trouble is that the $secmon_guid and $location_policy_guid do not work. If I manually put the values in, it works.
# Run these commands first to connect and install without the #
Install-Module -Name AzureAD -AllowClobber -Force # Answer Y to install NuGet. Run once on workstation running script.
Install-Module -Name Microsoft.Graph.Identity.SignIns -Force # Install this to allow us to setup a trusted location. Run once on workstation running script.
Install-Module MSOnline -Force #Allow us to edit users. Run once on workstation running script.
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine #Set execution policy to allow our script to do things.
Import-Module -Name AzureAD #The following 3 commands are ran for each client.
Connect-AzureAD # Use GA credentials from Glue
Connect-MsolService #Reauthenticate if necessary.
Get-AzureADMSConditionalAccessPolicy #This will list out all of the existing CA policies. This is a good opportunity to get them into documentation.
Connect-MgGraph #This enabled graph, you will need to approve the request in the popup window.
#Set variable for account name
Set-Variable -name "account" -Value "secmon"
#Create named location for the IP address
$ipRanges = New-Object -TypeName Microsoft.Open.MSGraph.Model.IpRange
$ipRanges.cidrAddress = "IP ADDR"
New-AzureADMSNamedLocationPolicy -OdataType "#microsoft.graph.ipNamedLocation" -DisplayName "Blackpoint IP Address for SecMon" -IsTrusted $true -IpRanges $ipRanges
#Disable MFA for secmon
Get-MsolUser -SearchString "secmon" | Set-MsolUser -StrongAuthenticationRequirements #()
#Get the Azure AD GUID for use later
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select ObjectID
#Name the policy
$name = "Allow Secmon Only from Blackpoint IP"
#Enable the policy. Set to Disabled to test.
$state = "Enabled"
#Get location GUID and save to variable
$location_policy_guid = Get-AzureADMSNamedLocationPolicy | Where-Object -Property DisplayName -Contains 'Blackpoint IP Address for SecMon' | Select-Object -Property Id
#Working on this
#Create the overarching condition set for CA, this is the container.
$conditions = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessConditionSet
#Include all applications - This might be able to be removed?
$conditions.Applications = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessApplicationCondition
$conditions.Applications.IncludeApplications = 'All'
#Create the user condition and include secmon
$conditions.Users = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessUserCondition
$conditions.Users.IncludeUsers = $secmon_guid
#Add new location policy to CA policy
$conditions.Locations = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessLocationCondition
$conditions.Locations.IncludeLocations = $location_policy_guid
#Grant access control to CA policy
$controls = New-Object -TypeName Microsoft.Open.MSGraph.Model.ConditionalAccessGrantControls
$controls._Operator = "OR"
$controls.BuiltInControls = "block"
#End work
New-AzureADMSConditionalAccessPolicy `
-DisplayName $name `
-State $state `
-Conditions $conditions `
-GrantControls $controls
The error I get is due to poorly formatted GUID's, the values I am pulling are not correct. How can I fix this? Any help is greatly appreciated!
New-AzureADMSConditionalAccessPolicy : Error occurred while executing NewAzureADMSConditionalAccessPolicy
Code: BadRequest
Message: 1054: Invalid location value: #{Id=1234GUID}.
InnerError:
RequestId: 5678GUID

Where you define the variables, you need to use -ExpandProperty on the select-object statement e.g:
$secmon_guid = Get-MsolUser -SearchString "secmon" | Select -ExpandProperty ObjectID
Otherwise, you would have to access your current variable like so:
$conditions.Users.IncludeUsers = $secmon_guid.ObjectID

Related

Get device owner from Azure Active Directory group members

Is there a simple way to get the owners of all devices that are assigned to a particular group? I have a Azure AD group that has devices assigned to it and I would like to change all of the assignments from device to user. Is there a way I can find out the owner of the device and assign them as a member in bulk?
You can use the below Powershell Script to get the the device owners of the devices present in the group.
Connect-AzureAD
$Result=#()
$Members = Get-AzureADGroupMember -ObjectId "b446d49b-****-****-****-************"
foreach ($Member in $Members) {
$DeviceOwner = $Member|Get-AzureADDeviceRegisteredOwner
$deviceprops = [ordered] #{
DeviceDisplayName = $Member.DisplayName
DeviceObjectID = $Member.ObjectId
OwnerDisplayName = $DeviceOwner.DisplayName
OwnerUserPrincipalName = $DeviceOwner.UserPrincipalName
OwnerObjectID = $DeviceOwner.ObjectId
}
$deviceobj = new-object -Type PSObject -Property $deviceprops
$Result += $deviceobj
}
$Result
$Result | Export-CSV "C:\DeviceOwners.csv"
I have tested the above on my environment I have only devices present in a group.
Output:
Then to Add owners to the group you can import the csv and add the owners to the Group and then similarly remove the Devices from Group. I tested it only for GetADUser as I don’t want to do the changes in my AAD group.
Code:
$Owners = Import-Csv -Path "C:\DeviceOwners.csv"
#$Owners|Format-Table
Connect-AzureAD
$Owners | ForEach-Object {
#$Owner = $_
#Get-AzureADUser -ObjectId $Owner.OwnerObjectID
$Owner = $_
Add-AzureADGroupMember -ObjectId "b446d49b-****-****-****-************" -RefObjectId $Owner.OwnerObjectID
#$Owner = $_
#Remove-AzureADGroupMember -ObjectId "b446d49b-****-****-****-************" -MemberId $Owner.DeviceObjectID
}
Note :
First Add the Owners to the Group . While running the above script to add Owners to Group keep the Remove command commented . After you have added the Owners to the Group then you can comment the Add command and use the Remove command to remove the Devices from the Group.
Reference:
Install Powersell azuread module :
Command: Install-Module -Name AzureAD
AzureAD Group Module | Microsoft Docs

How to check if the Powershell cmdlet Get-AzKeyVaultSecret supports -AsPlainText parameter?

With the following command I am able to retrieve a list (or is it a dictionary? My Powershell knowledge is unfortunately very limited) of parameters supported by the Get-AzKeyVaultSecret cmdlet:
PS C:\> $params = (Get-Command Get-AzKeyVaultSecret).ParameterSets | Select -ExpandProperty Parameters
PS C:\> $params | ForEach {$_.Name}
VaultName
Name
InRemovedState
DefaultProfile
Verbose
Debug
ErrorAction
WarningAction
InformationAction
...
How could I please check if the list contains the AsPlainText parameter, which was added in the newer versions of the cmdlet?
In my custom script I would like to check for that and then adapt the way I retrieve a secret value from a key vault:
if ($is_AsPlainText_Supported) # how to set this variable?
{
$mySecret = Get-AzKeyVaultSecret -VaultName 'MyKeyVault' -Name 'MySecret' -AsPlainText
}
else
{
$mySecret = (Get-AzKeyVaultSecret -VaultName 'MyKeyVault' -Name 'MySecret').SecretValueText
}
I would prefer not to use try/catchhere (or check if retrieved secret value is null), because I have numerous Get-AzKeyVaultSecret calls in my real script and such approaches would cost performance.
Add this line before your if statement:
$is_AsPlainText_Supported = (Get-Command Get-AzKeyVaultSecret).ParameterSets.Parameters.Name -contains "AsPlainText"
The -contains operator will return a boolean based on if the list before the operator contains the item after it.

How to set value of -DefaultProfile (of type IAzureContextContainer) in New-AzSqlSyncMember

I am trying to create a powershell script to create azure data sync between 2 azure SQL databases.
My member database is on another subscription.
I need to set -DefaultProfile which is of type on 'New-AzSqlSyncMember' command.
I am not aware of the syntax for setting this parameter.
My current script without -DefaultProfile looks like below:
New-AzSqlSyncMember -ResourceGroupName $resourceGroupName `
-ServerName $serverName `
-DatabaseName $databaseName `
-SyncGroupName $syncGroupName `
-Name $syncMemberName `
-MemberDatabaseType $memberDatabaseType `
-SyncDirection $syncDirection
I want to set the value of the subscription field using powershell like in the image below using powershell:
Possible cross post from https://social.msdn.microsoft.com/Forums/en-US/4ad3dd3e-314a-4442-957f-da77c17ef85b/how-to-set-value-of-defaultprofile-of-type-iazurecontextcontainer-in-newazsqlsyncmember?forum=azurescripting&prof=required
You want to call Connect-AzAccount with the credentials for the account you want to use in the -DefaultProfile parameter and store that in a variable. You can use that variable to set the parameter:
$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId
New-AzSqlSyncMember <params> -DefaultContext $DefaultProfile
If this throws a type error that it can't convert from a PSAzureContext to a IAzureContextContainer there is an explicit converter available.
$DefaultProfile = Connect-AzAccount <params> -SubscriptionId $SubscriptionId
$Converter = New-Object -TypeName Microsoft.Azure.Commands.Profile.Models.AzureContextConverter
$Container = $converter.ConvertFrom($DefaultProfile, [Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer], $null, $true)
New-AzSqlSyncMember <params> -DefaultContext $Container

How do I translate a set of powershell commands into a script that I can run when I want?

I have a set of commands I can use in azure powershell. The commands create a resource group, app service, etc. I want to bundle them up so that I can just type one command into a terminal and run all of the deployment in one go.
# Ask user for work item id
$workItemId = Read-Host -Prompt "Enter the Work Item ID"
# Set Variables
$appdirectory="C:\Users\Charles\Desktop\Timesheet App\Discover\Client\build"
$webappname="discoverTest$workItemId"
$location="West Europe"
# Create a resource group.
New-AzResourceGroup -Name discoverTest$workItemId -Location $location
# Create an App Service plan in `Free` tier.
New-AzAppServicePlan -Name $webappname -Location $location `
-ResourceGroupName discoverTest$workItemId -Tier Free
# Create a web app.
New-AzWebApp -Name $webappname -Location $location -AppServicePlan $webappname `
-ResourceGroupName discoverTest$workItemId
# Get publishing profile for the web app
$xml = [xml](Get-AzWebAppPublishingProfile -Name $webappname `
-ResourceGroupName discoverTest$workItemId `
-OutputFile null)
# Extract connection information from publishing profile
$username = $xml.SelectNodes("//publishProfile[#publishMethod=`"FTP`"]/#userName").value
$password = $xml.SelectNodes("//publishProfile[#publishMethod=`"FTP`"]/#userPWD").value
$url = $xml.SelectNodes("//publishProfile[#publishMethod=`"FTP`"]/#publishUrl").value
# Upload files recursively
Set-Location $appdirectory
$webclient = New-Object -TypeName System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$files = Get-ChildItem -Path $appdirectory -Recurse #Removed IsContainer condition
foreach ($file in $files)
{
$relativepath = (Resolve-Path -Path $file.FullName -Relative).Replace(".\", "").Replace('\', '/')
$uri = New-Object System.Uri("$url/$relativepath")
if($file.PSIsContainer)
{
$uri.AbsolutePath + "is Directory"
$ftprequest = [System.Net.FtpWebRequest]::Create($uri);
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::MakeDirectory
$ftprequest.UseBinary = $true
$ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password)
$response = $ftprequest.GetResponse();
$response.StatusDescription
continue
}
"Uploading to " + $uri.AbsoluteUri + " from "+ $file.FullName
$webclient.UploadFile($uri, $file.FullName)
}
$webclient.Dispose()
$workItemId = Read-Host -Prompt "Enter the Work Item ID"
Remove-AzResourceGroup -Name "discoverTest$workItemId" -Force
# print variable
Write-Host $variable
I want to be able to run a single command and have the full deployment process executed.
There are two ways to realize your needs, as below.
Extract all parameters you used in these PowerShell command lines as the arguments for a PowerShell Script <your-script-name>.ps1 which includes all same commands as yours. Please refer to the existing SO thread How to handle command-line arguments in PowerShell to know how to do. Then, you just need to run <your-script-name>.ps1 with these arguments in a terminal which had pre-installed Azure PowerShell Module.
Follow the blog Four ways to package a non-GUI PowerShell script as an executable file to make an executable file with the current set of commands.
Normally, I think the first way is better and be recommended.

Office 365 - how to manage many users

I have 200 unsorted users in office 365. I want to find an easy way to manage who they are and what security group each user belongs to.
Is there an easy way to export username and what groups each user belongs to?
Iam quite new to poweshell...
But i want to export a CSV file with user and gruops.
Is this possible?
Or do you recommend any other way to quick get an overview of all users and what grups they belong to.
Some users need to be in multiple groups and i suspect some users are missing in groups they should be in..
Thanks for any tips i can get.
################################################################################################################################################################
# Script accepts 2 parameters from the command line
#
# Office365Username - Optional - Administrator login ID for the tenant we are querying
# Office365Password - Optional - Administrator login password for the tenant we are querying
#
#
# To run the script
#
# .\Get-DistributionGroupMembers.ps1 [-Office365Username admin#xxxxxx.onmicrosoft.com] [-Office365Password Password123]
#
#
# Author: Alan Byrne
# Version: 2.0
# Last Modified Date: 16/08/2014
# Last Modified By: Alan Byrne alan#cogmotive.com
################################################################################################################################################################
#Accept input parameters
Param(
[Parameter(Position=0, Mandatory=$false, ValueFromPipeline=$true)]
[string] $Office365Username,
[Parameter(Position=1, Mandatory=$false, ValueFromPipeline=$true)]
[string] $Office365Password
)
#Constant Variables
$OutputFile = "DistributionGroupMembers.csv" #The CSV Output file that is created, change for your purposes
$arrDLMembers = #{}
#Remove all existing Powershell sessions
Get-PSSession | Remove-PSSession
#Did they provide creds? If not, ask them for it.
if (([string]::IsNullOrEmpty($Office365Username) -eq $false) -and ([string]::IsNullOrEmpty($Office365Password) -eq $false))
{
$SecureOffice365Password = ConvertTo-SecureString -AsPlainText $Office365Password -Force
#Build credentials object
$Office365Credentials = New-Object System.Management.Automation.PSCredential $Office365Username, $SecureOffice365Password
}
else
{
#Build credentials object
$Office365Credentials = Get-Credential
}
#Create remote Powershell session
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $Office365credentials -Authentication Basic –AllowRedirection
#Import the session
Import-PSSession $Session -AllowClobber | Out-Null
#Prepare Output file with headers
Out-File -FilePath $OutputFile -InputObject "Distribution Group DisplayName,Distribution Group Email,Member DisplayName, Member Email, Member Type" -Encoding UTF8
#Get all Distribution Groups from Office 365
$objDistributionGroups = Get-DistributionGroup -ResultSize Unlimited
#Iterate through all groups, one at a time
Foreach ($objDistributionGroup in $objDistributionGroups)
{
write-host "Processing $($objDistributionGroup.DisplayName)..."
#Get members of this group
$objDGMembers = Get-DistributionGroupMember -Identity $($objDistributionGroup.PrimarySmtpAddress)
write-host "Found $($objDGMembers.Count) members..."
#Iterate through each member
Foreach ($objMember in $objDGMembers)
{
Out-File -FilePath $OutputFile -InputObject "$($objDistributionGroup.DisplayName),$($objDistributionGroup.PrimarySMTPAddress),$($objMember.DisplayName),$($objMember.PrimarySMTPAddress),$($objMember.RecipientType)" -Encoding UTF8 -append
write-host "`t$($objDistributionGroup.DisplayName),$($objDistributionGroup.PrimarySMTPAddress),$($objMember.DisplayName),$($objMember.PrimarySMTPAddress),$($objMember.RecipientType)"
}
}
#Clean up session
Get-PSSession | Remove-PSSession

Resources