TechOnTip Weblog

Run book for Technocrats

Archive for the ‘Powershell’ Category

Powershell Scripts, Tips

Azure Web App & SSL Certificate Reporting using Powershell

Posted by Brajesh Panda on February 18, 2019

Here you go… download from here.

Still using AzureRM Module. But can be easily converted to Az Module

# Retrieve Azure Web App and Azure Certificate Details.
# Helps to find out which Web Apps are enabled for TLS 1.0 or 1.1 so they can be moved to 1.2
# Helps to find out few other info like if HttpsOnly is enabled, Tags, Cert Thumbprint and Expiry date
# Generates CSV files

#Select-AzureRmSubscription -Subscription "test"

# Pick all subscriptions except Azure AD
$AllSubscription = Get-AzureRmSubscription | ?{$ -inotlike "*Azure Active Directory"}

# Few empty arrays
$AllSSLCerts = @()
$AllWebApps = @()

# Retrieve required info from each subscription
foreach($Subscription in $AllSubscription)
    $null = Select-AzureRmSubscription -SubscriptionId $Subscription.ID

    # Web App SSL Certificates
    $WebAppCerts = Get-AzureRmWebAppCertificate 
    $AllWebAppCerts =  $WebAppCerts | select @{n="SubscriptionName";e={$Subscription.Name}}, FriendlyName, IssueDate, ExpirationDate, `
                                                         Thumbprint, SubjectName,Location, Issuer, @{n="ResourceType";e={$_.Type}}
    # Get Azure Web Apps
    $WebApps = Get-AzureRmWebApp

    # Retreive all Key Value paris from Tags & put them into new attributes i.e. Tag-'Key
    $AllKyes = @()
    foreach($item in $WebApps)
            $AllKyes += $item.Tags.Keys
    $SelectedKeys = $AllKyes | select -Unique | ?{$_ -notlike "hidden*"}
    foreach($key in $SelectedKeys)
            $TagAttribute = "Tag-"+$key
            $WebApps | Add-Member -MemberType NoteProperty -Name $TagAttribute -Value '' -Force

            foreach($item in $WebApps)
                    $Object  = New-Object PSObject -Property $item.tags
                    $item.$TagAttribute = $Object.$key

    # Select Specific Attributes from web apps
    $WebAppsDetails = $WebApps| select @{n="SubscriptionName";e={$Subscription.Name}}, Name, State, Enabled, ResourceGroup, Location, DefaultHostName, Tag-*, httpsOnly, `
                            #@{n="httpsOnly";e={(Get-AzureRmResource -ResourceGroupName $_.ResourceGroup  -ResourceType Microsoft.Web/sites -ResourceName $ -ApiVersion 2016-08-01).Properties.httpsOnly}},`    
                            @{n="minTLSVersion";e={(Get-AzureRmResource -ResourceGroupName $_.ResourceGroup  -ResourceType Microsoft.Web/sites/config -ResourceName $ -ApiVersion 2016-08-01).Properties.minTLSVersion}},`
                            @{n="CertName";e={(Get-AzureRmWebAppSSLBinding -WebAppName $_.Name -ResourceGroupName $_.ResourceGroup).Name}}, `
                            @{n="Thumbprint";e={(Get-AzureRmWebAppSSLBinding -WebAppName $_.Name -ResourceGroupName $_.ResourceGroup).Thumbprint}}, `
                            SubjectName,ExpirationDate, Issuer

    # find out ExpiryDate, SubjectNames, Issuer Name
    foreach($WebApp in $WebAppsDetails)
            $Cert = $AllWebAppCerts |?{$_.Thumbprint -eq $WebApp.Thumbprint}
            $WebApp.ExpirationDate = $cert.ExpirationDate
            $WebApp.SubjectName = $cert.SubjectName
            $WebApp.Issuer = $cert.Issuer

    $AllSSLCerts += $AllWebAppCerts | sort expirationdate
    $AllWebApps += $WebAppsDetails
    Remove-Variable -Name AllWebAppCerts
    Remove-Variable -Name WebAppsDetails
    Remove-Variable -Name WebAppCerts
    Remove-Variable -Name WebApps
$AllSSLCerts | Export-Clixml C:\Scripts\AllSSLCerts2.xml
$AllWebApps | Export-Clixml C:\Scripts\AllWebApps2.xml

$AllSSLCerts | Export-Csv C:\Scripts\AllSSLCerts2.csv -NoTypeInformation
$AllWebApps | Export-Csv C:\Scripts\AllWebApps2.csv -NoTypeInformation

Posted in Powershell | Leave a Comment »

Search Multiple Files using Select-String

Posted by Brajesh Panda on November 28, 2017

Get-ChildItem -recurse | Select-String -pattern "blah blah" | Select-Object path ,line,linenumber,filename | Export-Csv -Path C:\Garbage\search-logs.csv -NoTypeInformation

Posted in Powershell | Leave a Comment »

Powershell Tip: Date Formatting ISO 8601

Posted by Brajesh Panda on October 10, 2016

Convert current date to ISO 8601 format (like 2016-10-10T16:35:48.477):  Get-Date -format s

Convert ISO 8601 format to Powershell’s date time format:  [datetime]::Parse($date). where $date has the ISO 8601 input.  Here is the reference to one of my old post which converts user input to powershell’s DateTime format.

Here are two other interesting articles.



Posted in Powershell | Leave a Comment »

Azure Backup Reporting

Posted by Brajesh Panda on August 10, 2016

In the absence of any good reporting mechanism for Azure Backup Agents, I have created this one for my work. We just start backing up some branch file servers to Azure and that number will go up. So for now it is okay, will see what improvements I can do to this. If you have an idea please suggest or implement and send me a copy 😉

Download from here.

# Base Script
# Added Recovery Points
# Convert UTC times to server's local time

# Add all of your servers computer accouts to a group called Azure_Backup_reporting
$AzureBackupAgents = Get-ADGroupMember Azure_Backup_Reporting | select Name

$Consolidated = @()

foreach($Node in $AzureBackupAgents)
 $Agent = $Node.Name
 # Select last 10 Azure Backup Jobs from the remote server
 $AgentReports = Invoke-Command -ComputerName $Agent -ScriptBlock `
 # Find time (ticks) offset between Local and UTC. 
 $Date = Get-Date;
 $UTC = $Date.ToUniversalTime();
 $OffSet = $Date – $UTC;
 # Find last 10 job details
 Get-OBJob -Previous 10 | select Jobtype, `
 @{Name="StartTime"; Expression ={($_.JobStatus.StartTime).AddTicks($OffSet.Ticks)}}, `
 @{Name="EndTime"; Expression ={($_.JobStatus.EndTime).AddTicks($OffSet.Ticks)}}, `
 @{Name="JobState"; Expression ={$_.JobStatus.JobState}}, `
 @{Name="BackupSizeInGB"; Expression ={($_.JobStatus.DatasourceStatus.ByteProgress.Progress / 1GB).ToString('#.##')}}, `
 @{Name="TotalSizeInGB"; Expression ={($_.JobStatus.DatasourceStatus.ByteProgress.Total / 1GB).ToString('#.##')}}, `
 @{Name="FailedFileLog"; Expression ={$_.JobStatus.FailedFileLog}}
 # Filter & Select last 24 hours logs 
 $Day = (Get-Date).AddHours(-24)
 $Filtered = $AgentReports | where{$_.StartTime -gt $Day} | Sort StartTime -Descending | Select @{Name="AgentName"; Expression ={$_.PSComputerName}}, JobType, StartTime, Endtime, JobState, BackupSizeInGB, TotalSizeInGB, FailedFileLog
 ($Filtered | Measure-Object).Count
 $Consolidated += $Filtered
$Node = $null

# Recovery Point Details
$Consolidated | Add-Member -MemberType NoteProperty TotalRPs ''
$Consolidated | Add-Member -MemberType NoteProperty OldestRP ''
$Consolidated | Add-Member -MemberType NoteProperty LatestRP ''

foreach($Node in $Consolidated)
 $RecoveryPoints = Invoke-Command -ComputerName $Node.AgentName -ScriptBlock `
 Get-OBAllRecoveryPoints | Sort-Object backuptime
 $Node.TotalRPs = ($RecoveryPoints | Measure-Object).Count
 $Node.OldestRP = $RecoveryPoints[0].BackupTime
 $Node.LatestRP = $RecoveryPoints[-1].BackupTime

 # HTML Formating; Styles to be placed in the header
 $a = "<style>"
 $a = $a + "BODY{font-family: Verdana, Arial, Helvetica, sans-serif;font-size:10;font-color: #000000}"
 $a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
 $a = $a + "TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color: #E8E8E8}"
 $a = $a + "TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black}"
 $a = $a + "</style>"

 # Mail Alert
 $MailSubject = "Consolidated Azure Backup Report for Last 24hrs"
 $MailBody = $Consolidated | Select AgentName,JobType,StartTime,EndTime,JobState,BackupSizeInGB,TotalSizeInGB,TotalRPs,OldestRP,LatestRP,FailedFileLog | ConvertTo-Html -Head $a

 # Mailout the Report
 $smtpServer = ""
 $msg = new-object Net.Mail.MailMessage
 $smtp = new-object Net.Mail.SmtpClient($smtpServer)

 $msg.From = ""
 $msg.Subject = $MailSubject
 $msg.Body = $MailBody

Email Output looks like below;

azuer backup

Posted in Azure, Powershell | 4 Comments »

Powershell Trick: Execute Logon Script as per Group Membership

Posted by Brajesh Panda on May 22, 2016

If((Get-ADPrincipalGroupMembership $env:username).name -like “Domain Users”)

{Write-Host “Yes”}

Change the Write-Host section with the action script, what you want to execute. I think this is what you want.

Here $env:username gets the logged on user name. It is like “whoami” command, without the domain info. You can get domain info using $env:USERDNSDOMAIN

Posted in Mix & Match, Powershell | Tagged: | Leave a Comment »

Powershell Trick: Convert TXT to HTML and Send Email

Posted by Brajesh Panda on May 17, 2016

If you want to get contents from a txt file and send its content in email body, this trick will do the job. My txt file has multiple separate lines, like general error files.

So this trick joins all lines with <BR> HTML encode to introduce line breaks. If you do not use this encode and just do get-content, all lines will be messed like a paragraph and will be hard to read.

$Body = (Get-Content <File Path>) -join ‘<BR>’

After you encode the html, make sure use BodyAsHtml to set outgoing email format. So email client will convert html page back to readable format.

Send-MailMessage -From <> -To <> -Subject <Message> -Body $Body -BodyAsHtml -SmtpServer smtp.server

Posted in Mix & Match, Powershell | Tagged: | Leave a Comment »

Powershell Trick: Capture Valid IP

Posted by Brajesh Panda on April 30, 2016

[ipaddress]$ipaddress = Read-Host “Type valid ip”

Posted in Mix & Match, Powershell | Tagged: | Leave a Comment »

Powershell – Get AD Forest Details

Posted by Brajesh Panda on March 30, 2016

Get AD Forest Details…

$Forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest() | select -expandproperty domains

$Forest | Add-Member -MemberType NoteProperty DCs ”

$forest | ForEach-Object {$PSitem.DCs = ($PSItem | select -ExpandProperty DomainControllers) -join ‘,’}


Like Domains, sites can be expanded for more details etc. So I am going to work on this and expand the same to get more details… Thank you Jason Heisley for motivating me to learn ADSI .Net Namespaces 😉

Posted in Mix & Match, Powershell | Tagged: | Leave a Comment »

Service Now REST API and PowerShell

Posted by Brajesh Panda on March 28, 2016

Disclaimer… Neither am I a software developer nor a Service Now Guru. In the absence of our service now dev guy, I just got some time to play around with my powershell stuff. Just out of curiosity trying to learn how to work with REST API using Powershell.

Latest service now instances (starting with Eureka release) supports REST API. More info can be found here

There are tons of REST client resources in programming languages & dev guys understand them better. But as an infrastructure professional, without much of Dev knowledge, I play around with Powershell & bit with Chrome’s REST Extension. So “Invoke-RestMethod” cmdlet is my friend here. Note, Powershell 3.0 and above support this. I use latest one… 5.0 ;-). Just learned a new app from, These GUI tools are kind of cool to understand different parameters.

1. So Service Now REST API can be connected using two methods;

a. With Normal User ID & Password. Means every time you query, you need to send out both user ID & password for authentication. Although it goes thru HTTPS, it is little bit too much when you are doing all these stateless queries.

b. With Token based authentication. Starting with Service now’s Fuji release we can use Access Token to do all these queries. And this Access Token expires after certain time (default 30mins), then we can use another token called as Refresh Token with a fixed Client ID (like a weird string user name) & Client secret (like a complex password) to regenerate the Access Token.

2. Let’s see the powershell codes for 1(a) method.

# Query Incident Table and get maximum numbers of ticket

$URI = ‘’

# OR Query Incident Table and get one ticket using sysparm query

# $URI = ‘https://’

$SNowUser = “DomainUser” # If integrated with ADFS or any SAML Identity Source for SSO

$SNowPass = ConvertTo-SecureString –String “Password” –AsPlainText -Force

$SNowCreds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $SNowUser, $SNowPass

$Incidents = Invoke-RestMethod -Uri $URI -Credential $SNowCreds -Body $Body -ContentType "application/json"



3. For 1(b) method, you have to enable OAuth 2.0 thru service now portal. Here are the steps;

4. You may have to give yourself security admin role. I think I have that access in our Dev instance. I am going to figure that out later. As it is not my current priority, I have not checked those details.

5. Here is a screenshot. I created a new one for my Powershell Scripts.

In Service Now – Search “system oauth” – click on “application registry” – Click “new” – Select “Create an Oauth api endpoint for external clients” – configure necessary things..

6. Keep Client ID & Client Secret in a safe place. You may like to change Refresh token and access token time period as per our requirement.

7. Here is a nice video presentation from service now team using getpostman app. This one demonstrate how to generate refresh token & access token. And then how to use access token to retrieve data. But I am going to give you few line of Powershell codes here…

# Get Refresh token and Access Token using below script

$username = “DomainUsername”

$password = “Password”

$ClientID = “Paste Client ID from Step 6”

$ClientSecret = “Paste Client Secret from Step 6”

# Query REST Endpoint

$RestEndpoint = ‘’

$body = [System.Text.Encoding]::UTF8.GetBytes(‘grant_type=password&username=’+$username+’&password=’+$password+’&client_id=’+$ClientID+’&client_secret=’+$ClientSecret)

Invoke-RestMethod -Uri $RestEndpoint -Body $Body -ContentType ‘application/x-www-form-urlencoded’ -Method Post

8. Output will be somewhat like below..

scope : useraccount

token_type : Bearer

expires_in : 1800

refresh_token : jsdfkajd;ewiorqjkfmsdkfamdfi;qirjqwkvm,c vkoejpmfklsdmfpiopioqijekmfd,kj7381893409mkas

access_token : sdnfok34u59834mdkfmaoiei4u398mlak;smr9i43uumaslkjripp98q347ja;k3ju409932mf;lkaj493q883

9. Now let’s use the access_token to retrieve data. We need to pass access_token thru headers as authorization. Do not forget that Bearer word to append before the access token.

# Query Incident Table and get maximum numbers of ticket

$URI = ‘’

# OR Query Incident Table and get one ticket using sysparm query

# $URI = ‘https://’

$headers = @{“authorization” = “Bearer sdnfok34u59834mdkfmaoiei4u398mlak;smr9i43uumaslkjripp98q347ja;k3ju409932mf;lkaj493q883”}

$result = Invoke-RestMethod -Uri $URI -Headers $headers

10. After 1800 seconds, the access_token will expire and we need a new one. We can use the step 7 or below codes with the existing refresh_token, client id & secret to get a new access_token.

# Get Access Token using Refresh Token.

$Refreshtoken = "jsdfkajd;ewiorqjkfmsdkfamdfi;qirjqwkvm,c vkoejpmfklsdmfpiopioqijekmfd,kj7381893409mkas"

$ClientID = “Paste Client ID from Step 6”

$ClientSecret = “Paste Client Secret from Step 6”

# Query REST Endpoint

$RestEndpoint = ‘’

$body = [System.Text.Encoding]::UTF8.GetBytes(‘grant_type=refresh_token&client_id=’+$ClientID+’&client_secret=’+$ClientSecret+’&refresh_token=’+$refreshtoken)

Invoke-RestMethod -Uri $RestEndpoint -Body $Body -ContentType ‘application/x-www-form-urlencoded’ -Method Post

11. Output will be kind of same as step 8, with a different access_token. Then repeat step 9 using new access token.

Posted in Mix & Match, Powershell | Tagged: , , | 1 Comment »

Application of Active Directory Snapshot feature

Posted by Brajesh Panda on March 21, 2016

Posted in Active Directory User Management, BackupExec 2010, BackupExec2010R3, Mix & Match, Powershell | Tagged: | Leave a Comment »

Skype for Business Online: Dial-In Conferencing Reporting

Posted by Brajesh Panda on January 25, 2016

Here is my tiny script to report all user level Dial-In Conferencing details from Skype for Business Online Tenant. Useful if you have integrated InterCall, Pgi etc.

# Connect to SfB Online


# Dial In Users

$DialInUsers = Get-CsOnlineUser -Filter {AcpInfo -ne $null} -ResultSize Unlimited | select FirstName, LastName, DisplayName, UserPrincipalName, SIPAddress, HostingProvider, Office, CountryAbbreviation, CountryOrRegionDisplayName, ACPInfo

# Add Properties

$DialInUsers | Add-Member -MemberType NoteProperty TollNumber ”

$DialInUsers | Add-Member -MemberType NoteProperty TollFreeNumber ”

$DialInUsers | Add-Member -MemberType NoteProperty PassCode ”

$DialInUsers | Add-Member -MemberType NoteProperty Provider ”

$DialInUsers | Add-Member -MemberType NoteProperty Domain ”

# Populate Attributes

foreach($DialInUser in $DialInUsers)



[xml]$DialInInfo = $DialInUser.AcpInfo

$DialInUser.TollNumber = $DialInInfo.acpInformation.tollNumber

$DialInUser.TollFreeNumber = $DialInInfo.acpInformation.tollFreeNumber

$DialInUser.PassCode = $DialInInfo.acpInformation.participantPassCode

$DialInUser.Provider = $

$DialInUser.Domain = $DialInInfo.acpInformation.domain

#[xml]$DialInInfo = $null


$FilteredData = $DialInUsers | `

select FirstName, LastName, DisplayName, UserPrincipalName, SIPAddress, HostingProvider,Office,CountryAbbreviation,CountryOrRegionDisplayName,TollNumber,TollFreeNumber,PassCode,Provider,Domain

$$FilteredData | Export-Csv C:\Script\InterCallUsers_Report.csv -NoTypeInformation

Posted in Mix & Match, Powershell | Tagged: , , | Leave a Comment »

Dell Hardware Info thru Powershell

Posted by Brajesh Panda on November 13, 2015

Posted in Dell OEM, Mix & Match, Powershell | Tagged: | Leave a Comment »

Windows Storage Performance Measurement with DiskSPD

Posted by Brajesh Panda on May 5, 2015



Posted in Mix & Match, Powershell | Tagged: | Leave a Comment »

Powershell: Networking Commands

Posted by Brajesh Panda on April 22, 2015

My favorites

1. Test-NetConnection -ComputerName | Select -ExpandProperty PingReplyDetails | fl


3. Resolve-DnsName -Server -Type MX

Posted in Mix & Match, Powershell | Tagged: | Leave a Comment »

Get Public IP using Powershell

Posted by Brajesh Panda on April 3, 2015

Invoke-WebRequest -URI

Invoke-WebRequest -URI

Invoke-WebRequest -URI

Invoke-RestMethod -URI

Invoke-RestMethod -URI

Invoke-RestMethod -URI

Posted in Mix & Match, Powershell | Tagged: | Leave a Comment »

%d bloggers like this: