Eliminate Repetitive Tasks Through Automation Using AI-Generated Scripts

Eliminate Repetitive Tasks Through Automation Using AI-Generated Scripts

Have you ever found yourself bogged down by tedious computer tasks? You’re not alone! The good news is that with a little assistance from artificial intelligence (AI), you can streamline and automate your Windows tasks using PowerShell scripts, freeing up valuable time for more important activities.

PowerShell Overview: Your Automation Ally

PowerShell serves as both a powerful command-line shell and a comprehensive scripting language embedded in Windows, providing remarkable administrative and automation solutions. According to Microsoft, it’s a tool that can transform how you manage tasks on your computer.

PowerShell Interface

With PowerShell, you can craft scripts—self-sufficient files filled with commands and instructions—to automate everything from basic file management to intricate system operations.

For those new to scripting, numerous pre-written PowerShell scripts are available online. For instance, the PowerShell Scripts Repository features over 500 free scripts designed to assist with various tasks, including monitoring drive space, listing installed programs, and organizing photos by creation date.

While these ready-to-use scripts are valuable, the true potential of PowerShell lies in your ability to create tailored scripts suited to your specific requirements—this is where AI becomes a game changer!

Leveraging AI to Generate Custom PowerShell Scripts

Imagine needing to organize thousands of files recovered from a damaged hard drive. Rather than spending hours mastering PowerShell syntax or scouring for the ideal pre-existing script, I employed ChatGPT to whip up a custom script.

For my specific need—sorting various types of files (like images, audio, and documents)—I crafted a clear, concise prompt for the AI:

AI Prompt for PowerShell

Here’s what I made sure to include in my AI prompt:

  • Instructions for handling files that don’t fit any categories.
  • The exact task of organizing files by their extensions.
  • A breakdown of categories and file types for each group.

The AI quickly generated an effective PowerShell script that tackled my file organization task:

# 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 existforeach ($category in $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. CountWrite-Host "Starting to organize $totalFiles files..." # Process each fileforeach ($file in $files) { $extension = $file. Extension. ToLower() $targetCategory = "Other" # Determine which category the file belongs to foreach ($category in $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 } Move-Item -Path $file. FullName -Destination $targetFile $movedFiles++ # 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."

Automating Your PowerShell Scripts with Task Scheduler

The magic of AI-generated PowerShell scripts doesn’t end at creation; they can also be set to run automatically, eliminating the need for human intervention!

Since I often overlook breaks during my long computer sessions, I created a script that alerts me to take short breaks. Once again, I utilized AI to generate this reminder script with a straightforward prompt:

AI Prompt for Break Reminder

The resulting PowerShell script was perfectly tailored to my needs:

# 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 -Seconds 12 $notification. Dispose() } # Display an initial notification Show-BreakReminder Write-Host "Break reminder displayed. Set this script to run hourly using Task Scheduler."

Now that I had the script, I set it to automatically execute every hour through Windows Task Scheduler. Here’s how:

Task Scheduler Basic Task

Firstly, I saved my AI-generated script as a.ps1 file and accessed Task Scheduler via the Start Menu. I proceeded to create a new basic task with a daily trigger.

Edit Trigger in Task Scheduler

I modified the trigger settings to run the task hourly. After locating my task in the Task Scheduler Library, I right-clicked it and selected Properties. In the Triggers tab, I clicked Edit, checked the Repeat task every: option, and set the interval to 1 hour. I also selected Indefinitely under duration and saved my changes by clicking OK.

Trigger Properties in Task Scheduler

Next, I adjusted the action settings in the Properties window by navigating to the Actions tab and clicking Edit. For the Program/script field, I input powershell.exe rather than the direct path to my script. In the Add arguments field, I used -ExecutionPolicy Bypass -WindowStyle Hidden -File "C:\Users\David\Desktop\eye-saver.ps1", which covered both execution policies and the complete path to my script.

Eye Saver PowerShell Script Setup

After saving these settings, I finalized the Properties window by clicking OK twice. The outcome? A seamlessly running reminder that boosts my productivity while reducing eye strain!

The beauty of employing AI in creating and automating PowerShell scripts is the remarkable efficiency it introduces into your daily routine. With these simple commands, you’re not just fostering a better workflow, but also empowering your computer to do the work for you silently in the background.

All images and screenshots are credited to David Morelo.

Frequently Asked Questions

1. Do I need programming knowledge to create PowerShell scripts?

No, you don’t need extensive programming knowledge. With AI tools like ChatGPT, you can generate scripts by simply describing what you want, making it accessible for everyone.

2. How can I run my PowerShell scripts automatically?

You can schedule your PowerShell scripts using Windows Task Scheduler. This allows them to run at specified intervals, automating your tasks without further action from you.

3. What if my AI-generated script doesn’t work as expected?

It’s common for initial scripts to require adjustments. Review the generated code, ensure your paths are accurate, and tweak any parameters. Don’t hesitate to consult PowerShell documentation for troubleshooting!

Source & Images

Leave a Reply

Your email address will not be published. Required fields are marked *