How can I create a script to open a random folder?

July 11, 2025 3 answers
Asked by 2 spoons of cocoa
Hey everyone! I'm just starting out with coding and I want to write a script that selects a random folder within a specified directory—in my case, E:Games. The idea is to run this script and have it open one of the folders in that directory. I've made some progress on the script, but I'm struggling with how to actually execute it from my desktop and have it run automatically. Here's what I've got so far: ```powershell $parentPath = "E:GamesGAMES" $folders = Get-ChildItem -Path $parentPath -Directory if ($folders.Count -eq 0) { Write-Output "No subfolders found in '$parentPath'." return } $randomFolder = $folders | Get-Random Invoke-Item $randomFolder.FullName ```

Answers

all-weather tires
You can use the Get-Random cmdlet to pick a folder. Just make sure to point it to the right directory. The script you've shared is pretty close! If you want it to execute automatically from your desktop, you can create a shortcut to the script file and set it to run with PowerShell when you double-click it.
Reply to this answer
YARD SALE
What have you tried so far? Have you run the script in PowerShell? If the script opens but doesn’t pick a random folder, you might want to check your path or add -Recurse only if you're okay with including subfolders. Here's a simple line to execute it directly: ```powershell start powershell.exe -File "C:PathToYourScript.ps1" ```
Reply to this answer
squid jig
For running a .bat file that opens PowerShell, your batch script could look something like this: ```bat @echo off start powershell.exe -File "C:PathToYourScript.ps1" ``` This way, when you run the .bat file, it will launch PowerShell and execute your script!
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions