Last month, I had an app that had some issues for a single end user. I wasn’t sure why it was causing issues, but one of the troubleshooting steps we needed to do was uninstall it and have Intune reinstall it. We uninstalled the application. However, Intune, being Intune, sat there. We forced a sync, and nothing. I wish there was a redeploy option in the Intune interface, but there isn’t. So what can you do? Well, there is a small secret. Intune has registry keys that keep track of the deployments on the machine itself. These linger even after uninstalling the app. So, removing them is the gravey. So today we are going to force Intune apps to redeploy.
Intune Registry Keys / App ID Number
Intune’s registry keys are located in the Local Machine > Software > Microsoft > IntuneManagementExtension > Win32App. Let me tell you what now. My southern is going to come out some yall. This is where we can see the users. The system has it’s own user, which is the all zeros, but each other user has it’s own code.
When you open this folder, you will be taken to a beautiful list of what? Yeah, it’s a mess. You need to know some things about this list in order to force intune apps to redeploy. You will need to have the app’s ID number. To get this number, you will need to navigate to your Intune. We will be heading to the app you want to uninstall. I’m doing my 7zip today as an example. At the end of the url, you will see the appID. That’s what you will need.
Once you have that code, you will be ready. What you will need to do now is delete the folder with that code. Then navigate to the GRS folder. It will have a bunch of hashes. No, not the drug, but math code. Wait, is hash still what people call it now days? I feel old. Anyway, you have two options here. One, you can go to the logs and search the logs for the hash. This can take a while, and shockingly, it is not reliable as logs get deleted. The other way is to go through this registry folder, folder by folder, until you find the key, as seen below. I prefer PowerShell. Once you delete the required registry keys, all you have to do is restart the Microsoft Intune Management Extension service.
Powershell To the Rescue
If you have read this blog long enough, you know PowerShell is coming somehow. Today’s script will save you a crap ton of time. Let’s dive right in.
There are many versions online for this script. Most use the logs, and that’s cool. This script doesn’t use the logs, and for a good cause. In my case, the logs were deleted. Why were they deleted, you shall ask? Humans, that’s always going to be my answer until it’s AI.
The break down
Let’s break this bad boy down, shall we? The first part of the script is the path we are going to be playing with, followed by the code of the app. You will have to grab this from your intune.
Next, we want to grab all the users. So, remember I said the system uses all zeros. Well, we want to exclude those. However, users use the hypens. It’s the Fantastic 4, hypens, not the Marvel characters. Using a basic where object, we sort through all of the ones that have our hypens and are not the system and drop their ID numbers into the users variable.
Now we start our loop. Everyone should like a good loop. Each user will have it’s own path. The first thing we run into is that the above command gave us HKEY_Local_Machine instead of a searchable HKLM. So we change them using the replace. Then we grab the userID for later. Finally, we grab all the applications. Notice the name is the new name we made. It’s important to have the HKLM: because without it, you will get an error with get-childitem. No candy was stolen from any children while writing this blog post.
Notice we are looking for the appid at the end. Sometimes, there will be more than one entry like this. To force Intune apps to redeploy, we must remove all of them. I liken them to bed bugs. Burn them all. With that said, we start our loop. For each App inside the applications. We will get the app name and then remove it. Once again, we used get-childitem. Goodness, I need to stop still items from kids. So we need to convert the name like we did before changing the HKEY_Local_machine to HKLM: with a nice replace. Once we have it, we delete the path and everything inside by force.
Now we need to handle the GRS side. The GRS keeps the datetime stamps. Like I said before, most people use the logs. Today we will navigate through the registry. The first thing we are going to do is set the path and get the kids on that path. This is where the UserID we made at the start of this big loop comes into play.
Now we have the children’s items. We start our looping. The first thing we get is our GRS properties with the get-itemproperty commands. Now here is the magic. A standard check has only 1 or maybe 2 items inside the folder. While more advanced items will have more than that. So, if we convert the properties into a Powershell object, we can count them.
Yes, the second line works. You can pretty much convert anything into a PowerShell object. All we have to do now is count how many counts per object are there. When we convert the item property into a powershell object, we gain a few extra items. So, anything past 5 in this case will be our special stuff. So, if it is past 5, we get to work.
We first look at the keys, looking for our fantastic 4. We will do this by calling the psobject.properties.name because it will be the name of the property. Then we will compare it to the appid. If they are the same, we correct the hkey_local_machine and drop our nuke, remove-item. Nested ifs are fun, but can get complex quick if you don’t watch out.
After the large loop of Fantastic Four, we have to restart the intune extension. So, using get service, we pipe it into restart service. Then we are done! Right? Well, kind of.
After the script has done it’s thing and stolen candy for kids and nuked stuff, you will need to resync the computer. You can do this via the Accounts setting, or you can do this via Intune. In my case, the application we were redeploying was our remote application. So, I had to do it via Intune.
Navigate to the device under Windows > Device Name and hit the sync button. Now you are done. Force Intune apps to redeploy, check.
What can we learn as a person?
Restarting is sometimes the only option. Taking a step back, clearing things away, and starting new is good, whether you’re troubleshooting an Intune app deployment or dealing with a hard time in life.
When an app in Intune stops working, we don’t just sit around and hope it gets fixed (at least for a while). After we empty the registry and do some troubleshooting, we gently push it to redeploy. Life is no different. When things don’t work out the way you expected, that’s okay; setbacks are inevitable. Starting over equalizes the situation; it’s not a sign of surrender.
Restarts, in reality, are chances for growth. By doing so, they demonstrate our flexibility, competence, determination and insight to put things right. Our fantasic four. When something feels stuck, whether it’s an app or your thinking, don’t be scared to reset. Do not be afraid, especially with our thinking. That’s where real change happens.
Recently, I was playing with Intune devices using graph API and managed devices. I was able to search for things like the device name with no issues, but when it came to the unique codes, I started having beautiful dyslexia issues. As I struggled, I asked myself how I could search this whole PowerShell object all at once, every value and every index. The first thought was to go property by property with a switch. But I asked myself, How can I reuse this function later? Let’s Search PowerShell Objects together.
The concept is that we feed the script the ps object we want to search in. This function will search the top level. Searching recursively is dangerous for weaker machines, but it’s fully doable with the above function. It’s time to break down this function.
Parameters
First, we want to look at the parameters. We need the Powershell object, then the string, and finally a nice little flag to give us more information. We are requiring the object and the search are both required because that’s what we need. The expand isn’t because we may not need everything.
The Search PowerShell Object Loop
This step is the meat and potato of the function. Here is how we are going to search the full object. We start off by looping the object. We want to use a foreach-object loop because of the beginning and simplicity of it all.
The foreach-object is treated like a function in some context. We have a beginning, process and ending flags. So we begin the loop with our index of zero. We do this to keep track of the index of the powershell object we are analizing. The process is where we begin.
The next step is to open the door of the PSobject. Once we crack the door we select the Properties information and start another loop through that.
$_.PSObject.Properties | ForEach-Object {}
This is where we can now search each object inside the object. At this point we are looking at a properity of an object that has been opened that is inside the main object. Confused yet, that’s ok. We are at the end of that trail. Next, we need to ask if the value of the current property is our search string. If it’s true, then we send back a ps object.
if ($_.Value -like "*$SearchString*") {
[pscustomobject][ordered]@{
Index = $index
PropertyName = $_.Name
Value = $_.Value
}
}
Objects making objects, we are so in the .net work for sure.
What’s cool at this is the ps object is being returned to the Results. Finally, we do an index increase by using the index++.
$index++
Expanding
Now we have searched the powershell object, lets expand it. The code above grabs the index number. So we want to expand upon that. If you trigger the flag “Expand” we want to grab all the index number. First we take the results from the above and group them by group-object. We select the property of index. This will give us all of the options in a nice pretty package. So we then select the names. This will give us all the indexes for each item that was found and not multiple of the same. I
From there we start a for each loop. Here we display the objects index. We do this by having the main object with [#]. If expanding isn’t set, we just display the results.
Since this function does one level, you can use another powershell script that will search each level if it has an object. The only problem with this is, processing power. Powershell is not designed to be database software. So it’s best not to deep dive into an object like that.
What can we learn as a person?
It’s ok to find other solutions. Doing it the hard way only adds stress. But there is a point where you can spend more time automating than doing the work itself. So keep it balanced. You deserve that. Just like we search PowerShell objects, we should search for different ways to keep the balance in our life.
Ever found yourself tangled in the web of Exchange Online mailbox rules? Yeah, me too. It’s like trying to find a needle in a haystack, especially if you’re managing multiple mailboxes. Thankfully, I stumbled upon a nifty PowerShell script that makes this task a breeze. Let’s Get Mailbox Rules Using PowerShell.
Let’s Talk About Our Script
Before we jump into the script, let’s understand what it does. The PowerShell script Get-RASMailboxRules helps you retrieve mailbox rules for specific email addresses in Exchange Online. Whether you’re an IT admin juggling a dozen tasks or just someone who likes things neat and tidy, this script can save you a ton of time.
Breaking Down the Script
Here’s the full script for reference:
function Get-RASMailboxRules {
[cmdletbinding()]
param (
[Parameter(
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True,
HelpMessage = "Email Addresses",
Mandatory = $true)][Alias('Mailbox','EmailAddress')][String[]]$Mailboxes
)
begin {
# Checks if Exchange Online is connected
if ($null -eq (Get-ConnectionInformation)) {Connect-ExchangeOnline}
# Pulls all mailboxes from the $Mailboxes parameter and checks if they exist
$Boxes = @()
foreach ($box in $mailboxes) {
Try {
$Boxes += Get-Mailbox $box
} catch {
Write-Error "Error getting mailbox"
}
}
}
process {
foreach ($mailbox in $Boxes) {
$Rules = Get-InboxRule -Mailbox $mailbox.Name
foreach ($Rule in $Rules) {
$ruleDescription = $Rule.Description -join "`n"
$Description = (($ruleDescription -split 'If the message:')[1] -split 'Take the following actions:')
$ifMessage = ($Description[0].Trim() -replace "`t", "") -replace "\s*`n", ""
$actions = ($Description[1].Trim() -replace "`t", "") -replace "\s*`n", ""
[PSCustomObject]@{
MailboxName = $Mailbox.Name
Mailbox = $Mailbox.UserPrincipalName
RuleName = $Rule.Name
Enabled = $Rule.Enabled
ID = $Rule.RuleIdentity
IfMessage = $ifMessage
Actions = $actions
}
}
}
}
end {
Disconnect-ExchangeOnline -Confirm:$false
}
}
What’s Happening Here?
Let’s break it down:
Parameters and Initialization:
The script takes email addresses as input through the $Mailboxes parameter.
It checks if Exchange Online is connected. If not, it connects using Connect-ExchangeOnline.
Fetching Mailboxes:
It loops through the provided mailboxes and tries to fetch their details using Get-Mailbox.
Any errors encountered during this process are caught and reported.
Processing Mailbox Rules:
For each mailbox, it retrieves the inbox rules using Get-InboxRule.
It parses the rules to extract the conditions (IfMessage) and actions (Actions).
Output:
It creates a custom PowerShell object for each rule, which includes details like mailbox name, rule name, enabled status, and more.
Finally, it disconnects from Exchange Online to clean up.
Key Points to Remember
Mandatory Parameter: The script requires at least one email address to be provided.
Error Handling: It gracefully handles errors when fetching mailbox details.
Custom Output: The output is a clean, readable list of mailbox rules with all the necessary details.
Wrapping up “Get Mailbox Rules using PowerShell”
And there you have it! A super handy PowerShell script to get mailbox rules using PowerShell in order. It’s efficient, straightforward, and takes the hassle out of managing mailbox rules. So next time you’re knee-deep in inbox rules, you know which script to pull out.
Happy scripting, folks! If you run into any issues or have questions, drop them in the comments below. Let’s keep the conversation going!
Last week we went over how to do audits using PowerShell (Link). Today we will use scheduled tasks with PowerShell to have the audit script run hour by hour. We do this because we don’t want to be manually running the PowerShell script every hour. Let the computer handle all of that for us. We will go over how to manually build the Scheduled Task and the PowerShell way.
Manual Process – Scheduled Tasks
Lets take a look at the manual process. We are placing our AuditDisabledAccounts.ps1 script on the computer. I like placing things in the c:\scripts or c:\temp folder. Sometimes this is good, sometimes this is bad. It depends on the world you are working in.
Start Task Scheduler
Click Task Scheduler Library.
Right Click and select basic task
Name it accordingly. I am naming mine “Hourly Disabled AD Audit.”
Under Triggers, I selected When the computer starts.
This scheduled task will repeat itself with another setting. It’s best to get it started when the computer starts. This way if the system restarts, it will start again. It can become confusing over time.
Now we have a basic scheduled task setup. Next we want to have it trigger every hour. Sense we opened the properites you can now do just this.
On the general tab
Radio check: “Run whether the user is logged on or not.”
If you need to change the user, this is where you will do that.
Click the Triggers tab.
You will see at startup, click edit
Under advanced Settings
Check Repeat task every
Select 1 hour
Duration: Indefinitely
Click ok
That’s how you manually setup a Scheduled Task for PowerShell.
Powershell Method
Now we can do a Scheduled Tasks with PowerShell. We will be using the scheduledtask commands to create the task accordingly. Lets take a look at the script itself.
The first thing we do is setup. We want to have the script, the name, the out file for our audit report, our servers, and the hours back we want to go.
The first thing we want is the veriables. We want the path of the script. We want it’s name. Where our CSV files will be dropped, the servers, how many hours back, usernames and passwords. Notice that the User is using a read-host and creds is using a secure string. This is to help stop shoulder surfers and powershell memory. This way you password isn’t passed around. Basicly, we input the password as a secure string, and it becomes a veraible. Thus, if someone is looking through the powershell history, or is monitoring it with something like defender, then they will not see the password. Only the veraible from this point on.
Decoding Passwords as Veriables
Part of the Scheduled Tasks with PowerShell is we need to register the task later. This means that the password needs to be plain text. However, we don’t want a password to ever exist in the shell visability. So we want to decode it directly into a Veriable.
The code above allows you to convert the secure string to normal text in Powershell 5. If you are using powershell 7, this isn’t a problem. But most servers are still defaulting at 5. The new veriable name is UnsecurePassword which has the password as plain text for the register command.
Triggers – Scheduled Task for powershell
We need to start making the triggers. Unlike the gui, we can’t setup a startup with a hourly repeat. Instead, the safeist way is to do an hourly thing for repeating the hour. We do this using the new-scheduledtasktrigger command.
Since we have 24 hours in a day, we want to repeate a foreach-object loop 24 times. We start at 0 and go to 23 which makes 24. Wow… Anyways, As we loop, the $_ will be the number. So we create a new trigger at that time and set it to daily. All of this will be dumped into the $triggers array.
Principal
Next we want to setup a user account. The command for this is…. Yep, you guessed it, New-ScheduledTaskPrincipal. Here we are setting the ID to the author, using our user flag, doing the logontype as password, and the runlevel is limited. We don’t want it to have full access to anything since it’s not doing anything on the local PC. Notice the ` symbol. This allows you to do mulitlple lines with one command. It’s like break here and continue to the next line. It makes reading code so much easier.
Next we need to do our actions. AKA, what’s it going to do. Using the New-scheduledTaskAction we want to execute with powershell and push our arguments in. Using our Veriables, we fill in the blanks. It’s very straight forward. The secret sause here is the arguments will be like you did with the gui approach.
Next we need to make the task itself. We are going to use the New-ScheduledTask command. This part of the command creates a task object that will need to be registered. We give it the description we want. The Actions from above. The user inside the principal names and the triggers we built out.
Finally, we want to register the task in question. We are going to use “Register-scheduledTask” to do this. Notice that this is where we are using that password we used at the start. It’s used as a variable, and thus it’s never shown in the PowerShell history.
Additional Thoughts on Scheduled Tasks with PowerShell
This technique is very powerful. I built out a script that scanned the local network via Get-NetNeighbor. The script was a scheduled task and it grabbed all the devices. Imagine having admin rights, pushing out a script that scans the local network drops a scheduled task on another computer that scans that network. You could map out a whole network within a few minutes. This could be used as a worm and it’s a good reason to block WMI on the network except from the machines that does the administration.
What can we learn as a person?
It’s always a good idea to have routine. Having a Scheduled task in your life that you like tends to improve our lives. For example, I like going to a monthly meetup with my friends. It’s something I look forward to. Having it on my calendar helps. This is why vacations are important. We need to have those things on our calendar. It’s ok to have them on the calendar. So, find something you can look forward to, and put it on the calendar.
Imagine waking up to an email full of alerts about unwanted access attempts. It is every administrator’s nightmare. The truth is that many security incidents can be traced back to disabled accounts that were not properly reviewed. You might wonder, “What about disabled accounts? “Aren’t they harmless?” Well, not quite. There are reasons we need to, Audit Disabled Accounts.
Disabled accounts in Active Directory (AD) are analogous to lost keys to your home. They may be out of sight, but they do exist. Those who look hard enough can find them. If you do not audit these accounts on a regular basis, you risk exposing your network to vulnerabilities. Neglected accounts may result in attacks or compliance difficulties.
I discovered this the hard way during my early days as a sysadmin. I believed I had things under control. One day, an audit found multiple disabled accounts that had been left neglected for months. It was a wakeup call. Since then, reviewing disabled accounts has been an important part of my routine.
Why should you consider auditing disabled accounts? It’s not just about checking the compliance box. It is about ensuring a safe and well-managed environment. It is critical to keep your network secure from unauthorized access and breaches. In this post, I’ll show you how to build up a PowerShell script to audit disabled accounts. We will also automate the process using a scheduled task. Believe me, it’s easier than you think. Your future self will thank you for this.
Let us begin our path toward greater security and peace of mind.
The Why Audit Disabled Accounts?
Picture this: It’s the middle of the day, when the CFO’s account is abruptly deactivated. Chaos ensues. The support desk is frantic, and everyone is on edge. You are left wondering, “Who did this, and when?” It’s a frustrating situation that could have been prevented with routine audits.
Auditing disabled accounts is more than just a boring process; it is critical for determining exactly when and by whom an account was disabled. Consider installing a surveillance camera on your network doors. You know precisely who locked which door and at what time. This level of visibility is critical for keeping control of your Active Directory (AD).
This PowerShell script was built in response to a particularly stressful occurrence. A help desk technician unintentionally shut down the CFO’s account. The names were nearly identical: bholts for the CFO, and bsholts for a floor technician. One tiny error resulted in a major problem. The CFO was naturally furious, demanding to know who was to blame. That’s when I realized I needed a solid technique to keep track of these actions.
Security is a significant reason for auditing disabled accounts. If an attacker acquires access to one of these accounts, they may be able to explore your network without detection. It’s like leaving the front door wide open. Regular audits ensure that these accounts are appropriately managed and secured, preventing unwanted access.
Compliance
Compliance is another reason to keep track of disabled accounts. Many regulatory regimes impose severe controls on user accounts. GDPR, HIPAA, and other regulations need proper account management, including for disabled accounts. Failure to comply might result in costly fines and a tarnished reputation.
However, it is not simply about avoiding undesirable results. Regular auditing of disabled accounts is also excellent housekeeping. It keeps your Active Directory clean and orderly. An clean Active Directory makes it easier to manage active users and keeps your environment running smoothly.
In my early sysadmin days, I underestimated the necessity of auditing disabled accounts. That was until the incident with the CFO’s account. Since then, auditing has been an essential component of my managerial routine. It’s a modest step that provides significant peace of mind.
So take a time to reflect on your current practices. Do you periodically audit disabled accounts? If not, this is a great moment to start. It represents an investment in your network’s security and efficiency. And believe me, it is worth every minute.
Let’s dive into the heart of this guide: the PowerShell script that will help you audit disabled accounts in Active Directory. We’ll break it down line by line, so you understand exactly how it works and how to customize it for your needs.
foreach ($Server in $Servers): Iterates through each server in the $Servers list of strings. Remember, a list of strings is like an array but for strings. Reminds me of noodles before you cook them. Which my daughter made spaghetti the other day and I am proud of her.
Get-WinEvent: Retrieves the events that match the criteria in $FilterTable. -ErrorAction SilentlyContinue suppresses errors. I liken this command to the spaghetti after it has been cooked.
foreach ($Event in $Events) {
$ReturnInfo += [pscustomobject][ordered]@{
Task = "Account Disabled"
Time = $Event.TimeCreated
DC = $Event.MachineName
Name = (get-aduser -Identity "$($Event.Properties[0].Value)" -Properties Displayname).Displayname
Username = $Event.Properties[0].Value
Admin = $Event.Properties[4].Value
}
}
Processing and Exporting Events
Processing Events
foreach ($Event in $Events): Iterates through each retrieved event. We like to loop a lot with powershell.
$ReturnInfo += [pscustomobject][ordered]: Adds a custom object to the $ReturnInfo array, containing:
Task: Describes the task (“Account Disabled”).
Time: The time the event was created.
DC: The domain controller where the event occurred.
Name: The display name of the disabled account.
Username: The username of the disabled account.
Admin: The account of the administrator who performed the action.
Export-Csv: Exports the $ReturnInfo array to a CSV file specified by $OutCSVfile.
-NoClobber prevents overwriting existing files.
-NoTypeInformation omits type information from the CSV. That’s the crappy line that sucks at the top of csvs that powershell 5 likes to add. You don’t ahve to do this if you are using powershell 7.
-Append adds the results to the file without overwriting it.
By understanding each part of this script, you can tailor it to your specific needs. Whether you’re dealing with multiple servers or need a different time range, you now have the tools to make those adjustments. From here, you can make scheduled tasks that points to the required devices and such. We will cover that next week.
In the end
Auditing disabled accounts in Active Directory is like keeping a vigilant eye on the silent guardians of your network. It’s a crucial step to ensure that your environment remains secure and compliant. With the PowerShell script we’ve walked through, you now have the tools to monitor when an account was disabled and by whom, saving you from potential security breaches and compliance headaches.
Remember the story of the help desk technician who accidentally disabled the CFO’s account? That incident was a wake-up call, highlighting the importance of regular audits. By setting up a scheduled task to run this script, you can prevent similar scenarios in the future. You’ll have clear, reliable records that can help you quickly identify and rectify mistakes, keeping your network safe and your users happy.
Regularly auditing disabled accounts isn’t just about avoiding problems; it’s about creating a culture of diligence and responsibility. It’s about taking proactive steps to manage your AD environment effectively. Whether you’re a seasoned sysadmin or new to the role, these practices are essential in maintaining a robust and secure network.
So, take a moment to implement these steps. Set up the script, configure the scheduled task, and rest easy knowing you’ve added a solid layer of protection to your network. Your future self, and your organization, will thank you.
What we can learn as a person?
Disabled accounts linger around and sometimes they can have emails and more attached to them. But they are not active. When I was working with the MSP, I often found ADs with a lot of these accounts and no documentation. Why were they disabled, and left there? Was it some compliance or something else?
Well, in our life, we have something like disabled accounts. They don’t activly hurt us, but over time they can add up and cause issues. That’s small truama. Some therapist call it death by a tousand paper cuts. By themselves, they are not damaging enough to cause PTSD or anything along those likes, but over time, they can cause major issues. A good example of this is, you get spanked each sunday because you fail asleep in church. Some people start seeing churchs as a place of abuse while others embrace the church as safty. By itself a simple spanking doesn’t cause trauma, unless it’s really ugly, but over time, it can cause all kinds of issues.
The shame child
The best way to handle these micro trauma’s is to address the distorted emotions that are born from them. A good example of this is a child who was shamed for being evil at birth. Hearing this one time is nothing, but hearing this daily makes this child believe he is evil. This translates to shame. This shame can come out in many different forms. To heal, he has to come to the conculsion himself that he wasn’t evil from birth and this belief is wrong.
It’s time for him to delete those accounts of shame. Knowing where they come from is half the battle. If you don’t kno where the emotion comes from, how do you find the emotion? It is a discovery process. It’s a rough one too. Seek a licensed therapist for this and have a good community.