what's a script you wrote once that's still saving you time years later
Posted by Less-Loss1605@reddit | sysadmin | View on Reddit | 164 comments
i wrote a powershell script like 3 years ago that checks AD for disabled accounts that still have active mailboxes and spits out a csv every monday morning. took me maybe an hour to write. it's caught orphaned mailboxes so many times since then that i stopped counting. the licensing cost it's saved us is probably more than my raise last year.
the other one is a bash script on our linux boxes that monitors disk usage and sends a slack alert when anything hits 85%. nothing fancy, just df piped through awk with a curl to the slack webhook. wrote it after we had a production outage because /var/log filled up and nobody noticed. that was a fun 2am call.
what's your version of this? the one script that keeps quietly doing its job in the background.
Agitated_Reveal_5363@reddit
tbh the AD cleanup one is the kind of thing that should be standard everywhere but almost never is. the gap between "we should automate that" and someone actually spending the hour to do it is where most orgs lose money quietly.
sgtGiggsy@reddit
I have to create reports on users, their mailbox usages and their mail group memberships monthly. It took me several hours to write the script, but now it produces the lists in three minutes. It's absolutely baffling how exporting these from ActiveDirectory is not supported out of box in RSAT.
Fungiblefaith@reddit
A script that checks a /var/log file for a specific error code of a revoked smart card error for our front end web authentication at the once an hour.
Pipes to a file that gets sent to the helpdesk for revoked Crediting access requests.
They know why someone’s authentication fails and why before they call. Saved countless hours of troubleshooting.
Evening-Result5868@reddit
i have a python script that scrapes our switch configs every night and commits them to a private git repo. started doing it after a junior admin fat-fingered a vlan config and we had no backup to roll back to. now any time someone messes up a switch config i just git diff and see exactly what changed. probably saved us 4 or 5 times already
Less-Loss1605@reddit (OP)
the git repo for switch configs is smart. we do something similar with rancid but it breaks every time we upgrade firmware and nobody wants to fix it so half our devices aren't backed up anymore. might just steal your approach and do it with a python script and cron instead. at least i'd understand what's breaking when it breaks
TheVirtualMoose@reddit
Oxidized works for us. Seems robust between vendors and firmware versions.
TylerJWhit@reddit
Thanks for the tip. Starred
swiss786@reddit
Did you never heard about something called Nagios (monitoring solution) or something else for your server disk space or any other infrastructure monitoring ?
Dat_Steve@reddit
This is a stupid simple one… but I have a group of scripts called “bulk - open all x in notepad++” that essentially opens config files in notepad++ from a group of servers defined in a $servers variable.
We manage different groups of servers that require manual changes to config files often and when I came onboard I was taught to log into each server to make the change. I asked why we they just didn’t \\server\c$\ flag into them instead… and they were just baffled by the concept initially. That led to further efficiencies in replacing variable within the config files- etc etc. Long story short- stupid simple tasks made stupid simpler-er to save time.
TylerJWhit@reddit
If it's Linux you can use cluster ssh. But ultimately I would highly recommend using config management tools like Ansible, Terraform, or saltstack.
hooch@reddit
That’s a good idea actually
Adam_Kearn@reddit
Back when I was doing my apprenticeship around 2019 I was working for an MSP and I would spend most days installing printers as some of our customers had multiple offices which meant lots of employees needed more than one printer installing on their computer.
(PaperCut wasn’t an option or any other solution like follow-me queues)
I created a script that we could push out remotely using our RMM tool to install the printer using a drop down box to select the Company and Office/location.
Spent about a week collecting all the drivers and IP addresses for every one of our customers (even the small customers) so everything was standardised.
I spoke with one of my old colleagues as I’ve not worked there for a long time and they are still using this script till this day. They just add IPs to the list occasionally.
cjbarone@reddit
I did that when I worked at an MFP company to quickly generate install scripts for our printers on multiple systems. People in my neck of the woods don't use print servers, I had to bring that fad back with my current job.
MajorInterest2033@reddit
Not one script specifically but rather a pinned notepad full of snippets for my day-to-day tasks.
Every time I find something new and useful it goes in there with a description line above to help future-self find it next time.
Saved me hours over time, along with the Powershell command history file
Icemagic@reddit
I did something like this at my last job. We ended up putting them into a gui where we could run them on various computers.
Click command or script needed > prompts for computer name > input name > get output.
I was tired of copying and pasting over and over lol
PaidByMicrosoft@reddit
I'm not sharing any of my scripts anymore with coworkers because they're incapable of troubleshooting anything. Even with an error saying "user not found", they'll come back and say "it's not working, can you fix it?". You stupid motherfucker, if the user isn't found in SCCM, this script won't be able to set that user as the primary user to the computer you specified.
chiperino1@reddit
I created a gui (ok chatgpt did cuz I don't know how to do this, the scripts are mine though) that looks at all scripts in the folder the GUI is housed in and will list them in the GUI.
If they are in folders it will list the folders and they can be expanded to select a script within so it can be organized. It will also launch the scripts with the account that triggered the GUI, so the GUI can be ran with admin creds even if the user session is not elevated.
This has allowed me to trigger my regular scripts without having to use vs code, ise, or go and find scripts. I also put .ps1s calling my daily use tools (sccm, aduc, devolution rdm, etc) in a folder so I can launch them and not enter creds.
It's saved me lots of time, and as I develop more tools I add them into the folder structure, hit refresh on the GUI, and there it is
techwaffles@reddit
We deployed SemaphoreUI at work for ansible and powershell. It has been fantastic. I can script things and hand it off to less technical teammates.
Add a couple webhooks for metrics and alerts and you got some happy teams.
Ratiocinor@reddit
Uh this is very worrying lol
Does your company not have a wiki or knowledge base or documentation of any kind?
I hate it when people don't document what they're doing and everything is fragmented, and when you ask them "did you write this down anywhere" they say "sure! It's right here on my desktop useful_commands.txt"
Like uhh, were you planning on sharing those at any point?
The reply is always the same too. "Oh it's nothing fancy, just stuff I need to know. It's not neat and formatted for other people. I don't have time to clean it up!". Brother I'm not asking you to write an blog or flawless how-to guide. Just a "if you get this error message run this command to restart the web server" or something but no one ever does it
No one ever documents anything it's the bane of my existence
MajorInterest2033@reddit
Two levels of this...
If it's a specific script for maintaining a specific product yes goes into a docs page with a clean explanation of what it does and why you use it.
For little script loops, functions etc. those go in my cheat sheet as building blocks for anything larger. Basically one feeds the other over time.
Myte342@reddit
Having things documented for the entire company is different than personal notes. I am just like the guy you responded to, I have my own personal notes full of commands and scripts for various functions and tasks. I also have them all documented in the company knowledge base... but having them local to my PC and formatted a specific way makes it soooo much easier than searching the company KB's for a specific item every time I need it... and worse if access to the database is down for some reason. That's when I REALLY need access to those commands. :D
Iliketrucks2@reddit
I get it but at the same time, I have one of those lists and it’s not “when the web server goes down”. I suspect that’s what most of us have - it’s just snippets of syntax or commands I have used that can reconstruct - not reusable chunks. Curating that into a document for others - then trying to keep it from becoming out of date, or dealing with questions about it - is time I don’t want to spent for my giant list of commands
Ratiocinor@reddit
Haha it's like you set out to prove everything I said
You don't have to "curate it into a document for others"
You don't have to "prevent it from becoming out of date"
You don't have to "deal with questions about it" (almost no one will even read it let alone ask you about it)
Just write down what you're doing somewhere people can actually see it
I don't know why people think it's like publishing an article on wikipedia or something. I see the same attitude from junior developers when I'm trying to get them to git commit their code. They're like "oh no I can't git commit yet, it's not ready. I need to clean it up first. It's not good enough. I'll do it soon I promise" (this drags on for literally months). My god just commit the work in progress it doesn't have to be flawless. I think they consider git commit like this grand act of publishing something for the entire world to see and scrutinise and it needs to be flawless and clean and finished
Trying to "curate a document for others" is a fool's errand because you'll never write anything better than the wealth of tutorials out there on the internet anyway. Just write down the command you used to make the virtual bridged adapter so I can see what flags you used damn it
weaver_of_cloth@reddit
Holy crap this is awful. If you hang on to your code for months without committing, how do you merge?? At the very least, branch that shit off. More people should do safety commits and end-of-day commits and...
Ratiocinor@reddit
They don't merge it
Obviously I don't allow this for any project I run, everyone will commit their work whether they like it or not, or I won't even look at it
This is for other projects in the company where juniors who aren't software devs write some python code or something and they have no actual oversight from a proper developer. I worked at a company that was very silo'd and the non-software projects they'd just let some junior run wild with it underneath a scientist or project manager that isn't IT savvy
I tried pointing out that a big cleanup / refactor is exactly the kind of dangerous stressful operation that makes a git commit beforehand critically important, so you can go back if you break everything or make sure you didn't change the output. They never listen though, it's never "ready"
Luckily they're not software projects so they normally just stay someone's internal tool forever and eventually get abandoned. I'm sure some of them though were actually being used to generate data to sell, and they weren't version controlled at all despite my protests... Oh well not my circus and all that...
weaver_of_cloth@reddit
I've got the opposite problem, I have a pretty comprehensive wiki, everyone knows this, and still people don't read it.
Ratiocinor@reddit
Yes same, but it still saves a lot of time when people keep coming to you with the same old questions and my response is always "it's on the wiki, here's the page"
It got to the point where they knew what my response would be before even asking, so they started coming to me with "I searched the wiki but I didn't find anything on X, do you know how to..." instead, and then I just reply with the link to the article they somehow didn't find because they did a cursory 5 second search and didn't actually read anything
When other people write down what they do though it doesn't matter if it's not a well formatted article, it still helps. Just seeing the commands they used for something at least lets me reverse engineer what they did
I don't care if other people don't read it, it's worth it for myself alone just to not have to look up the same old commands all the time but actually see what I did and what mistakes I made last time so I don't have to fix them again
It's much better than "Oh the NFS export isn't working, I remember this happening before, I think it was something to do with SELinux? Crap what did I do last time". Baffles me that people can work like that
TylerJWhit@reddit
Agreed. Every script I write I make it accessible to others.
If it's not reusable and properly wrapped (in a function with inputs I can pass to it) , then it's only a half finished script.
Jarrus__Kanan_Jarrus@reddit
No one documents anything because if management can run can have AI run the scripts they’d replace us with a quickness.
You have scripts to speed stuff up for you, not for management to take and give to the offshore guys after firing you.
Ratiocinor@reddit
Red flag #2: People who try and give themselves "job security" by obfuscating what they do to try and make themselves "unfireable"
sonic10158@reddit
I have never worked at a place with a real knowledge base before. Last job I was at was going to “soon” put one together for everyone to submit stuff. Current job they can’t even get the company to approve centralizing the various IT groups much less combine documentation
Myte342@reddit
Yup. I have the worst memory for details, but broad strokes are easy for me. So I can remember that there does exist a command for XYZ task or a script for ABC, but not the details of it. So I have searchable notes with such things recorded so I don't have to keep trying to google for them when I need them.
sanman_sabane@reddit
Notepad++
sonic10158@reddit
I have a text file for this sorta thing. I call it my cheatsheet lol
Enxer@reddit
I took my 14MB text file and put it into a bitbucket repo for other engineers when I moved up. Nice to see there are still pull and push requests to the file.
painted-biird@reddit
Yup- love my Powershell/Bash crib notes file in vs code.
Mr_Dobalina71@reddit
Drop database - you do that to all your databases, nothing to do, but also probably fired.
Coconut681@reddit
https://xkcd.com/327/
This always makes me smile
tgrantt@reddit
Mobile https://m.xkcd.com/327/
Froggypwns@reddit
I love how everyone knows exactly which XKCD this is without clicking the link.
Valheru78@reddit
I love Bobby Tables
hellcat_uk@reddit
Ah, little Bobby Tables
Ssakaa@reddit
No necessarily. It might just be a very visible learning situation if you have a good org.
https://about.gitlab.com/blog/postmortem-of-database-outage-of-january-31/
HayabusaJack@reddit
You can do anything you want on your last day :)
ShadowCaster0476@reddit
You do that after you’re fired.
Appropriate-Fish2374@reddit
That is a time savings
TKInstinct@reddit
A Winget array for software installation.
Pocket-Flapjack@reddit
2 scripts.
One that disables users who havnt signed in for X number of days. It creates an OU with the month and year, disables the accouts, moves them to the OU and then logs their DN to a file so I can put them back.
Second one iterates over a list of servers and looks for services and scheduled tasks and who runs them. Very handy for resetting service account passwords when the owner has "forgot" where they used them.
Both made in around an hour both have saved me weeks by now 😀
ilkhan2016@reddit
Would love a copy of those scripts
sugarfreecaffeine@reddit
Just use AI to help you write it, this isn’t rocket science..here comes the anti ai downvotes
RevLoveJoy@reddit
You may be getting anti AI downvotes? But the real deserved downvotes you're getting are for the security implication. Perusing AD and server roles like that requires admin / root access. Giving that access to some AI slop one does not completely understand and then setting it lose on corporate AD and a presumably long list of user-required servers is incredibly irresponsible. Those are the downvotes you deserve, as you seem concerned about them.
PPRabbitry@reddit
Just to be clear. We're talking about a easily auditable script. Not some massive prod application that we're going to ship and make money from.
It takes "about an hour" to write it yourself. Debugging, running tests, etc. Or. It takes you 10 minutes to have AI poop out an acceptable piece of script, audit it, and inject your secret credentials.
30 minutes vs 3 hours.
It's a damn automation script, not a million dollar app.
To the collective: Get over your damn ego.
atbims@reddit
If you give AI access to your AD or servers just to write a script you're an idiot. If you are incompetent as far as PowerShell and cannot make sense of the script the AI spits out, then don't do this, and probably also don't copy scripts from internet strangers either because you don't know what you are doing.
If you know PS basics but maybe not so familiar with specific syntax and all the AD commands, getting AI to write the basic script and then you read, test and tweak it makes a lot of sense.
Obviously don't run the script if you don't know what it does, if you needed that part to be said out loud just quit your job, you're not qualified.
nicolaj1994@reddit
I think you misunderstood. AI creates the script and you run it..
But I guess it's ok if some random dude on the internet sent you the script instead of the AI ?
Emergency-Map-808@reddit
Yes as typically in the community the scripts will have been vetted and also used for a long period of time
RansomStark78@reddit
Me too
sxspiria@reddit
Me three
jstuart-tech@reddit
Why would you have month and year.... Just seems like your making OU's for the fun of it. Make a disabled users OU and call it a day....
Does nobody know AD anymore 😞
CraigAT@reddit
So they know when it was disabled. But maybe that could be sent along with the DN instead.
xCharg@reddit
Why reinvent the wheel though, each user object has accountExpires property - set that. Don't even need to disable account but of course could do both.
It's much easier to then parse that data with other scripts and not care about building logic around OU names and such. And have the at all to begin with.
thomasdarko@reddit
Put the time and date in the description
SenTedStevens@reddit
What i did with disabling accounts was start with creating a variable, say $DateDisabled, that got the current date when the script auto ran. Then it would look for user accounts in an OU with LastLoginDate more than a certain number of days, disable the account, then use Set-ADUser to put a line on the description field, "Disabled $DateDisabled due to inactivity."
Pocket-Flapjack@reddit
I only log the DN because there are about 20 project OUs.
Much easier to restore them to the right place if I have the DN.
Pocket-Flapjack@reddit
I completely delete them if theyre unused for 6 months.
I manually delete them though, that feels too risky to automate.
Just a quirk of some of the networks I work on.
sonic10158@reddit
Even if you delete, you can recover them from ADAC. I don’t know off the top of my head how long they are saved there, but I have had to do that before
inept_adept@reddit
I would say it's best practice to not immediately delete for audit purposes.
Dense-Error-871@reddit
I’d hire the other guy over you any day. Bring me your scripts. What have you made?
society_victim@reddit
Just put the “disabled on xxx” in the object description. Is what we do.
Pocket-Flapjack@reddit
Thats fair but this way I simply remove the OU and all its children after 6 months.
Rather than having to audit all the disabled accounts again.
dragery@reddit
Description starting with the datetime in sortable format. Then you can sort a single OU by the description (if you need to do things manually).
society_victim@reddit
We have scheduled scripts for that as well. If account disabled more then 6 months ago and is in “disabled users” delete.
Pocket-Flapjack@reddit
Yes! I think thats too risky for me so I didnt do it.
I manually delete them like a coward but it means I can see what im removing and make judgment call IF theres someone I shouldnt delete.
society_victim@reddit
You just said you remove the OU do you don’t need to audit again. I don’t see the difference. Also you should always have the AD recycle bin enabled, so worst case you restore it. If someone has been gone for 6 months they probably won’t need the acct anymore. And if they do it should surface well within the restore period so you can just restore it. You way is doable if you only have 1 domain to manage. If you have many it’s not doable.
Pocket-Flapjack@reddit
Yeah, so OU contains all users who were disabled that month.
In 6 months time everyone who needed their account re-enabling should have asked so the only accounts left can be removed.
I do have recycle bin but the current process works well enough.
PathMaster@reddit
That second script is honestly brilliant.
I too would love a copy of that. I might edit it slightly to include recording the MAC address. I dislike when vendors license a server via the MAC, moving hosts or having to do a restore breaks it. And then trying to recall what it was...
psychopompadour@reddit
My favorite vendor licenses by hard drive GUID or something and it drives engineering crazy that they can't put it in citrix (well, they COULD, but every install would have to be on a separate vm, so it wouldn't save us any money over just using old desktops that are at the office locations... luckily, the software doesn't require much in the way of resources, and multiple users can share an install, so we only need one per office).
themanbornwithin@reddit
Here's looking at you Autodesk
420GB@reddit
Using the description or "AccountExpires" (which is even a datetime/file time attribute) to record the date makes way more sense than abusing OUs.
OUs only exist for permissions delegation and GPOs. They should not be used as a replacement for object attributes.
martin8777@reddit
I have a script that spits out all the ad groups, entra groups, directory roles and licenses assigned to a user.
Have it automated in Freshservice so that when we get an off boarding or role change ticket, it runs that script, saves the output to Sharepoint and adds a note to the ticket with a link to the csv file.
Also have a similar one for shared mailbox access. Makes it so much easier for the tickets we get like "setup new user A like user B who just left"
nitroman89@reddit
I have an Ansible playbook that runs every Monday and emails me a list of VMware snapshots so they don't accumulate.
sk1nlAb@reddit
I've made a few. My favorite ones are optimization related, but before doing any optimization, killing all unnecessary processes, and reloading windows explorer afterwards. It'll also output pertinent data from event viewer logs before clearing them.
I tend to try this before simply rebooting because the script is faster and has a very high success rate.
Semt-x@reddit
im a AD migration/Entra speccialist.
From 2005 i wrote a (vbs) script that makes an inventory of AD, objects (OU,GPO.Users,Groups,Machines etc)
lots of details per object, it calcualted groupmembers recursively with circle nesting detection etc.
I used it for \~15 years to start AD cleanup / migrations.
from 2020 i made a similar inventory script but now in PowerShell for Entra, and included AD. most of the functionality form the old script I rewrote.
Still dumps all objects, but now can merges entra and AD , detects Hybrid objects. for users, groups and devices.
and app registrations ( and Service principal names) for Entra (including all app properties, like SCIM/Secret&ceters/Approle/APIPermissions).
Beside object it makes an inventory from Entra services, like entitlement management, PIM config, Conditional Access, license assignments. and includes some intune details aswel. So i can identify which users have what kind of managed laptop. one of the details i see per user is what kind of devices are used. ( personal mobile and managed laptop forinstance)
The script became a hobby, so not only add functionality but also optimize it for performance.
It gives me a huge advantage when i start a new assignment.
My script doesnt have Exchange details tho. last time i checked those details werent avaialbe using direct msgraph. i think i have another fo at it. (script doesnt use any powershell modules, no dependencies esceot for PS7 beccause of multithreaded routines).
The script is not in the background for me tho 😄
Xydan@reddit
Back when I was a sysadmin; I setup a script to help me enroll users in our Azure tenant using MSGraph. I was able to also assign them a mailbox and set their phone number for MFA.
Felt like a SWE but truthfully it should have been automated more; I still had to run the script and manually type everything in. Really helped when we onboard 10+ employees.
FarToe1@reddit
Mythtv renaming script - something like 20 years so far.
MythTv is an old linux dvr that I use to record freesat tv programs. It's intended to be used with its own player, but I didn't like that so wanted to watch the mp4 files using a normal video player, but myth saved the files with a unique ID so I couldn't see what was what.
I raised this as a feature request at the time, but a dev was extremely dismissing that anyone might want to do such a thing, that I had a "Sod you then" moment and did it myself.
Looked into the SQL, which at the time I didn't know much of. It actually turned out really simple to get the TV program channel and name for a given file and rename it into a human readable "Channel-Program-DateTime" string.
It ran perfectly for about 18 years before the kernel drivers for my DVB-S card stopped working with modern kernels, and by then, there wasn't much left on terrestrial I cared for.
https://github.com/digdilem/myth_rename
ARJeepGuy123@reddit
Oh the disk usage alert is a good one, I'm going to have to do that!
Over-Map6529@reddit
Lock_Screen.bat
thebigshoe247@reddit
Just hate pressing Windows key + L?
Over-Map6529@reddit
remote connections.
thebigshoe247@reddit
Can't you just lock your entire machine?
Over-Map6529@reddit
Not if you're running a remote app and need to secure it, but also not log out of the remote system. Is an issue for non RDP remote tools.
HDClown@reddit
Ctrl+Alt+End ?
Over-Map6529@reddit
Depends on the software used. RDP, yes. Many others, no.
AllergicToPecans@reddit
We did this and incorporated it into a GPO. Fewer concerns now with users walking away and not locking. We have some issues with execs but you just get them to sign off that they understand the risk and move on
spacepirate6@reddit
A lot actually. Getting ip addresses reservation from ip address, mac address, and by name/description. Remove reservations from dhcp, edit mac addresses, adding new reservations. Getting hyper v replication statuses, ntp reports etc. I am always trying to automate something.
landob@reddit
My very first script I ever made (well aside from the hello world one). Uptime. I just plug in a computers name and it fetches that computers uptime for me so I can see if the user actually rebooted
MNmetalhead@reddit
Keep in mind that if Fast Startup is enabled, this number will not be accurate.
landob@reddit
That's good to know in case I go somewhere else. But I know here I disabled it across the enterprise for some reason. It was causing some kinda issue.
svideo@reddit
25+ years ago, needing to rename a bunch of files I created a perl cscript "renre.pl" that allowed renaming via regular expressions (perl style, of course). Compiled that to renre.exe and have been copying that to new systems on each upgrade, still use it regularly.
rio_sk@reddit
Very simple aliases for cd to the most used directories from terminal root. Ctrl-t then cdwww or cdvhost etc etc...
chicaneuk@reddit
I wrote a script to install SQL Server as we do it semi-regularly.. just uses a bunch of cmdlets from dbatools and does a full install. Lets you specify editions, versions, drives / placement of files all as command line parameters and imports all our standard database maintenance jobs (reindexes, backups, etc etc) ... microsoft kindly haven't changed much over the last decade or so for installing SQL so have been able to keep it current with very minimal tweaks.
Entwisi@reddit
Many moons ago in prod support our login process for production servers was that you tried to login, it would prompt for a key or a new request which you had to supply ticket number, area you worked, description of the task being done and your email address
Which was an absolute pain when you had some services with 20+ servers
I wrote an autohotkey script/GUI that had a box for ticket and description and checkboxes for each service which then loaded a list of all servers on that service with checkboxes and a select all checkbox
Hit go and it would loop for each server selected, open putty and fill in a full request for each with title of window set to each server name
I would sit and wait the mgmt approval mails and a highlight of the two lines with servername and access key, hit f8 and it would pick the right putty window repeat the request and paste the key
On 20 servers I would be in and working inside 15 mins when collegues who refused to use it would take anything up to an hour which was often called out on the bridge calls and in their 121s
Autohotkey is ace for getting rid of repetitve tasks and even common commands
One other donateware I found back in the days of ms communicator saved all conversations in a year/month/date folder structure as text files named by user. I had all conversations going back 10 years and being able to quickly find the conversation and pull any transcripts in minutes. This saved my arse on multiple occasions each one I threw enough for a coffee to the author as thanks
CyberRedhead27@reddit
ConnectTo-SSH Simple script, it checks a keypairs folder and it it finds a keypairs that matches the server name, it connects using that. Otherwise, just SSH to the server. Because I don't want to remember which servers use keypairs and which don't.
KarmicDeficit@reddit
You don’t need a script for that. In fact, all you need is
ssh username@server.SSH automatically tries all available key pairs until it finds one that works. If for some reason you don’t want it to do that, you can specify which key to use for which server in ~/.ssh/config.
castillar@reddit
Yes, but many servers have (or should have) an upper limit on the number of failed authentication attempts before they cut you off. More than once I’ve been scratching my head over a failed connection only to realize that SSH is trying a bunch of other keys that don’t work before it gets to the one that does.
As you point out, better to configure them specifically in a conf file. One trick I’ve been using is that SSH supports including additional conf files, so I have a ~/.ssh/config.d directory with groups of hosts (work, personal, lab, side-gig, etc.) all separated into individual files. Makes it easier to keep up to date!
kowaxuriskanfeti@reddit
I was using mp3 downloaders in browser for years which took hours to download songs from youtube because of ads, pop-ups, waitings and etc. Then I wrote some python script with ytlab libraries and help of AI. Since then I am doing hours of work in just the matter of minutes. Literally lifesaver.
idgarad@reddit
I wrote a calendar creator in Python 20 years ago to generate excel formatted calendars with custom holidays and events. I can still to this day point it at a sql server query to extract custom events, and add comments and notes for entries. I can pull from ServiceNow, JIRA, doesn't matter and it will build out a printer friendly excel document.
I wrote an executable WinRunner tool to every N minutes press X keystroke to a specifically named window. So for 25 years I use it for Outlook for a CTRL-M every 8 minutes to prevent my screensaver from kicking on.
420GB@reddit
Most of my scripts handle tasks that would simply be impossible if not scripted, so those have enormous impact but they do not save any time - because if they didn't exist the work or integration or functionality or whatever would simply not exist thus also not cause any work.
Some scripts also "save time" mostly for other departments and not for me or IT. I put save time in quotes because it's not really about saving time, it's about reducing the ridiculous 50% error or miss quota that we got when it was done manually. Many of our processes allow for enough time to do them by hand, but we couldn't deal with the inaccuracies and mistakes.
Other times we use scripts not to save time or reduce mistakes (although it's always a nice side effect) but just to be able to delegate the ability to perform some task within certain constraints and with certain checks in place to the helpdesk. AD delegation, PIM and custom Entra roles are nice but sometimes you just need even more granularity or safety checks. So we make something that's theoretically simple into a script and then delegate it to the helpdesk team so they can run it as a service user and perform said task even if their own user account(s) couldn't.
Basic scripts that just save myself or even IT colleagues time, I'm really hard pressed to think of anything. I guess the fully automated deployment of new machines, but that's only partially PowerShell.
TheLoko@reddit
Can you all please share those scripts?
dickg1856@reddit
Stop print spooler service, delete contents of folder c:/windows/system32/spool/printer/* restart spooler service
sonic10158@reddit
I wrote one that will update a user’s immutable ID between local AD and Entra, compare existing IDs to see if they need to be updated, and perform an Entra sync. Before I was working at this place, sites either didn’t have AD and Entra synced at all or were having to manually type each command in for each user to get them synced. Needless to say I was far too lazy to do all that, and I still use that script to this day. Other sites use my script too.
Also I put together a script to automatically disable a stale account after 120 days, then delete said account after 180. During one of our audits a couple of years ago, my site was the only one without stale accounts since everyone else manually managed them (or didn’t even bother)
FreakFromSweden@reddit
I have powershell script that monitors Sharepoint status and feeds it straight into Prometheus via windows exporter.
Crawl states, crawl durations, content sources, service applications, some usage things and some other bits. It is a bit of a hack job but feeding all this as metrics into prometheus have saved me hours over the last years.
6sossomons@reddit
Wrote a bash script that took 3 csv file exports from remedy. They were 1st, 2nd, last. Rule was simple: 1 look for the 3 files, they had to be named correctly AND that days date. Secondly it would parse the file and use the Remedy API to send a 1st/2nd/final email to essentially say "we solved your problem, can we close this ticket?" and send it from Remedy for first and 2nd. Last used sendmail to send it as the user to client and copy to ticket and then API close ticket.
Used all the ticket info, link to update, resolution content so everything was clean.
Took a day to write it, 3 days to test and confirm, day to document the whole process. Trained my teammates the next week... by end of month entire helpdesk had it. People were so behind they were getting write ups for not clearing their tickets. Some were weeks behind. They were the first ones to get it before managers found out. Once managers saw that trend, they started investigating and got it across the board, all levels.
Left that job and ran into a guy who turned into manager there years later. They were still using it. Still part of their on-boarding training on how to get it set up and use it. Only broke once when Remedy got an update and they had to tweak the API url.
Hours saved: thousands per year.
Money paid for making it: $0
EsotericalNinja@reddit
I work at a consultancy and on the first month of my job filing expenses I wrote a script that takes a bunch of PDFs, puts a document number on each one "expense 1", "expense 2", etc. and combines them into a single PDF, and attaches it to a draft email for sending. 14 years later I still run that script pretty much unmodified
RyeonToast@reddit
I got a small function in a module of other random stuff that searches all the DHCP scopes for a MAC address. I don't have to kick tickets back to ask for info just for the purpose of identifying the scope the device should be in. Nor am I searching through all the scopes to see if a thing moved.
dathar@reddit
I have an overengineered PowerShell script that used to sync certain groups and mirrored group members from OneLogin to Duo Admin because there wasn't really much there, at least ~5 years ago. It got dragged screaming and kicking when we switched IDPs. Then it also got adapted to do the same for Entra because you can't create a role group from the native integration.
This script is load-bearing.
kraeger@reddit
2018 - wrote a series of scripts to sync all printer properties across multiple servers using a CSV output from a "primary" server that synced to all of the "Secondary" servers. this allowed us to put all of our print servers behind an F5 VIP as a "print server pool"
2020 - wrote a tombstone script that does the following:
this allowed us to keep a much better record of which devices are being removed and when. it also allows us to have the last known LAPS to sign into the device locally if it ever shows back up and the BL export saved our asses after the Crowdstrike fiasco
I also use an old ISE mod called ISESteroids that allows me to create a script and launch it from a hotkey in ISE. i have scripts to recycle print server spoolers and has a calculated delay based on the CPU % to wait for it to drop to a reasonable number before moving to the next server, a script to find all locked office files in a given folder on our netapp and display their name, who has it open, whether it is write or read and the open file ID. i have another that I can close any of those files based on their file ID if needed. I have manual triggers of scheduled tasks for various systems we use (our AD sync with Teamviewer for example), and a bunch of other "daily use" scripts that are more than 1 liners.
the number of hours i have saved my team and my level 2 field techs is insane. we also have our printer deployments setup on an API backend and i wrote a WPF form powershell script to allow the level 2s to submit new printers, OUs and change requests to the API which, in turn, makes all of the mods based on the API. add, modify and delete are included. then there's a small, single endpoint script that sends the computer info to the API server upon login, processes the OU it is in, and returns the printers that need to be installed on that machine based on the OU. i also added a public docs text file that, if it exists, installs a printer (1 per line) for every user that logs into THAT machine instead of every one in the corresponding OU. so we use a single GPO to put that script on every endpoint and create the login task, and the API and local text file do the rest of the work.
not to mention the 100s of other scripts i have written over the years that manage an insane number of "5 second" tasks that we no longer have to manually do. i'm a big fan of powershell automation, in case you can't tell lol
Lammtarra95@reddit
dnscheck -- basically just looks up a domain (ip addresses, TTLs) on various public dns servers in order to monitor changes/migrations being propagated.
Even more basic and more useful -- a browser with links to the status pages of all the infrastructure and third party services we depend on. No need for a 2-hour incident conf call crawling through switch logs when you can see immediately it is Cloudflare's or Microsoft's fault. (Also to this sub and downdetector.)
Iliketrucks2@reddit
I spent the better part of a day building a script that I could point at our AWS org and get accounts then run arbitrary (ReadOnly) commands against the list, parallelized to run quickly. I can also give it a pattern to match, or accounts by name or number. It’s so handy to want to find something out and get an answer easily and quickly. The little framework saves me so much time.
we have 150 accounts across 5 organizations so it comes up regularly
i8noodles@reddit
PowerShell where i drop a username, email, employee number. basically anything that is a unique identifier into the script and it spits out the account information like username, email etc. when password wqs last set. active or disabled, locked or unlocked. any computers that are tied to the user.
option to expand on group policy for both user and computer
Affectionate-Cat-975@reddit
All my exchange ps commands
DesignerGoose5903@reddit
With all the API changes over the years I feel like I am spending more time just keeping scripts up to date than the issues they resolve, I don't really feel much of a need for a lot of personal scripts without anything on-prem anymore either.
Rockstaru@reddit
list_to_pythondoes exactly what it says - takes stdin of lines and spits it out in python list format, e.g. if I'm running something like this:$ cat fruits.txt Banana Apple Pear
I can pipe to
list_to_pythonand get this instead:$ cat fruits.txt | list_to_python ["Banana", "Apple", "Pear"]
Actually, as I'm writing this out, a small improvement occurs to me, I should have it take an optional parameter to include a var name/assignment:
$ cat fruits.txt | list_to_python fruits fruits = ["Banana", "Apple", "Pear"]
KarmicDeficit@reddit
I wrote a tiny New-Array cmdlet for PowerShell that does basically the same thing. So instead of typing out `"jdoe","joesmith","fred flintstone" | Find-ADUser`, I can instead just do `New-Array | Find-ADUser`, and then it interactively prompts to enter each item on a new line (enter on an emtpy line finishes it).
_Do_The_Needful_@reddit
A lengthy ETL process from a previous admin that involved running dozens of scripts and performing a bunch of manual checks on the data. It still took the old admin multiple days to process new datasets with his method.
Its the first thing I automated when I came onboard and now it takes about 5 minutes to setup, then processes all the data in 2 minutes and alerts on the checks.
I haven't told anyone, they still think it takes days for each new dataset, which buys me a lot of free time.
DenyCasio@reddit
In 2012 as a newby I was given the easy task of creating AS400/PKMS accounts. Many steps to do by hand but there were commands to automate portions of the account creation process as I came to learn.
We were expecting an influx of 400 employees for the summer in the warehouse. I wonder who was assigned that job?
I wrote an external GUI in c# to open AS400, login, create the account, switch context to PKMS, create the account there, export the account information to the approved password sharing solution, and draft the email to the manager (via AD lookup) the task was complete.
14 years and two acquisitions later, they still use it, and reversed it to be used for the parent company systems too. My most successful program, built because I was given the time to explore my interests as a teenager.
Shout out to the asshat Tom in the distribution center for sending all 400 created account passwords in a mass email to those 400 employees. I extended the program to handle that password reset situation too.
In 2013 I extended it to handle the regular audit requests.
If you knew what you were doing in the system it took about 5 minutes, with the program it was about 20 seconds per account.
HayabusaJack@reddit
I have an entire script library where a bunch of things are checked. It also queries servers to keep the inventory updated as the inventory creates the Ansible host files which are used to make sure servers maintain their ‘cow’ status :)
jamiro11@reddit
We implemented a new IAM tool, and needed to migrate 13000 accounts.
All accounts needed to be created, added to the correct groups and be e-mailed with log in instructions and some basic onboarding stuff.
This system has no way of doing bulk import/export actions over the UI.
We were handed the new system, an excelsheet with all the accounts and info, anf were told to do it by hand.
I said fuck it, created a script which loads the excel, tranforms the data into json and injected it over the API, and then send automated e-mails.
I have since adapted it, made it a proper service with a webapp UI (django) and proper authentication, deployment pipelines etc.
Next up is adding more modules for ohr other applications, making it a central hub for our support team.
Saved thousands of hours of manual work, and discoverd i really enjoy building tools like these which makes peoples libes a lot easier
sstorholm@reddit
I wrote an Ansible playbook that updates Debian boxes after getting tired of doing it manually. Probably has saved me 24 hours per year. Another good one is a playbook that copies a deb-file to the box, installs dependencies, installs the deb and then runs arbitrary commands to configure it. The trick I've found is to write all scripts as modularly as possible, that way after a couple of years you have all the modules needed for whatever you need to do, just cobble them together to get whatever you want done.
dragery@reddit
I have a large powershell toolset I've developed over the years. One of the biggest time savers is one that parses email addresses from my clipboard (it can be paragraphs of text with email addresses strewn throughout) resolves the AD user object, and adds them to a group. If you don't specify the group, it asks for input, wildcard searches, presents a list of groups, and you select the number for the corresponding group to add them too.
When people submit requests with a bunch of email address, it's just highlight, copy, run command, select group, done. Also have a version that does our EmployeeIDs as well. It has a parameter for domains to parse too, with our org's domains as the default, but you can add additional.
Cak2u@reddit
I wrote a little .bat file that simply opens all of our printers in a new web browser window so I can log into each to add a user. Beats having bookmarks for like 12 printers' ips.
LakeSuperiorIsMyPond@reddit
My login script, checks crowdstrike is running, checks what Wi-Fi ssid you're on and if it's not the one with AD that you should be on, switches it, checks mapped drives and fixes any that aren't there, checks your vpn string settings for the Cisco client and replaces your settings if they are incorrect, checks 8 different app versions like chrome against my published "safe" version and if your version is less than, drops a text file named $computername.txt with chrome, in it, appending to existing contents in case there's other apps, where a watchdog on a server parses through it and triggers pdq deployments for those apps on your computer... It does a few other things like flushes your temp dirs and stuff.
RansomStark78@reddit
I have a cmd ping avg log script
Works all the time. The paid monitoring misses stuff.
spookyelbert8@reddit
wrote a python script that pulls license usage from our management console and emails a breakdown to finance every friday, caught like two dozen unused seats we were paying for and basically paid for itself in the first month, now it's just background noise that occasionally saves us from over-provisioning
project2501a@reddit
ldapwhois() bash function: looks up a person on AD via email or name. requires kerberos ticket.
saved me a bunch and i'm able to re-use it in tools like Posit Workbench that do not have full ldap integration
finallygrownup@reddit
I feel the /var/log so much. Our Oracle box decided to go nuts logging nonsense. Luckily our DBA was paying attention. I need to write that script. It sounds like a fifteen minute job I need to do today. 😝
Thijscream@reddit
Wrote a script to integrate CyberArk privile cloud with RoyalTS, load all your safes accounts and servers in there and work natively in RoyalTS to do all your work, also the authentication is triggered through it so never need to visit the web interface. Really appreciated by my colleagues. Only have to rerun the script if they have new servers they need a connection to. Currently only doing windows and Linux servers, soon the rest will follow. Also have a lot of automation build in to insert commands that are commonly used within the orgs environment.
Material-Water-9610@reddit
I have a rmm script on syncromsp that creates a temp admin account with a random password and outputs it to console, it's active for a max of 30 mins, but then is disabled by another script that auto runs every x time. Sure I can use laps for some customer or other methods but this has helped speed up tickets and provide users with temp admin once I trust them or know it's only for a specific task and it costs £0.
I have the same for macos too. But I do alot of that via mosyle
ComprehensiveBuy675@reddit
Two, one that sends new users an email with a welcome doc explaining how to connect to printers, drive letters, using desk phones, and contacting IT. And another that dumps user profiles off end points once the termination is processed.
fdeyso@reddit
Nagios custom monitors via PS. For hyperv/failover/csv metrics and a lot of other small bits that are useful in our environment.
AllergicToPecans@reddit
Nagios for the win. Really powerful once you incorporate PS and other tools.
mrbiggbrain@reddit
I wrote a script about 5 years ago that automates some software setup and configuration. The process took runs 2 hours per computer plus some extra time for every user past the first for shared computers. It now takes around 2 minutes to run with zero touch time beyond running it. It took around a week decently dedicated. It has now saved over a collective 5K hours in that time. I don't even work there anymore and it's still adding value.
I wrote a script two years ago the looks at AWS Workspaces and makes sure people are using them, then sends warnings or terminated them depending on how long it has been. It has saved the company closet to $2M, with just my time to initially set it up. It keeps adding value every day.
I wrote a small web application for a company a few years ago. It filled a requirement for DR to allow users to spin up their own AWS Workspaces in a DR event. I finished that script in 2018. Not counting the pandemic, the company got a decrease in insurance premiums of around $5M/YR for the level of automation around that DR process, meaning I contributed to around $40M of savings over these 8 years.
There is a script I wrote that moves old files to slower storage and puts a shortcut to them in the original location. It's still used 12 years later and has been running non-stop since I put it in with only minor updates.
Its kind of funny to think of the hundreds of scripts I have still running in some capacity, and the hundreds more that are no longer relevant.
8008seven8008@reddit
The manual sync between AD and Azure
fdeyso@reddit
Would you mind sharing it?
PhoenixHeart86@reddit
Here is ours for ADSync (Called something else now I think) if it helps!
```
# ============================================================
# Manual Azure AD Connect Sync Script
# Run from the AD Connect server or with remoting enabled
# ============================================================
# 1. Define the AD Connect server to target
$syncServer = "ADSyncServerName"
# 2. Verify the ADSync service is running on the target server
$svcStatus = Invoke-Command -ComputerName $syncServer -ScriptBlock {
Get-Service -Name "ADSync"
}
if ($svcStatus.Status -ne "Running") {
Write-Error "ADSync service is not running on $syncServer. Aborting."
exit 1
}
Write-Host "[OK] ADSync service is running on $syncServer" -ForegroundColor Green
# 3. Import the ADSync PowerShell module on the remote server
Invoke-Command -ComputerName $syncServer -ScriptBlock {
Import-Module ADSync
}
# 4. Trigger a Delta sync cycle (syncs only changes since the last run)
# Use PolicyType "Initial" instead to force a full sync of all objects
Invoke-Command -ComputerName $syncServer -ScriptBlock {
Start-ADSyncSyncCycle -PolicyType Delta
}
Write-Host "[OK] Delta sync cycle initiated on $syncServer" -ForegroundColor Green
# 5. Poll the sync status until the cycle completes
Write-Host "Waiting for sync cycle to complete..."
do {
Start-Sleep -Seconds 10
$syncStatus = Invoke-Command -ComputerName $syncServer -ScriptBlock {
Get-ADSyncScheduler
}
Write-Host " Sync busy: $($syncStatus.SyncCycleInProgress)"
} while ($syncStatus.SyncCycleInProgress -eq $true)
# 6. Report the last sync time and next scheduled run
Write-Host "`n[Done] Sync cycle completed." -ForegroundColor Green
Write-Host " Last sync : $($syncStatus.LastSyncRunTime)"
Write-Host " Next sync : $($syncStatus.NextSyncRunTime)"
```
painted-biird@reddit
Not sure if it’s what they’re talking about, but the one I wrote is a pretty simple function that combines the ad sync sync command and repadmin. I’m on my phone so don’t recall it offhand but it should be easy enough to replicate by asking Claude or ChatGPT to make for you.
society_victim@reddit
I think he just means start-adsyncsynccycle -policytype delta
fdeyso@reddit
Ahh i thought a bit more complex.
8008seven8008@reddit
No, nothing complex just a click-and-sync in the desktop. But it’s the “script” I’ve had for years and used quite often.
QuantumDiogenes@reddit
Start-ADSyncSyncCycle -PolicyType Deltais what I used to manually syncbobdobalina@reddit
my git-init scripts
it took me long enough to learn git and even longer for me to do it API keys.
The script takes a config file of vault ids and pulls them from my bitwarden secrets manager and loads them into my enviroments variables. Works in bash and pwsh. With my github keys configured it initializes both a local repo and connects that to github and does an initial commit/push and wires up all the settings without leaving the API keys in the configs. Or it just pulls a repo from gh and configures it so I can get to work.
Basically create and configure a new repo, pull and configure an existing one, or load all my keys so I can push updates to the one already configured here in my \~/src/ directory
foldedturnip@reddit
I work for a security msp and I have a python script that will go through all the spreadsheets we use for bringing sites online and properly label and configure the remote monitoring platform we use. This is such a big time saver especially on larger 500+ device sites.
society_victim@reddit
Automatic on & offboardings are the real time saver.
Jeanine_s@reddit
Script to turn shadow copies on for our support team. (We usually get a server to install the erp on from our smb customers, the times they fucked up something and/or the backups…)
Vicus_92@reddit
Weirdly, it's custom shortcuts via an auto hotkey script.
Open or focus specific windows, open a PowerShell cheat sheet, type my full email address and most importantly, type the content of my clipboard.
Last one is awesome for fields that don't accept a traditional paste command. Like a login screen on devices I connect to via RMM
FormerlyGruntled@reddit
I put together a powershell GUI that handles most of my helpdesk stuff, and works across the team. PC lookups, common fixes, AD user pulling, a few email templates. Does a script count, if it's a gui?
dragzo0o0@reddit
2014 -
Script that checks if a pc is online and if it is, gets info about the pc, bios version, connected monitors logged on user, retrieves a bunch of info about that user from ad (incl mgr) last password reset date etc.
When the pc was last restarted, whether there’s patches awaiting installation and a bunch of other things.
Gives you options to force the updates to install, do go updates and a few other things.
Our service desk still use it afaik
AffekeNommu@reddit
Automation scripts in PowerShell that run under scheduler. Fetching from APIs, writing to databases, removing stale objects from AD, etc. They continue to run and make life easier for the team.
Greerio@reddit
I’ve written a couple. One checks to ensure our end user guides have the most recent version published once per week. Another that removes users from all of their 365 groups.
corsair130@reddit
Wrote a powershell script that collects all of the reports spit out of our payroll system, renames all the PDF files to the proper report names + dates, loads all of them into pre-designed emails with dynamic text for the dates with all the recipients ready to go. The emails pop up in Outlook and I click send. This saves me about 10 minutes of manual work twice a month. It also reduces errors.
ITCareerSwitcher@reddit
We label all of our devices and fiber jumper cables using a standard format. I wrote a python script to accept a csv with information about the device or fiber connections and it spits out a csv with the information that our label printer can use to bulk print the labels.
Previously we were hand-typing the labels on a label printer; which is fine for onesie/twosie applications, but for a building with 6 stacks of 4 switches each and two dozen or so connection points, multiplied by dozens of similar-sized buildings it’s saved a ton of time.
paleologus@reddit
I wrote a batch 15 years ago to create a standard email signature for Outlook that pulls the information from AD. I also have batch installs for all of our software so I can setup a new PC in a few clicks and I don’t have to keep and maintain multiple workstation images.
Erutan409@reddit
PS script that manages the fan speeds on my R610 Dell PowerEdge via the iDRAC controller. Necessary for a home lab.
drunkcowofdeath@reddit
I wrote a quick binary search function in powershell to use when I need to sync up two different directories of users, which happens pretty much all the time. It runs so much faster than built in powershell tools
Mysterious-Print9737@reddit
We've found the best automation is the scripts that target human error and blind spots like auditing orphaned licenses or monitoring log directories before they trigger an outage in the middle of the night. More specifically, we have a script that targets Stale Active Directory Computer Objects. It runs monthly, queries the domain for machines that haven't updated their machine password or checked in for over 90 days, disables them, moves them to a stale OU, and drops a report into a Teams channel. Before automating this, clean-ups were a tedious manual task usually ignored until an internal audit loomed but now, it keeps our AD environment clean and makes sure forgotten endpoints aren't sitting out there acting as potential entry points for attackers.