Who Deleted That Azure Resource? Find Out with PowerShell

In short: Azure’s Activity Log records every delete in your subscription. This script pulls out the successful ones and shows who did it, when, and from which IP address.

Hello all! The real-world scenario: you come in on Monday morning, a VM (or a storage account, or a whole resource group) is gone, and the Teams channel is full of “wasn’t me”. You could click through the Activity Log blade in the portal one filter at a time, or you could run this.

The script

#Requires -Modules Az.Accounts, Az.Monitor
param(
    [Parameter(Mandatory)][string]$SubscriptionId,
    [int]$DaysBack = 7     # Activity Log keeps 90 days
)

Connect-AzAccount -Subscription $SubscriptionId | Out-Null

Get-AzActivityLog -StartTime (Get-Date).AddDays(-$DaysBack) -MaxRecord 100000 |
    ForEach-Object {
        # Az.Monitor 5+ uses flat names (OperationNameValue), older versions use OperationName.Value
        $op     = if ($_.OperationNameValue) { $_.OperationNameValue } else { $_.OperationName.Value }
        $status = if ($_.StatusValue) { $_.StatusValue } else { $_.Status.Value }
        $ip     = if ($_.HttpRequestClientIPAddress) { $_.HttpRequestClientIPAddress } else { $_.HttpRequest.ClientIpAddress }

        if ($op -like '*/delete' -and $status -eq 'Succeeded') {
            [pscustomobject]@{
                Time          = $_.EventTimestamp
                Caller        = $_.Caller
                Operation     = $op
                ResourceGroup = $_.ResourceGroupName
                Resource      = ($_.ResourceId -split '/')[-1]
                ClientIP      = $ip
            }
        }
    } |
    Sort-Object Time -Descending |
    Format-Table -AutoSize

Run it like this:

.\Find-AzureDeletes.ps1 -SubscriptionId "00000000-0000-0000-0000-000000000000" -DaysBack 3

Quick explanation

  • Get-AzActivityLog reads the subscription’s Activity Log, which records every create, change and delete made through the portal, PowerShell, the CLI or the API.
  • The filter keeps only operations ending in /delete that succeeded, so failed attempts don’t clutter the results.
  • Caller is the user’s UPN, or an app/managed identity ID if automation did it. That is often the real answer: “it was the cleanup pipeline!”
  • ClientIP tells you whether it came from the office, a VPN or somewhere unexpected.

Good to know

  • The Activity Log only keeps 90 days. If you need longer (and for audits you do), send it to a Log Analytics workspace using the subscription’s Diagnostic settings.
  • Looking for one resource group only? Add -ResourceGroupName rg-name to Get-AzActivityLog.
  • To stop it happening again, put a Delete lock on important resource groups: New-AzResourceLock -LockName NoDelete -LockLevel CanNotDelete -ResourceGroupName rg-prod

Mystery solved, coffee earned. Hope this helps!

Find and Disable Stale AD Accounts with PowerShell

In short: this script finds Active Directory user accounts that nobody has logged into for 90 days, saves them to a CSV report, and only disables them when you add the -Disable switch.

Hello and welcome back! Every AD I have worked on has the same problem: leavers who were never disabled, test accounts from a project three years ago, and service accounts nobody remembers creating. Every one of them is an account an attacker can use, and auditors love to ask about them.

Clicking through Active Directory Users and Computers to find them takes forever, so here is the script I use. It has two safety features: by default it only reports, and it supports -WhatIf so you can see exactly what it would do before it does it.

The script

#Requires -Modules ActiveDirectory
[CmdletBinding(SupportsShouldProcess)]
param(
    [int]$DaysInactive = 90,
    [string]$SearchBase = (Get-ADDomain).DistinguishedName,
    [string]$DisabledOU,            # optional: move disabled accounts here
    [string]$ReportPath = "C:\Temp\StaleAccounts_$(Get-Date -Format yyyyMMdd).csv",
    [switch]$Disable                # without this switch the script only reports
)

$ErrorActionPreference = 'Stop'    # if anything fails (e.g. the report can't be saved), stop before disabling

$cutoff = (Get-Date).AddDays(-$DaysInactive)

$stale = Search-ADAccount -AccountInactive -TimeSpan "$DaysInactive.00:00:00" -UsersOnly -SearchBase $SearchBase |
    Where-Object { $_.Enabled } |
    Get-ADUser -Properties LastLogonDate, WhenCreated, Description |
    Where-Object { $_.WhenCreated -lt $cutoff }   # skip brand new accounts that never logged on yet

# -WhatIf:$false = always write the report, even in -WhatIf mode
$stale | Select-Object Name, SamAccountName, LastLogonDate, WhenCreated, Description, DistinguishedName |
    Export-Csv -Path $ReportPath -NoTypeInformation -WhatIf:$false

Write-Host "$($stale.Count) stale account(s) found. Report: $ReportPath"

if ($Disable) {
    foreach ($user in $stale) {
        $note = "Disabled by stale-account script $(Get-Date -Format yyyy-MM-dd) - last logon $($user.LastLogonDate)"
        if ($user.Description) { $note += " | was: $($user.Description)" }   # keep the old description
        Disable-ADAccount -Identity $user
        Set-ADUser -Identity $user -Description $note
        if ($DisabledOU) {
            Move-ADObject -Identity $user.DistinguishedName -TargetPath $DisabledOU
        }
    }
}

How to use it

Save it as Get-StaleAccounts.ps1 and run it from a machine that has RSAT (the ActiveDirectory module) installed.

  1. Report only (changes nothing):
    .\Get-StaleAccounts.ps1
  2. See what it would do:
    .\Get-StaleAccounts.ps1 -Disable -WhatIf
  3. Do it for real, only in one OU, and move the accounts to a “Disabled Users” OU:
    .\Get-StaleAccounts.ps1 -SearchBase "OU=Staff,DC=contoso,DC=com" -DisabledOU "OU=Disabled Users,DC=contoso,DC=com" -Disable

Quick explanation

  • Search-ADAccount -AccountInactive finds users whose last logon is older than the number of days you give it.
  • It skips accounts that are already disabled, and accounts created in the last 90 days, so a new starter who has not logged in yet is not caught.
  • Every account found goes into the CSV first, so you have a record to send to HR or your manager. The CSV is written even with -WhatIf, and if it can’t be saved the script stops before disabling anything.
  • When it disables an account it writes the date and last logon into the Description field and keeps the old description after it, so the next admin knows why it was disabled and what it was for.

A couple of gotchas

  • LastLogonDate can be up to about 14 days behind. It comes from the lastLogonTimestamp attribute, which only replicates every 9–14 days by default. That is fine for a 90-day check, but do not use this for a 7-day one.
  • Exclude service accounts. Some service accounts never log on interactively. Point -SearchBase at your user OUs rather than the whole domain, or keep service accounts in their own OU.
  • Disable, don’t delete. Leave disabled accounts for 30 days or so before deleting them. Turning an account back on is easy; restoring a deleted one is not.

You can also run this as a scheduled task every month and email the CSV to yourself. More on that in a later post. Hope this helps!

Microsoft Error Lookup Tool


How to Use the Microsoft Error Lookup Tool

The Microsoft Error Lookup Tool is a command-line utility that helps decode Microsoft error codes. It’s straightforward to use and doesn’t require administrative privileges. Here’s a step-by-step guide on how to use it:

Step 1: Download and Install the Tool

  1. Visit the official Microsoft download page and download the tool.
  2. Extract the contents of the downloaded file to a folder of your choice.

Step 2: Open Command Prompt

  1. Open the Command Prompt. You can do this by pressing Win + R, typing cmd, and pressing Enter.

Step 3: Run the Tool

  1. Navigate to the folder where you extracted the tool using the cd command. For example:
   cd C:\path\to\folder
  1. Run the tool with the error code you want to look up The syntax is:
   Err_6.4.5.exe "error code"

Replace "error code" with the actual error code you want to decode.

Example Usage

Here are five examples of how to use the tool with different error codes:

  1. Example 1: Decoding Error Code c000021a
   Err_6.4.5.exe c000021a

Explanation: This error code corresponds to a “STATUS_SYSTEM_PROCESS_TERMINATED” error, indicating a fatal system error.

  1. Example 2: Decoding Error Code 7b
   Err_6.4.5.exe 7b

Explanation: This error code corresponds to an “INACCESSIBLE_BOOT_DEVICE” error, indicating that the system cannot access the boot device.

  1. Example 3: Decoding Error Code 80070002
   Err_6.4.5.exe 80070002

Explanation: This error code corresponds to an “ERROR_FILE_NOT_FOUND” error, indicating that a file or directory could not be found.

  1. Example 4: Decoding Error Code 80070005
   Err_6.4.5.exe 80070005

Explanation: This error code corresponds to an “ERROR_ACCESS_DENIED” error, indicating that access to a resource was denied.

  1. Example 5: Decoding Error Code 80070422
   Err_6.4.5.exe 80070422

Explanation: This error code corresponds to a “WINSVC_STOPPED” error, indicating that a Windows service has stopped.

Conclusion

The Microsoft Error Lookup Tool is a handy utility for diagnosing and understanding error codes on Windows systems. By following the steps above, you can quickly decode error codes and troubleshoot issues more effectively.

Terminate Citrix Session/s via PowerShell

Hello! Once again another PowerShell Code for you to automate quite common task which is done daily on a support engineer perspective.

I use this script pretty much everyday at some point its much easier when you do it via PowerShell, the reason i say this you will have to login to the Citrix Cloud click here and there to find the right place where you need to look for a specific user and then you will need to see how many session he/she has opened and then select the right session. Then you would go into that page and click logoff or disconnect. which is a very mundane task but what we are talking here is about time (TIME IS MONEY).

Imagine now you have to do it for around 20 users, 50 Users, 100 Users and etc.

The Time comes in handy when you have simple script which will save all those time in-fact you can schedule or many other ways to trigger but lets talk about that later now. let me show you how does this script looks. Before that you need make the initial connect to the Citrix Cloud click here to learn how to.

Enough is said here you go:

Set-XDCredentials -ProfileType CloudApi -StoreAs default -CustomerId "customerID" -SecureClientFile C:\Temp\secureclient.csv

$users = get-content -path "C:\Users\Fazul\Download\names.txt"

foreach($user in $users){
$samuser = $user.accountname

$output = "D:\Citrix_termination\Termination_$samuser.txt"

 Get-BrokerSession -UserName "Domain\$samuser" -Filter { DesktopGroupName -like 'UK-W10*'} | select UserName,machinename,DesktopGroupName,EstablishmentTime

    if($results -ne $null){
            foreach($result in $results){

                (Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " -> Active Session Found - " + $result.UserName+ " | "+$result.MachineName+ " | "+$result.DesktopGroupName+ " | "+$result.EstablishmentTime >> $output
                
		try{ 
		Get-BrokerSession -UserName "lseg\$samuser" -Filter { DesktopGroupName -like 'UK-W10*'} -ErrorAction stop #| Stop-BrokerSession 
		}catch{ 
		(Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " -> " + $samuser + " Citrix Session unable to terminate!!!">> $output 
		}

                (Get-Date -Format "yyyy-MM-dd HH:mm:ss") + " -> " + $samuser + " Citrix Session test terminated!!!">> $output
            }
}
}

Quick Explanation on the function of the script above.

The script starts by setting some credentials for a cloud API, and then retrieves a list of user names from a file called “names.txt” located in a folder called “Download” on the user’s computer.

For each user in the list, the script searches for any active sessions for that user on a Citrix server. If an active session is found, the script attempts to terminate it. If the termination is successful, a message is written to a log file indicating that the session was terminated. If the termination fails for any reason, an error message is written to the log file instead.

The log file is created in a folder called “Citrix_termination” located on the user’s computer. The log file name includes the user’s account name as part of the file name.

Overall, the script automates the task of searching for and terminating active sessions on a Citrix server for a list of users, and provides a log file to keep track of the termination attempts.

Hope this Helps, Have a great friday.

Microsoft Designer!!

Welcome back to another blog, this time its not about Powershell. Its about Microsoft Designer. Why am talking about this?

Thanks Microsoft for allowing the preview of Microsoft Designer.

In my point of view this is great tool for content creation who ever wants to start content creating but struggling to create images or graphics content or already started, this tool could help both.

There is a limited set of users who are given access to Microsoft Designer from a join list. my request was approved and given Preview access to the tool. which is incredible.

Microsoft is heavily focusing on AI integrating with most of the there exisitng products and services like ChatGPT with bing, Azure AI Platform and AI based design tool much more to come.

Enought of my chatter lets me show what Microsoft Desinger is.

Microsoft Designer

In the Above image you can see how straight forward is the Microsoft Designer is all you have to do let the designer know what time of image or graphics content are you looking for.. to put things into prespective i will show you some capabilities of this tool below or in other words messing with the tool to see what it can do.

Result from Microsoft Designer

Just like that the Image is ready on the side panel, let do another one to see how deep can it go.


Lets actually create a Poster

I am going to create a poster using the Microsoft Designer. Lets do it…

have asked the Designer Copilot to generate a empty road with motivational qoute its given the me lots of templates i have chosen the once marked on the image above. lets edit it to the way i need it.

This a quick result of what i did in less than a minute. when it comes to productivity this tool is going to help a lot of people who are trying to get into content writing, infographs, posters and lots more, the tool also show recommendation let me show another one which is comletly made using the content i have passed on to this image.

I Mean look at this image above simple and to the point on what i need to express. I am barely scratching the surface here on this tool. will try to create something sooner using full functionality of this tool.

From a desingers prespective this tool would help millions.

Until Next time see ya….

Retrieve Current Admin in Citrix Cloud

Hello and welcome again, its been a while since I wrote a blog post. Obviously been busy with other stuff, Enough of my stuffs lets get into the title.

let’s start with a small and nice script, One of my colleague asked me to let him know how many Admin users are there in the Citrix cloud.

Obviously for monthly account audits. Before getting into the script do the pre-requisites Click here (How to connect to Citrix cloud )

Lets get into the code now.

Add-PSSnapin citrix.*

Get-AdminAdministrator -MaxRecordCount 9999 | select Name,Enabled,rights 

Here comes the explanations: Starting with the adding the PS-Snapins, which loads the Citrix commands into the Powershell for you to use.

Now comes the Killer one line: Get-AdminAdministrator. This command will get you all the necessary information shown below. The MaxRecordCount is to display all I went with 9999 the default is 249.

From the above we can just filter the information that will make use decision much quicker, Will pipe the result and select the requires fields shows in the script above.

result of the script

Hopefully this small and quick blog post helped someone. Until next time.

Compare 2 Files for Difference

Hi All, welcome back to another Blog. I was approached by an subscriber today who is a beginer to Powershell made an awesome script which user compare-object function to compare to files. which was great start in powershell. Like i say to get to know something you need to get started. Applause to him.

The requirement was to compare 2 files to find difference, obviously there are more than one way to find difference the below script is one of those ways.

$PreFile = import-csv -LiteralPath "D:\YooAdmin\PreProcess.csv" 
$PostFile = import-csv -LiteralPath "D:\YooAdmin\PostProcess.csv"
$forHTML = @()

foreach($pline in $PostFile){
    foreach($line in $PreFile){
        if($pline -ne $line){
            $pline | export-csv -Path D:\YooAdmin\report.csv -Append -Force -NoTypeInformation
            $forHTML += $pline
            break
        }
    }
}

$forHTML | ConvertTo-Html | Out-File -FilePath D:\YooAdmin\report.html

In Summary: there are 2 file PreProcess and PostProcess both CSV
Both data in the CSV is loaded into variables and an Array to load the result for creating an html report as requested by my subscriber.

Then we get in to Loops, where you can basically check 2 file classed as array to compare.
The first loop will load the files that will be check against to see if there is any difference we call is reference and the next one is difference file.

if the a result in first loop is not equal to the result in second loop. then export that line to a CSV and add it to the Global Array, once that is done we break the loop to end it.

after completion of the loops the global varible had collected all the fields and ready to export as Export to HTML.

it’s a quick script for me but for someone who is starting with powershell this could be a milestone and moment of getting way deeper and better than me in powershell.

All the Best.

here is the result on html showing on the difference.

result from script above

Manage Citrix Cloud via PowerShell

Welcome to another blog on Citrix and PowerShell. Today we will see how to manage Citrix Cloud via PowerShell. Before getting started please refer to the previous blog if you need to know how to setup the Citrix PowerShell.

Simply Click here (Getting Started with Citrix Cloud via PowerShell).

Let see how to do few things from PowerShell on Citrix Cloud like Getting Sessions details

Get-BrokerSession

Above command will get all of the session that is made to the Citrix Cloud including App session and Desktop session. Below is result of a session details, Obviously I have to hide sensitive details.

get-brokersession result

There are lots of information in Get-BrokerSession where you can select the only fields you need which will make more sense and easy by simply using the below example command for selecting username, sessionstate, establishmenttime, appstate

get-brokersession | select  username,sessionstate,establishmenttime,appstate
Result of the above command

The AppState that Says Active are the Application instance, highlighted to make a not of it.

Now you know how to get data for BrokerSession let me show you what else you can do with it. based on the information we have we can see sessionsate is disconnected. Imagine you have 1000 of disconnected session on floating VDI on the weekend you need to Stop brokering from Citrix Cloud. You can easily write a PowerShell command as below to achieve it.

get-brokersession -Filter {Sessionstate -eq 'Disconnected'} | Stop-BrokerSession

This will get it done rather you logging into the Citrix Cloud and searching for machines that are disconnected and select all to Stop it. this one liner will help you save time where you can set it to run weekly simply, that’s the power of PowerShell.

There are 274 Broker based PowerShell Command, Image the power of the PowerShell combined with Citrix. The Commands from Citrix here

You can basically manage and Automate 95% Admin work with the PowerShell. I have barely scratched the surface with this blog on managing Citrix from PowerShell

Do let me know if there is any specific commands in Citrix Cloud you need to write about or build an automation.

Have a Nice day.

Getting Started with Citrix Cloud via Powershell

Hello, Welcome to another blog of mine, Today will look at how to manage Citrix via PowerShell. You can do some extraordinary tasks via PowerShell paired with Citrix Cloud.

Prerequisites: Citrix PowerShell SDK Install the SDK for the relevant version of Citrix XenDesktop environment. Once the installation done we can now start writing our commands and scrip to manage Citrix XenDesktop.

It’s straightforward installation as you can see below:

EULA
Components that are to be installed.

Once you click Install

Components Installed.

Hooray, we have installed Citrix XenApp & XenDesktop SDK, Now first thing you need to do is to add the PS Snap in for Citrix in PowerShell, |The below command will add the Citrix snap in for us to use.

Add-PSSNappin citrix*

Now check if the Citrix Snap-ins are added correctly using the below command.

Get-PSSnapin -name *Citrix*

You can now see that Citrix Snap ins are added to PowerShell successfully.

All good, lets start with the authentication before we start any commands, we should enter the below line. The easiest and the best way according to me is to leverage the CloudAPI in Citrix. You will need to create a Secure Client for Citrix Cloud APIs by logging into Citrix Cloud Console.

After creating Secure Client

You will get a ID and Key which you can download and use it for authentication for the below command.

Set-XDCredentials -CustomerID "You Customer ID" -SecureClientFile "You File Location" -proFileType CloudAPI -storeas Default

This command will authenticate you via Citrix Cloud API on you powershell Session.
Will catch you guys with Managing Citrix Xendesktop via Powershell on the next blog.

Import P12 Certificate

Heyyy… It’s been a while since i wrote a script, completely been busy with lots of other stuff. Anyways enough of my stuff lets get into the script and how this came as a request.

I had a colleague who asked me if i can get a cert deployed to wide range of workstations. I took this chance to write this quick script to deploy it via SCCM.

Import-Pfxcertificate -FilePath "Path of the Certificate" -Password "Password if required" -CertStoreLocation "Cert:\LocalMachine\Root"

The Script is very simple as you can see it requires 2 or 3 (if password is needed to import the Cert) Switches.

-FilePath = where the Cert is located easy way to get it. Locate the Cert and do a Shift + Right click and Copy as a path.
-Password = Some Certs will be password protected (Infact mostly on a Corp environment.) what is did instead of passing the test as it is i created a SecureString Variable as shown below. Which came in handy incase of changing the password for another cert while using the same Script.
-CertStoreLocation = This is where you want to place the Cert.

Click Here to see Microsoft’s Documentation – https://docs.microsoft.com/en-us/powershell/module/pki/import-pfxcertificate?view=windowsserver2019-ps

$pwd = 'Password' | convertto-securestring -asplainText -Force

This $Pwd Variable now can be used across the script rather than using the actual password everywhere in the script.