by David | May 27, 2024 | Information Technology, Resources
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.
The Script
#Hourly
[cmdletbinding()]
param (
[int]$HoursBack = 1,
[string[]]$Servers,
[string]$OutCSVfile
)
$StartTimeStamp = ((Get-Date).AddHours(-($HoursBack)))
$EndTimeStamp = (Get-Date)
$ReturnInfo = @()
$FilterTable = @{
'StartTime' = $StartTimeStamp
'EndTime' = $EndTimeStamp
'LogName' = 'Security'
'Id' = 4725
}
$Events = foreach ($Server in $Servers) {
Get-WinEvent -ComputerName "$Server" -FilterHashtable $FilterTable -ErrorAction SilentlyContinue
}
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
}
}
$ReturnInfo | Export-Csv $OutCSVfile -NoClobber -NoTypeInformation -Append
The Breakdown
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.
[cmdletbinding()]
param (
[int]$HoursBack = 1,
[string[]]$Servers,
[string]$OutCSVfile
)
- Parameters and Initialization
- [cmdletbinding()]: This line makes the script act like an advanced function, providing more control over parameters and runtime behavior.
- param: Here, we define three parameters:
$HoursBack
: The number of hours back to search for disabled accounts (default is 1).
$Servers
: An array of server names to query.
$OutCSVfile
: The file path to save the audit results.
$StartTimeStamp = ((Get-Date).AddHours(-($HoursBack)))
$EndTimeStamp = (Get-Date)
- Setting Up Timestamps
- $StartTimeStamp: Sets the start time for the search to one hour ago.
- $EndTimeStamp: Sets the end time to the current date and time.
$ReturnInfo = @()
$FilterTable = @{
'StartTime' = $StartTimeStamp
'EndTime' = $EndTimeStamp
'LogName' = 'Security'
'Id' = 4725
}
Grabbing the Events
- Filtering Events
- $ReturnInfo: Initializes an empty array to store the results. This allows us to collect the needed information for later.
- $FilterTable: Defines the criteria for filtering events:
StartTime
and EndTime
specify the time range. It’s important not to grab to many logs because Powershell can’t handle large amount of data.
LogName
is set to ‘Security’ to search in the Security log because that is where the disabled accounts live.
Id
is set to 4725, the event ID for account disablement.
$Events = foreach ($Server in $Servers) {
Get-WinEvent -ComputerName "$Server" -FilterHashtable $FilterTable -ErrorAction SilentlyContinue
}
- Retrieving Events
- 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.
$ReturnInfo | Export-Csv $OutCSVfile -NoClobber -NoTypeInformation -Append
- Exporting Results
- 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.
Additional reading
by David | May 20, 2024 | Information Technology, PowerShell
Digital explorer, how are you? Are you ready to learn more about how your computer works? Good news! You’ve just found PowerShell, the best tool for a digital spy to peek behind the scenes. It’s kind of like a mix between Sherlock Holmes and Ace Ventura: strange, funny, and never dull. Are you read for some monitoring program modules with PowerShell?
Why try to look? Now picture being able to see exactly what your computer does—or doesn’t do. Yes, PowerShell lets you find those hard-to-find modules that know a lot about security and speed. That’s pretty brave, huh?
Just put on your detective shoes and grab a magnifying glass (or a nice chair, really). We are about to start an exciting trip through the Search-ProcessModule function’s twists and turns. It sounds like a wild ride full of surprises, geeky charm, and “aha!” moments. Let’s work together to break this code and maybe save the internet in the process!
Getting to know PowerShell and Process Modules
Thanks for coming back, digital spy! PowerShell is an amazing tool that lets you control your system like a pro. You already know how to use it. Let’s look at process modules, which are an important but often ignored part of the PowerShell toolkit.
What’s the big deal about process modules?
When it comes to your software ecosystem, process modules are like the unsung stars. Each section in your apps is like a little brain—it’s important for them to work but doesn’t get much attention. Monitoring these units isn’t just about knowing what’s going on inside; it’s also about spotting problems before they get worse.
You could find a part that is acting up and slowing down your system, or you could find a security risk before it becomes a threat. That is why it’s important to keep an eye on process units. It’s like having x-ray vision that lets you see right through the outside of your system to its working heart.
Now that you know this, you’re not just working on hope; you have knowledge and foresight. Next, we’ll talk about the Search-ProcessModule function, which is the main character of our story. It’s the most important thing you can use to put this idea into action. Watch out!
A Look at the Search-ProcessModule Function
Now that you know how process modules work, it’s time to bring out the big guns. Now comes the Search-ProcessModule function, which is your secret tool against waste and security risks. The great thing about this PowerShell function is that it can do a lot of different things. Let’s take apart monitoring program modules with PowerShell.
Finding Out What Search-ProcessModule Can Do for You
The Search-ProcessModule function isn’t just another script; it’s a very useful tool for finding specific modules in any process. This function is where you can get quick and accurate answers, whether you’re trying to fix a program that’s running slowly or making sure that security rules are being followed.
How Function Parameters Work:
- ProcessName: This is where you define the process name that you want to look at. It’s like picking which room in a huge house to look.
- ModuleName: This is where you list one or more modules that you want to find in the chosen process. It’s like knowing what kind of furniture you want for that room.
- ComputerName: If you choose “ComputerName,” you can do this search on a remote computer. Not a problem. With this number, you can reach more people on the network.
A quick run-through of how it works
- Before the Search-ProcessModule code does anything else, it checks to see if the given process is already running. Then it goes deeper and checks each module that the process loaded. It’s smart as it doesn’t just look at names; it also looks for patterns that fit your search. It’s like having a bloodhound that sniffs out the exact thing you want.
What if something goes wrong? The function has a strong way of handling errors. It won’t just fall down; it will also tell you why, giving you clear error messages that can help you figure out what to do next.
Uses in the Real World
The Search-ProcessModule tool can be used to find unnecessary modules that slow down the server and make sure that only authorized modules are running on sensitive systems. It is very flexible and powerful. It’s like having eyes and ears in the digital world, and it really does keep the system safe.
We’ll go over everything you need to know to start using this powerful tool in the next part, from installing it to setting it up. Keep listening, because soon you’ll be a pro at module watching!
Creating an Environment for Utilizing Search-ProcessModule
Okay, let’s prepare the stage for an outstanding performance from the Search-ProcessModule function. Getting everything ready may seem like a task, but believe me, it’s a breeze—easier than baking a pie, in fact! Here’s a straightforward guide to getting everything tuned and ready to go.
Preparing PowerShell for Optimal Performance
First, you need to ensure that PowerShell is installed on your machine. If you’re using a recent version of Windows, well done! It’s likely that you already have it installed. Simply type PowerShell in your search bar and check if it appears. If it doesn’t, no problem! A brief visit to the Microsoft website will help you find what you need for a download.
Setting Up Execution Policies
First, let’s discuss execution policies. PowerShell prefers a cautious approach, so it does not execute scripts without careful consideration. Here’s a step-by-step guide on how to create the perfect setting:
- Launch PowerShell with administrative privileges by right-clicking and selecting “Run as administrator”.
- Execute the command Set-ExecutionPolicy RemoteSigned. This policy allows you to execute scripts that you have created or obtained from reliable sources.
Getting Ready for Remote Execution
Considering using the Search-ProcessModule function on a remote machine? Enabling PowerShell remoting is necessary. Here’s the enchanting incantation:
- Continuing in your admin PowerShell window, go ahead and enter the command Enable-PSRemoting -Force. This command will help you configure your machine to send and receive PowerShell commands remotely.
- Make sure the remote machine is set up in a similar way if you want to take a look at its process modules.
Simple Test Run
Now, let’s ensure that everything is functioning properly:
- Launch PowerShell.
- Give the Get-Process command a try to easily view the processes currently running on your machine. If you come across a well-organized list, you’re all set!
Finishing the Setup
And just like that, everything is ready for you! You’re all set to begin using the Search-ProcessModule function with ease in your environment. Now, we’ll explore a straightforward guide that will help you effectively utilize this tool to maintain the stability of your systems. Stay prepared, as things are about to become quite captivating!
A lot of work so far to do something as simple as monitoring program modules with PowerShell. However, this is all for remote and local monitoring. If your environment is already setup, you don’t need all of this.
The Script
Function Search-ProcessModule {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, HelpMessage="Enter the name of the process you want to check.")]
[Alias("Process")]
[string]$ProcessName,
[Parameter(Mandatory=$true, HelpMessage="Enter the name(s) of the module(s) you want to find in the process.")]
[Alias("Module")]
[string[]]$ModuleName,
[string]$ComputerName
)
$scriptBlock = {
param($ProcessName, $ModuleName)
try {
$processes = Get-Process -Name $ProcessName -ErrorAction Stop
foreach ($process in $processes) {
$modules = $process.Modules | Select-Object -ExpandProperty ModuleName
foreach ($name in $ModuleName) {
if ($modules -like "*$name*") {
return $true
}
}
}
return $false
} catch {
Write-Error "Error: $_.Exception.Message"
return $false
}
}
if ($ComputerName) {
Invoke-Command -ComputerName $ComputerName -ScriptBlock $scriptBlock -ArgumentList $ProcessName, $ModuleName
} else {
& $scriptBlock $ProcessName $ModuleName
}
}
Detailed Breakdown of the Search-ProcessModule Script
Now that your stage is set, it’s time to spotlight the star of the show: the Search-ProcessModule
function. Let’s dissect this function piece by piece, understanding how each part works and how you can use it to keep your systems running smoothly.
The Heart of the Function: The Script Block
The core of the Search-ProcessModule
function is a script block. Think of this as the brain of the operation, where all the major decisions are made. Here’s how it ticks:
- Initialization: The script block starts by taking in the
ProcessName
and ModuleName
parameters you specify.
- Process Check: It uses
Get-Process
to locate the process. If the process isn’t running, it stops and raises an error—no wild goose chases here!
- Module Search: Next, it sifts through each module loaded by the process, checking if any match the names you’re curious about. It’s thorough, ensuring no stone is left unturned.
Navigating Through Processes and Modules
As we dive deeper:
- Iterative Checks: For each process found, the function iterates through all loaded modules. It uses a loop to compare each module name against your specified criteria.
- Pattern Matching: It isn’t just looking for exact names; it’s smarter! The function searches for patterns, catching even partially matching names.
Error Handling: Your Safety Net
Errors? No problem:
- The function is equipped with try-catch blocks, making it robust against unexpected hiccups. If something goes wrong, it catches the error and provides a clear message. This helps you understand what went wrong and how to fix it.
For Remote Enthusiasts: Running the Script on Another Machine
Got a remote machine? Here’s your toolkit:
- If you specified a
ComputerName
, the function doesn’t just run locally. It uses Invoke-Command
to execute the script block on the remote machine. This feature turns your local setup into a command center for multiple machines.
Putting It All Together
With this detailed breakdown, you’re not just running scripts; you’re conducting an orchestra of system checks with precision. Next, we’ll walk through a step-by-step guide to deploying this function effectively, ensuring you’re fully equipped to monitor and manage your system’s modules like never before.
Practical Application: MS Teams
When managing IT environments, especially in settings where communication tools like Microsoft Teams are widely used, it’s crucial to ensure that system updates or software deployments do not disrupt important meetings or presentations. Here’s how you can use the Search-ProcessModule
function to intelligently manage deployments based on Teams’ activity. We are about to bring reality to monitoring program modules with PowerShell.
Scenario Setup
Let’s consider a common scenario: you need to deploy an application on a user’s machine during working hours. The challenge is to do this without interrupting an ongoing Microsoft Teams conference call or screen sharing session.
Step-by-Step Guide for Monitoring Teams
Step 1: Identify the Process
We know that the main process for Microsoft Teams is named ‘MS-Teams’. This is your target process for monitoring.
Step 2: Define Modules of Interest
- For detecting conference calls, we look for the module ‘coremmres.dll’.
- For detecting screen sharing, the modules ‘mfmjpegdec.dll’ and ‘mfperfhelper.dll’ are the indicators.
Step 3: Craft Your PowerShell Command
To check for a conference call, your command might look like this:
Search-ProcessModule -ProcessName "MS-Teams" -ModuleName "coremmres.dll"
For screen sharing, you’d check both modules:
Search-ProcessModule -ProcessName "MS-Teams" -ModuleName "mfmjpegdec.dll", "mfperfhelper.dll"
Step 4: Execute and Analyze
Run these commands remotely or locally based on your administration setup. If either command returns True
, you know now is not a good time for interactive tasks.
Step 5: Integrate with PADT
With this information, you can configure PADT to delay or adjust the deployment method. For example, if Teams is currently used for a call or sharing a screen, you might opt to deploy the application silently or reschedule the deployment.
Advanced Automation Tips
To streamline this monitoring program modules with PowerShell, consider setting up a scheduled task that checks for these conditions at regular intervals or right before a planned software deployment. You can also integrate these checks into your deployment scripts, automating the decision-making process based on the presence of these modules.
Final Thoughts
Using the Search-ProcessModule
function to monitor applications like Microsoft Teams ensures that your software deployments are as unobtrusive as possible. This approach not only minimizes disruptions but also enhances user satisfaction and system administration efficiency.
What can we learn as a person?
Just as the Search-ProcessModule
function in PowerShell allows system administrators to preemptively identify potential issues by monitoring certain modules, we can similarly benefit from understanding and managing our personal triggers. This proactive approach not only prevents disruptions in our digital systems but can also lead to more harmonious personal and professional lives.
The Importance of Recognizing Triggers
Imagine walking into a room full of people. It’s loud, crowded, and there’s only one exit. For someone like me, who experiences PTSD, such settings can quickly become overwhelming. This is a trigger—a psychological trigger that, much like an unwanted software module, can disrupt my operating system—my mental state.
Drawing Parallels with PowerShell
Just as we use the Search-ProcessModule
function to detect if Microsoft Teams is in a delicate state (like a conference call or screen sharing), understanding our mental triggers allows us to gauge when we’re potentially entering a delicate emotional state. The function helps avoid awkward disruptions during digital meetings; similarly, knowing our triggers can help avoid personal discomfort or emotional crises.
Personal Strategies for Managing Triggers
Here’s how I manage:
- Preparation: Much like how we prepare our systems with the right tools (like PowerShell scripts), I equip myself with tools to manage my triggers. Carrying headphones helps manage sound levels, much like how monitoring tools help manage system performance.
- Avoidance: If I know ahead of time that a situation—like a noisy room with poor acoustics and limited exits—might become overwhelming, I choose not to engage, similar to how we might delay software deployment during critical business operations.
- Awareness: Just as system monitoring provides real-time insights into what’s happening with our digital environments, being mindful and aware of my surroundings helps me maintain emotional equilibrium.
Broader Implications
This isn’t just about avoiding what makes us uncomfortable. It’s about understanding the environments in which we thrive. Knowing your triggers and how to manage them can dramatically improve your quality of life, enhance your interactions, and reduce stress—much like how effective system monitoring can enhance performance and reduce downtime.
In both technology and life, the better we understand the systems and their sensitivities, the more effectively we can manage them. Whether it’s preventing a software crash during a critical presentation or managing personal stress in a crowded environment, the principles remain the same: monitor, understand, and prepare. This proactive approach not only prevents problems but also promotes a smoother, more efficient experience for everyone involved.
Future Readings
by David | May 13, 2024 | Information Technology, PowerShell
Here, we’ll learn how to use the & operator to run script blocks—your go-to PowerShell script block tutorial! You’re not alone if you’ve ever thought PowerShell scripting was a little confusing. Today, we’re simplifying the & operator, one of PowerShell’s most important features, and making it really easy to use. Knowing how to use this operator successfully will improve your scripting talents, regardless of experience level. Together, we can make writing scripts as pleasurable as indulging in your preferred treat after a demanding day! Join me as we dive into our PowerShell script block tutorial.
What is the &
Operator?
Your key to running commands kept in script blocks or variables in PowerShell is the & operator, sometimes referred to as the call operator. Consider it as your script’s magic wand, waved to bring it to life. What use is this to us? As simple as entering Write-Host “Hello, World!” commands aren’t always clear-cut. The & operator exists to make sure things go smoothly and precisely as intended when you start storing commands in variables or need to perform complicated expressions kept as script blocks.
For example, typing just $command in PowerShell will return the string “Get-Date” if your command is $command = “Get-Date”—not very useful if you’re trying to find out the time! But & $cmd runs it, converting your string into a useful command. That seems easy enough, right? Still, so potent.
Understanding Script Blocks
Moving deeper into the rabbit hole, let’s talk about script blocks. In PowerShell, a script block is essentially a collection of statements or expressions that are written as a single unit but executed as needed. Imagine them as your script’s building blocks, where each block is crafted to perform specific tasks.
Syntax-wise, a script block is encased in curly braces {}
. Here’s a straightforward example:
$myScriptBlock = {
param ($name)
"Hello, $name! Today is $(Get-Date)."
}
In this script block, we’re passing a parameter $name
and outputting a friendly greeting along with the current date. But without our trusty &
operator, this friendly message remains locked inside its curly brace prison. By calling & $myScriptBlock -name 'Frank'
, you breathe life into it, and out pops, “Hello, Frank! Today is [current date].”
Script blocks can be as simple or as complex as you need them to be, handling anything from quick one-liners to extensive scripts requiring loops, conditionals, and more. They’re incredibly powerful because they let you neatly package and repeatedly execute chunks of code with minimal fuss.
Executing Script Blocks with the &
Operator
Now, let’s get our hands dirty and see the &
operator in action. We’ll take the script block we mentioned earlier and really break it down. This script block scrambles a message—a fun way to see the power of randomization in PowerShell:
$myScriptBlock = {
param ($msg)
$charArray = $msg.ToCharArray()
$random = New-Object System.Random
[Array]::Sort($charArray, [System.Collections.Generic.Comparer[char]]::Create({param($x,$y) $random.Next(-1,2)}))
$scrambledMsg = -join $charArray
Write-Host "$scrambledMsg"
}
To execute this script block and see your message get all mixed up, you’d use:
& $myScriptBlock "I like cheese cake on my chocolate syrup."
This line invokes the script block with the &
operator and passes the string “I like cheese cake on my chocolate syrup” as an argument. The script takes each character, scrambles them, and outputs something that looks like your original message went through a blender. It’s a practical, hands-on way to see script blocks and the &
operator in perfect harmony.
Practical Examples
While our scrambled message is fun, let’s look at more practical uses of script blocks and the &
operator in everyday scripting tasks. Here are a few scenarios:
- Batch Renaming Files:This script block takes a file and a new name as parameters and renames the file accordingly.
$files = Get-ChildItem -Path "C:\MyDocuments" $renameScript = { param ($file, $newName) Rename-Item $file.FullName -NewName $newName } foreach ($file in $files) { & $renameScript $file "New_$($file.Name)" }
- Processing Log Files:
Here, the script block filters out lines containing “ERROR” from a log file and saves them to a new file.
$processLog = { param ($logPath) $logContents = Get-Content $logPath $logContents | Where-Object { $_ -match "ERROR" } | Set-Content "FilteredErrors.log" } & $processLog "C:\Logs\server.log"
Advanced Tips and Tricks
To elevate your scripting game, here are some advanced tips and tricks for using script blocks and the &
operator in PowerShell:
- Passing Multiple Parameters: You can pass multiple parameters to a script block by simply separating them with commas after the script block call:
& $myBlockParam $arg1, $arg2, $arg3
- Using Script Blocks for Asynchronous Tasks: PowerShell allows script blocks to be run asynchronously, which can be great for performance when dealing with long-running tasks
$job = Start-Job -ScriptBlock $myScriptBlock -ArgumentList "ParamValue"
- Error Handling within Script Blocks: Always include error handling within your script blocks to manage exceptions smoothly
$errorHandlingBlock = { try { # Potentially risky operations } catch { Write-Error "Something went wrong!" } } & $errorHandlingBlock
Wrapping Up
Congratulations for delving deeply into the operator and script blocks of PowerShell! We’ve unpacked a lot of really technical material today, transforming what may have appeared like magic into a set of useful abilities you can apply immediately. We began with a review of the & operator, looked at defining and running script blocks, and even played about with message scrambling. We next advanced to increasingly difficult scenarios to show how script blocks might make chores like batch renaming files or sorting through logs easier.
Writing more effective and efficient scripts is easy when you have the & operator in your toolbox. PowerShell is a potent tool. Recall that putting in constant practice is the best approach to improve. Try out several script blocks, modify our examples, and learn how you might use them for everyday chores.
For those who are itching for more, I suggest you to explore more sophisticated PowerShell scripting methods or sign up for PowerShell forums and groups. There is always a new, clever method to learn in the field of scripting, and learning never really ends.
May your scripts always run well and happy scripting! Thank you for looking at our PowerShell script block tutorial.
What can we learn as a Person?
Here’s the thing about PowerShell script blocks: they’re modular. You write them once and use them wherever needed without starting from scratch each time. It’s neat, tidy, and incredibly efficient. Now, let’s take this concept and apply it to something a bit closer to our everyday lives—our work-life balance.
Why Boundaries Matter
Imagine your life as a complex script. Each segment—work, family, personal time—is like a little block of code. Just like in scripting, you don’t want these blocks interfering with each other more than they need to. It messes things up. If work starts to bleed into family time regularly, it’s like a script executing commands where it shouldn’t. Before you know it, you’re looking at a full-blown system crash (or in human terms, a burnout).
Recycling What Works
Why reinvent the wheel? If you’ve nailed a routine that keeps your work and personal life neatly compartmentalized, keep that going. Apply it as often as needed, just like a reusable script block. Found that turning off email notifications after 6 PM helps keep your evenings calm? Make it a staple. Effective routines are like code that doesn’t need debugging—they just work, and they save you a ton of mental energy.
Tweaking the System
Life, just like software, updates and changes all the time. New job? Family dynamics shifted? Just as a programmer tweaks a script to fit new requirements, you might need to adjust your boundaries and routines to keep everything running smoothly. It’s not about sticking rigidly to old scripts but adapting them to better fit your current scenario.
So, let’s take a leaf out of our script book. Setting clear, modular boundaries in our lives isn’t just about keeping things orderly. It’s about ensuring we don’t run ourselves into the ground. After all, nobody’s got time for downtime, right?
Additional Resources
by David | May 6, 2024 | Information Technology
Hi there Ever wish a chatbot could converse back to you like a good friend? You are not by yourself. Like a chat in a coffee shop, many of us want our online exchanges to feel as organic and interesting. Therein is the humanizing ChatGPT magic. Teaching an elderly dog new skills is similar, but the dog is a robot and the tricks are puns. Let us explore how to make your AI more endearing than robotic!
Knowledge of the Features of ChatGPT
How then does ChatGPT work? Think of a really intelligent notepad that records and recalls, well, anything. I call that ChatGPT. Because of its human conversational mimicking design, it may assist with homework, respond to questions, or just make light of a bad day. Everything boils down to patterns, which is the trick. ChatGPT maintains the conversation by learning from a ton of data. To be honest, though, occasionally it sounds more like the president of your high school robotics club than it does like your clever friend. We are therefore here to liven things up a little and give its answers a hint of humanity. As who doesn’t want a chatbot that can actually converse?
Key Strategies to Humanizing ChatGPT
Direct Communication
First off, let’s talk about being direct. When you’re chatting with a friend, they usually get straight to the point, right? So, why should your AI be any different? Teaching ChatGPT to keep its responses clear and straightforward can stop it from rambling like a lost tourist. Just imagine it cutting to the chase, delivering just what you need without the fluff. It’s like your AI suddenly got that it doesn’t need to beat around the bush to sound smart.
Sentence Structure
Now, onto sentence lengths. Ever read something so long you forget the start by the time you reach the end? We’ve all been there. Keeping ChatGPT’s sentences short and sweet can really help. It makes the conversation punchy and to the point—much more like texting with a buddy than reading a dissertation. This means breaking things down into bite-sized pieces that are easy to chew on, so your brain doesn’t have to.
Emulating Human Authors
And here’s where it gets really fun—playing dress-up with ChatGPT’s style. Want it to sound like Hemingway? Or maybe more like your favorite blogger, Noamii Carr? You can actually tweak its style to mimic different authors. This not only spices up the conversation but also lets you feel like you’re chatting with different personalities. It’s like having a little party in your chat window where everyone’s invited.
Consistency in Style
Last but definitely not least, let’s talk consistency. It’s great to have ChatGPT sound human, but if it flips between sounding like Shakespeare and your cool Uncle Joe in the same convo, things can get weird. Keeping a consistent style means you know what to expect—like having that one friend who’s always reliably themselves, which is pretty comforting, right? Plus, it keeps the conversation flowing smoothly, without any jarring surprises.
Illustrate Style Variability with Examples
We’ve discussed customising ChatGPT’s style a lot, but what does that truly mean in real life? Showtime has arrived! We’re going to see how three quite distinct ways can be spun around the same subject—yes, ant’s feet, because why not? A stylish rollercoaster is coming your way. Lets see what Humanizing ChatGPT looks like.
Default ChatGPT Style on Ant’s Feet
Ants’ feet, technically referred to as “tarsi,” are quite the marvel of nature. Each foot consists of five small segments, each progressively smaller than the one before it. This design helps ants maintain stability and grip surfaces effectively as they move. Additionally, at the end of each leg, ants have a pair of claws that allow them to climb and hang onto surfaces vertically or upside down, facilitating their ability to navigate through various environments.
Jean-Luc Picard Style on Ant’s Feet
Consider, if you will, the humble ant. A creature of extraordinary diligence, its journey is never hindered by the terrain it traverses. The secret lies in its tarsi—feet, you might say, engineered with precision. Five segments, each a smaller echo of the last, grant it the stability of a seasoned explorer on these micro expeditions. And those claws? They are not mere appendages; they are the tools that allow it to boldly climb where none have climbed before.
Drunk William Shakespeare Style on Ant’s Feet
Oft have I mused upon the tiny pedestals of yon noble ant, so fleet of foot! Tarsi, they call them, with segments five, each less than t’other—what art! How doth the ant scale yon lofty blade of grass? With claws as fine as Cupid’s arrows, that’s how! Verily, these little beasts do strut the earth as kings in their tiny dominions, making merry as they go up and down, to and fro!
Examination of Variations in Style
That was a real laugh. Every style adds a whole new taste to our ant foot. When you simply need the facts, the basic ChatGPT style is clear and instructive. The one by Captain Picard adds a grandeur and adventure that is ideal for igniting wonder and curiosity. And our Shakespeare as a drunk? Just for fun, that adds a little vintage flair and humor to the description. You can adjust ChatGPT’s answers in this way to suit any audience or mood for your AI chat. Like carrying about a conversational chameleon! That’s Humanizing ChatGPT for you.
Extra Advice and Things to Think About
Okay, let’s share a few more pearls of wisdom regarding humanizing ChatGPT before we part ways. First of all, never underestimate the influence of unique touches. Your AI interactions can taste just perfect by adding a little personal flair, much as how a pinch of salt enhances food’s flavors. Keep in mind the mood you want to convey as well. Standard conversations can become unforgettable if you match the AI’s tone with your preferences, whether it be formal, informal, or downright strange.
Whoa, we’ve covered a lot about Humanizing ChatGPT, didn’t we? With a plethora of tools at its disposal, ChatGPT can mimic our favorite characters and craft witty lines to simulate human speech as closely as possible. So why not try out these tips? Try different things, have fun, and see how you can make your online chats extraordinary. Recall that every small adjustment contributes to your AI feeling more like a friend than a machine.
Just for a laugh
Just for a good laugh, Here is Worf trying to read some shakesphere.
“Hear me now, brave explorers of cyberspace! Let not this knowledge sit idle in thy minds. I, Worf, son of Mogh, doth challenge thee: engage in the artful manipulation of thy digital companions! Craft thine responses with care; mold thy ChatGPT with the wisdom imparted here. Shall we not share our victories as one? Subscribe, comment below with thine own tales of conquest, and join us in this noble quest for richer dialogues. For honor!”
What can we learn as a person?
To be honest, I was perspiring when AI first appeared. Like bothersome insects, thoughts like, “Is this gizmo going to swipe my job?” swam around my head. I choose to board the AI train instead of swiping at them. And what a trip it’s been! I’ve been teasing AI for the last year, experimenting with various automations and little adjustments. Not going to lie, I’m still getting used to the whole AI tralking to AI automation thing.
The truth is that artificial intelligence is only a tool—think of it as an upscale electric sander. A table can be hand-sanded as smooth as silk by a skilled carpenter, but with the correct equipment, the same task could only take a few hours. Still, give that sander to a rookie. More splinters and sawdust may be present than anything else. Similar to this is AI. Giving a novice AI tools and asking them to create something amazing is… well, hit or miss. They might be able to run a basic script, but things could get complicated when the difficult sections appear.
My first worry stemmed from my imagination of what AI may be rather than from its actual nature—a kind of enhanced autocomplete, if you will. AI will advance, perhaps even completely change everything. It could, however, go away. In any case, we have to roll with the punches. Having adapted for millennia, humans are experts at it. Let us embrace AI rather than worrying about it. Let us learn how to use technology to enhance our life. One never knows. Possibly, we’ll surpass ChatGPT’s humanization!
Additional Resources
by David | Apr 29, 2024 | Information Technology, PowerShell
Tired of manually configuring networks for each VM? Perhaps you’re not alone. Virtual network management is time-consuming and error-prone. If I told you there’s a simpler way? This essay examines a PowerShell script that does that. Making your life easy is key. This will teach you how to quickly Bulk Configure VM networks with PowerShell.
This PowerShell script revolutionizes. Create a private switch and assign it to all VMs automatically. Imagine setting up networks without manually selecting VMs. The script verifies network’s existence. If not, it binds your VMs to a new private switch. Automation saves time and reduces errors. Efficiency at its best.
Before you start, make sure you have everything. PowerShell must be installed and running first. Additionally, the script requires administrative permissions to make significant modifications to your VM setup. View your VM network settings. Using this will prevent configuration conflicts. Checked everything? You can automate your VM network setup now.
The Script
$NewSwitchName = Read-Host "Enter the name for the private switch network"
$NewSwitch = Get-VMSwitch -Name $NewSwitchName -ErrorAction SilentlyContinue
if ($null -ne $NewSwitch) {
Write-Error "Network $NewSwitchName Already Exists"
end
}
New-VMSwitch -Name $NewSwitchName -SwitchType Private -
$VMs = Get-VM
foreach ($VM in $VMs) {
$networkAdapters = Get-VMNetworkAdapter -VMName $vm.Name
if (!($networkAdapters.name -contains "$NewSwitchName")) {
Add-VMNetworkAdapter -VMName $vm.Name -SwitchName $NewSwitchName -Name $NewSwitchName
Connect-VMNetworkAdapter -VMName $vm.Name -Name $NewSwitchName -SwitchName $NewSwitchName
}
Start-Sleep -Seconds 5
Get-VMNetworkAdapter -VMName $vm.Name | Select-Object VMName,SwitchName,MacAddress,IPAddresses,Status,connected | ft
}
The Breakdown
Let’s unravel this script line by line to understand exactly how it simplifies your VM network configurations.
- Reading the Switch Name:
- First, the script prompts you to enter a name for your new private network switch. It uses this name to create or identify the switch.
$NewSwitchName = Read-Host "Enter the name for the private switch network"
- Checking for an Existing Switch:
- It looks up an existing switch by the entered name. If found, it proceeds; if not, it silently handles the error without stopping the script.
$NewSwitch = Get-VMSwitch -Name $NewSwitchName -ErrorAction SilentlyContinue
- Error Handling:
- If a switch with the specified name already exists, the script throws an error and stops. This prevents duplicate networks and potential confusion.
if ($null -ne $NewSwitch) {
Write-Error "Network $NewSwitchName Already Exists"
end
}
- Creating the Private Switch:
- If no existing switch is found, a new private switch is created with the name you provided. This is where the magic of automation starts.
New-VMSwitch -Name $NewSwitchName -SwitchType Private
- Grabs the Current VMs:
- The script fetches a list of all virtual machines on your system.
- Looping Through VMs:
- It loops through each VM, checking and modifying network settings as needed.
- Managing Network Adapters:
- For each VM, it retrieves the network adapters.
foreach ($VM in $VMs) {
$networkAdapters = Get-VMNetworkAdapter -VMName $vm.Name
}
- Conditional Addition and Connection:
- The script checks if the network adapter with the new switch name already exists.
- If not, it adds a new adapter and connects it to the created switch.
if (!($networkAdapters.name -contains "$NewSwitchName")) {
Add-VMNetworkAdapter -VMName $vm.Name -SwitchName $NewSwitchName -Name $NewSwitchName
Connect-VMNetworkAdapter -VMName $vm.Name -Name $NewSwitchName -SwitchName $NewSwitchName
}
- Final Configuration Display:
- The script pauses briefly, then displays the final configuration of network adapters for verification.
Start-Sleep -Seconds 5
Get-VMNetworkAdapter -VMName $vm.Name | Select-Object VMName,SwitchName,MacAddress,IPAddresses,Status,connected | ft
Each step is crafted to ensure your VM networks are set up efficiently and correctly, without manual repetition. This script is your shortcut to smarter VM management. A great way to Bulk configure VM networks with PowerShell.
Running the script
Running the script is easy. PowerShell needs administrator access to modify VM networks. Go to your script directory. Enter [YourScriptName].Type ps1 and Enter. Enter the network switch name as instructed on-screen. Each VM is configured by the script. Watch it streamline your network one VM at a time.
Fixing Common Problems
Despite this handy script, things may not always go well. Here are some common issues and their solutions:
- Script Not Starting: Verify administrative permissions. Without these, the script can’t alter network settings.
- Error “Network Already Exists”: A switch with the specified name already exists. Change the name or remove the switch if it’s unnecessary.
- Adapters Not Connecting: Make sure your VMs can accept updated network configurations. VMs may need restarts to acknowledge updated settings.
- Recheck each script step for typos or access rights if you find any issues. PowerShell errors typically indicate the problem, so check the output.
Conclusion
Congratulations on automating VM network setups with PowerShell! Your virtual machine management improved significantly. Try tweaking the script to meet your environment and watch how smooth your operations perform. Share a story or tweak? Leave a comment—let’s learn from each other and establish a smart system admin community!
What can we learn as a person?
Throughout my life, I’ve seen how friends often come from friends. My best friend? I met him because of a kid from the playground, and my wife, well, I met her through someone in a chat room. Even those pals from Discord were introduced by someone else. It’s kind of like that PowerShell script we talked about—making connections that make everything work better.
Building these networks, whether they’re the tight-knit kind or the more extensive, professional types, is crucial. It’s just like setting up networks in PowerShell. You’ve got your internal network—those are your close friends, the ones who really get you. And then there’s your external network, which includes acquaintances and professional contacts. Both are key for different reasons.
Networking events? They’re gold. They throw you into a room with people who might just have the same quirks or career goals. It’s about planting seeds that could grow into either your next job opportunity or into someone you can rely on when things get rough.
Just as our script ensures smooth communication across VMs, weaving through networking events helps build a solid web of contacts. Every handshake or quick chat could be the start of something big—think of each as connecting a new node in your vast network.
Keep it balanced, keep it genuine, and watch as your network—both personal and professional—flourishes. Just like a well-run system of VMs, a well-nurtured network supports and enhances your life in ways you might not even expect.
Additional Reading