Automate Repetitive Tasks via AI-Generated PowerShell Scripts
I’ve repeatedly said that computers must work for us, not the other means roughly. This was until I recognized myself investing innumerable hours on brainless work. This was until I launched utilising faux expertise (AI) to seamlessly version PowerShell scripts for to automate my Windows work.
PowerShell 101: Job Automation for Windows
PowerShell is both a command-pitch upwards pill and also scripting language designed into Windows that makes it feasible for effective unit management and also automation capacities, as Microsoft defines.
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 35
In strategy, you can version scripts (self-had files containing commands and also instructions that can be moved out instantly) that perform every little thing from mere file operations to expansive unit management work.
There are innumerable with one voice set-rendered PowerShell scripts digital that can snatch care of widespread work. For example, the PowerShell Manuscripts Repository contains over 500 emancipate scripts for work that array from taking care of unit placements to automating file operations. You can develop scripts that review drive suspension, list mounted software program, and also also organize images by day.
Yet while premade scripts are convenient, the real power of PowerShell is unlocked once you version custom scripts custom to your offbeat last opportunities, and also that’s where AI comes in.
Using AI to Incarnation Tradition PowerShell Manuscripts
Let me define how I version PowerShell scripts to automate taskks without literally evaluating PowerShell, utilising AI on a convenient example.
I recently reclaimed a ball of wax of information utilising PhotoRec from a failing drive. However, I expired upwards via thousands of miscellaneous files in a single brochure, and also going wearing them was a plight. To render things a minuscule bit less complex, I longed to instantly kind this jumble of files into major genres, pick images, solid, files, and also so on.
Instead of investing hours situating out PowerShell phrase delicacy or combing for the gorgeous pre-rendered script, I revolved to ChatGPT via a transparent summary of what I essential. Under’s how I prompted the AI:
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 36
The pivot admires I rendered sure to involve in my expeditious were:
What must happen via files that don’t suit my genres
The specific job I longed to full (plunking together files by extension)
The details genres and also file conglomerations for each genre
Of program, I underlined the fact in my AI expeditious that my nondiscriminatory was to version a PowerShell script (as condemned to, let’s say, a Revelry script) at the awfully prelude.
Within seconds, the AI collected this PowerShell script to automate work for me:
# Define the source folder as the current directory where the script is executed $sourceFolder=$PSScriptRoot
# Define category folders and their associated file extensions $categories=@{ "Images"=@(".jpg",".jpeg",".png",".gif",".bmp",".tiff",".webp",".svg",".ico",".raw",".cr2",".nef",".heic",".psd",".ai",".eps") "Documents"=@(".pdf",".docx",".doc",".txt",".rtf",".xlsx",".xls",".pptx",".ppt",".odt",".ods",".odp",".md",".csv",".json",".xml",".html",".htm",".log",".tex",".epub",".mobi") "Audio"=@(".mp3",".wav",".aac",".flac",".ogg",".wma",".m4a",".mid",".midi",".aiff",".alac",".ape",".opus",".amr",".au",".voc") "Video"=@(".mp4",".avi",".mov",".wmv",".mkv",".flv",".webm",".m4v",".mpg",".mpeg",".3gp",".3g2",".ts",".vob",".ogv",".divx",".asf",".rm",".rmvb") "Archives"=@(".zip",".rar",".7z",".tar",".gz",".bz2",".xz",".cab",".iso",".tgz",".tbz2",".lzh",".dmg",".pkg",".deb",".rpm") "Code"=@(".py",".js",".html",".css",".java",".c",".cpp",".cs",".php",".rb",".go",".swift",".sql",".ps1",".sh",".bat",".vbs",".ts",".jsx",".r",".pl",".lua") "Executables"=@(".exe",".msi",".app",".apk",".dll",".bin",".com",".jar",".gadget",".wsf",".appx",".appxbundle") "Other"=@() }
# Create category folders if they don't exist foreach($categoryin$categories.Keys){ $categoryPath=Join-Path-Path$sourceFolder-ChildPath$category if(-not(Test-Path-Path$categoryPath)){ New-Item-Path$categoryPath-ItemType Directory |Out-Null Write-Host"Created folder: $category" } }
# Get all files in the source folder (non-recursive) $files=Get-ChildItem-Path$sourceFolder-File|Where-Object{$_.Name -ne$MyInvocation.MyCommand.Name }
# Counter for moved files $movedFiles=0 $totalFiles=$files.Count
Write-Host"Starting to organize $totalFiles files..."
# Process each file foreach($filein$files){ $extension=$file.Extension.ToLower() $targetCategory="Other"
# Determine which category the file belongs to foreach($categoryin$categories.Keys){ if($category-eq"Other"){continue} if($categories[$category]-contains$extension){ $targetCategory=$category break } }
# Move the file to the appropriate category folder $targetPath=Join-Path-Path$sourceFolder-ChildPath$targetCategory $targetFile=Join-Path-Path$targetPath-ChildPath$file.Name
# Check if target file already exists and handle accordingly if(Test-Path-Path$targetFile){ $baseName=[System.IO.Path]::GetFileNameWithoutExtension($file.Name) $newName="$baseName`_$(Get-Random)$extension" $targetFile=Join-Path-Path$targetPath-ChildPath$newName }
# Show progress $percentComplete=[math]::Round(($movedFiles/$totalFiles)*100,2) Write-Progress-Activity"Organizing Files"-Status"$movedFiles of $totalFiles files processed ($percentComplete%)"-PercentComplete$percentComplete }
Write-Host"File organization complete! Moved $movedFiles files into categories."
As you can browse through, the totality code is nicely commented, so it’s literally probable to educate what borrower percentages are lugging out via relative relieve, which is nice if you would pick to develop out PowerShell and also perform manual tweaks yourself.
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 37
To turn this code into a usable script, I simply mimicked the totality code block from the AI chat and also opened upwards Windows Note pad (though any text editor would work with one voice correct).
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 38
After pasting the code, I conserved the file via a descriptive moniker and also the .ps1 extension (pick “organize-files.ps1”). I presented this script straight in the folder via my reclaimed files and also ran it by correct-clicking on the file and also pick Dashed via PowerShell.
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 39
In undoubtedly no time, thousands of spread files were neatly organized into conducive folders.
Automating Your AI-Elicited PowerShell Manuscripts via Job Scheduler
Even much more detailed than a convenient AI-grown PowerShell script is one that will automate your Windows work without you owning to reckon about it!
I work on my computer system for long hours, and also I in some casings fail to remember to snatch goes against, which leads to eye apprehension and also agitation and also filched too lightly productivity. I desperate to version a script that would remind me to snatch orchestrate goes against at invariant intervals. Once anew, I revolved to AI via a transparent expeditious:
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 40
The AI immediately collected this eye-saving script:
# Script to remind user to take regular screen breaks
# Load required assemblies for notifications Add-Type-AssemblyName System.Windows.Forms
# Function to show break reminder notification function Show-BreakReminder { $motivationalMessages=@( "Time for a 5-minute break! Rest your eyes and stretch.", "Screen break time! Look at something 20 feet away for 20 seconds.", "Break time! Stand up and move around for 5 minutes.", "Your eyes need a rest! Take 5 minutes away from the screen.", "Productivity hack: A 5-minute break now will boost your focus!" )
# Select a random message $randomMessage=$motivationalMessages| Get-Random
# Create and configure the notification $notification=New-Object System.Windows.Forms.NotifyIcon $notification.Icon =[System.Drawing.SystemIcons]::Information $notification.BalloonTipTitle ="Wellness Reminder" $notification.BalloonTipText =$randomMessage $notification.Visible =$true
# Show notification for 10 seconds $notification.ShowBalloonTip(10000)
# Clean up after a delay Start-Sleep-Seconds12 $notification.Dispose() }
# Display an initial notification Show-BreakReminder
Write-Host"Break reminder displayed. Set this script to run hourly using Task Scheduler."
This script was specifically what I essential, yet I didn’t want to have to remember to rushed it by hand. Instead, I set it upwards to rushed instantly once an hour utilising Windows Job Scheduler.
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 41
Anew, I conserved the AI-grown PowerShell script as a .ps1 file, then opened upwards Job Scheduler from the Start menu and also grown a neoteric typical job via a daily activate.
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 42
After earning the typical job, I essential to equalize the activate placements for hourly masterstroke. In the Job Scheduler Library, I situated my newly grown job and also correct-clicked to pick Properties. I maneuvered to the Prompts tab and also picked Edit. In the Edit Trigger residence window, I frisked the Recur job every: recourse and also set the recur period to 1 hour. Under duration, I picked Indefinitely, then clicked OK to preserve these placements.
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 43
I also essential to adequately configure the reaction placements. In the Properties residence window, I maneuvered to the Commandments tab and also picked Edit. For the Syllabus/script field, I keyed in powershell.exe instead of the linear program to my script. In the Add debates field, I keyed in -ExecutionPolicy Bypass -WindowStyle Hidden -File "C:UsersDavidDesktopeye-saver.ps1", which involves both the masterstroke specifications and also the full program to my script.
Automate Repetitive Tasks via AI-Generated PowerShell Scripts 44
After earning these readjusts, I clicked OK to preserve the reaction placements, then clicked OK anew on the Properties residence window to finalize with one voice readjusts. The result was well worth the project!
The looker of this AI approach is that once you’ve develop a few automated work wearing PowerShell scripts, your computer system takeoffs massaging for you in the background, lugging out with one voice those minuscule encouraging nudges that given to necessitate you to remember or set external alarms.
If you’re intrigued in touring more PowerShell capacities for your automation assignments, review out our guide to pertinent PowerShell commands that every Windows user must construe. These commands kind the structure blocks of more expansive scripts and also will help you construe what’s taking place under the hood of your AI-collected automation.
With one voice images and also screenshots by David Morelo.
This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.