Archive for the ‘Scripts’ Category

If You need to get members of particular Azure AD role use below script:


#get all groups
Get-AzureADDirectoryRole | select displayname

$role = Get-AzureADDirectoryRole | Where-Object {$_.displayName -eq 'Company Administrator'}

Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId | Get-AzureADUser | select displayname,user
principalname | Export-Csv "C:\Users\lap-top\Downloads\1.csv" -NoType


  • If a file is deleted in source, remove it from destination as well.
  • If a file is deleted form destination, do not remove from source.
  • if a file is already in source and destination do not do anything
  • if a file is on source but not destination, copy to destination
robocopy "\\source" "destination" /r:60 /w:5 /PURGE /MIR /MT:64

r:60 – retry 60 times

w:5 wait 5 seconds between retries

/PURGE: delete from destination if file is not in source

/MIR MIRror a directory tree

/Z : copy files in restartable mode

If we use /Z (restartable mode) the transfer bandwidth is about 4 to 6Mbps.

If  we take off the /Z switch, it goes between 80-120Mbs

and we need to add /MT:64

/MT[:n] :: Do multi-threaded copies with n threads (default 8).

This way the “file in use” error should be eliminated since Robocopy will have enough time between the scheduled run times to copy even the largest files ~6GB

lThis script performs following:


import boto3
import collections
import datetime
import time
import sys 

ec = boto3.client('ec2', 'eu-west-1')
ec2 = boto3.resource('ec2', 'eu-west-1')
from datetime import datetime
from dateutil.relativedelta import relativedelta

#create date variables 

date_after_month = relativedelta(days=7)

def lambda_handler(event, context):
  #Get instances with Owner Taggs and values Unknown/known
    instance_ids = []
    reservations = ec.describe_instances().get('Reservations', []) 

    for reservation in reservations:
     for instance in reservation['Instances']:
        tags = {}
        for tag in instance['Tags']:
            tags[tag['Key']] = tag['Value']
        if not 'Owner' in tags or tags['Owner']=='unknown' or tags['Owner']=='Unknown':

                #Check if "TerminateOn" tag exists:

              if 'TerminateOn' in tags:
                  #compare TerminteOn value with current date
                    if tags["TerminateOn"]==today:

                    #Check if termination protection is enabled
                     terminate_protection=ec.describe_instance_attribute(InstanceId =instance['InstanceId'] ,Attribute = 'disableApiTermination')
                     #if enabled disable it
                     if protection_value == True:
                        ec.modify_instance_attribute(InstanceId=instance['InstanceId'],Attribute="disableApiTermination",Value= "False" )
                    #terminate instance
                     print "terminated" + str(instance_ids)
                     #send email that instance is terminated

                    #Send an email to engineering that this instance will be removed X amount of days (calculate the date based on today's date and the termination date."

                      TerminateOn = datetime.strptime(future, "%d/%m/%Y")
                      days= (TerminateOn-now).days
                      print str(instance_ids) +  " will be removed in "+ str(days) + " days"

                 if not 'TerminateOn' in tags:#, create it

                  print "was shut down "+format(','.join(instance_ids))

In one of previous posts we created JIRA subtasks using REST API, in this example we’ll see how to create new JIRA task with Epic link,label, assignee and reporter


curl -D- -u user:pass -X POST --data "{\"fields\":{\"labels\":[\"SERVICES\"],\"assignee\":{\"name\":\"emergencyadmin\"},\"reporter\":{\"name\":\"user\"},\"project\":{\"key\":\"AA\"},\"summary\":\"Create user account in Local AD.\",\"description\":\"Create user account in Local AD.\",\"issuetype\":{\"name\":\"Managed Service\"},\"customfield_10107\":{\"id\":\"10505\"},\"customfield_10006\":{\"CP-3289\"}}}" -H "Content-Type:application/json"

customfield_10006-epic link
customfield_10107-client account




import sys
import json
import re
import requests
import subprocess
import os
import urllib2
import argparse

import datetime
from dateutil.relativedelta import *

one_month_ago = – relativedelta(months=1)

previous_month = one_month_ago.strftime(“%B”)

currentYear =

password = str(sys.argv[1])

headers = {“Content-Type”: “application/json”}
data = {“fields”:{“labels”:[“SERVICES”],”reporter”:{“name”:”user”},”assignee”:{“name”:”emergencyadmin”},”project”:{“key”:”AA”},”summary”:”SPLA usage report for {previous_month} {currentYear}”.format(**locals()),”description”:”Review SPLA usage report”,”issuetype”:{“name”:”Managed Service”},”customfield_10107″:{“id”:”10505″},”customfield_10006″:”CP-3289″}}
response =“”,
headers=headers, data=json.dumps(data), auth=(‘user’, password))

Set-AzureRmContext -SubscriptionId "subscriptionid"

$accountKeys = Get-AzureRmStorageAccountKey -ResourceGroupName "test" -Name "mystorageaccount201806"

#The Storage Context object itself is what enables us to authenticate to the Azure Storage REST API from PowerShell.

$storageContext = New-AzureStorageContext -StorageAccountName "mystorageaccount201806" -StorageAccountKey $accountKeys[0].Value

#SAS key expiry time

$expiryTime = (get-date).AddYears(1)

#set perimissions:r-readmw-write-l-list

$permission = "rwl"

#Create policy

New-AzureStorageContainerStoredAccessPolicy -Context $storageContext -Container "test" -Policy "test" -ExpiryTime $expiryTime -Permission $permission

#Get token

$sasToken = New-AzureStorageContainerSASToken -Name "test" -Policy "test" -Context $storageContext
$sasToken = $sasToken.substring(1)

#Write-Host "SAS token (ref shared access policy): $sasToken"

$sasToken2 = New-AzureStorageContainerSASToken -Context $storageContext -Container tibp-userprofiles -Permission rwl
#Write-Host 'SAS token: ' $($sasToken2)



Azure Information Protection (sometimes referred to as AIP) is a cloud-based solution that helps an organization to classify, label, and protect its documents and emails. This can be done automatically by administrators who define rules and conditions, manually by users, or a combination where users are given recommendations.

Install-Module aadrm

#connect to the Azure Rights Management Service



Connect-AadrmService -Credential $cred

#Activate the service



#get the configuration information needed for message encryption

$rmsconfig = get-aadrmconfiguration

$licenseuri = $rmsconfig.LicensingExtranetDistributionPointUrl

#disconnect from service



#create a remote powershell session and connect to exchange online

$session = New-PSSession -ConfigurationName -ConnectionUri -Credential $cred -Authentication basic

Import-PSSession $session


#collect IRM configuration for Office 365



if (!$list) {$list=@()}

if (!$list.contains($licenseuri)) {$list+=$licenseuri}


#Enable message encryption for Office 365

set-irmconfiguration -licensinglocation $list

set-irmconfiguration -AzureRMSLicensingEnabled $true -InternalLicensingEnabled $true

set-irmconfiguration -SimplifiedClientAccessEnabled $true


#Enable server decryption for Outlook on the web,Outlook for iOS and Outlook for Android

Set-IRMConfiguration -ClientAccessServerEnabled $true


#Test connecttion

Test-IRMConfiguration -Sender


When composing new mail click Protect-Change permission



Choose option for handling message






Set Native App ID  (see section Native applications) in Microsoft partner center.

From Microsoft Partner Center you can manage your customers, offers, subscriptions, usage, etc.

Install Partner center Powershell module

Install-Module -Name PartnerCenterModule

If you’ll run this report at regular basis encrypt credentials:

#partner center credentials

$password = "somepass"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPwd | ConvertFrom-SecureString
Set-Content "C:\temp\ExportedPassword.txt" $secureStringText


#email (office365) credentials

$password = "somepass"
$secureStringPwd = $password | ConvertTo-SecureString -AsPlainText -Force
$secureStringText = $secureStringPwd | ConvertFrom-SecureString
Set-Content "C:\temp\mail.txt" $secureStringText

Following code will get license usage

#Partner center credentials

$username = ""
$pwdTxt = Get-Content "C:\temp\ExportedPassword.txt"
$securePwd = $pwdTxt | ConvertTo-SecureString


#email credentials

$mailuser = ""
$pwdmail = Get-Content "C:\temp\mail.txt"
$securemailPwd = $pwdmail | ConvertTo-SecureString


# Variables
$cspdomain = ""
$appid = "1223-scdd-ddadadad-11221211"
$PCcreds = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePwd
$EmailCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $mailuser, $securemailPwd
$From = ""
$To = ""
$SmtpServer = ""
$Subject = "Partner Center Licensing: "

# Build email parameters
$EmailParameters = @{
from = $From
To = $To
SmtpServer = $SmtpServer
Port = 587
UseSsl = $true
BodyAsHtml = $true
Credential = $EmailCreds

# Authentication
Add-PCAuthentication -cspAppID $appid -credential $PCcreds -cspdomain $cspdomain

# Get customers
$Customers = Get-PCCustomer -all

# For each customer
foreach ($Customer in $Customers) {
$CustomerReport = Get-PCCustomerLicensesDeployment -tenantid $ 2> Out-Null

# If there is a customer licence report
if ($CustomerReport){

# Return specific headings
$CustomerReport = $CustomerReport | Select-Object productName,licensesDeployed,deploymentPercent,licensesSold

# Create customer specific variable
$CustomerSubject = $Subject+$Customer.companyprofile.companyName

# Create Body HTML string
$CustomerBody = $CustomerReport | ConvertTo-Html | Out-String

# Send message
Send-Mailmessage `
-Subject $CustomerSubject `
-Body $CustomerBody `


If we have multiple customers, for each of them email will be generated