πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English | πŸ‡ͺπŸ‡Έ EspaΓ±ol | πŸ‡΅πŸ‡Ή PortuguΓͺs | πŸ‡ΉπŸ‡­ ΰΉ„ΰΈ—ΰΈ’ | πŸ‡¨πŸ‡³ δΈ­ζ–‡

Let's Automate File Operations with PowerShell! A Super-Beginner's Scripting Guide

In the last article, we learned 10 useful cmdlets that form the basis of PowerShell. You've probably experienced how combining each powerful, object-returning command with the pipeline can make complex operations possible.

Now that you've learned the "words" (commands), it's finally time to move on to the step of combining them to create "sentences" or "stories"β€”in other words, creating a PowerShell script. A script, in a nutshell, is a "list of procedures for commands." Once you've made one, you can complete tedious, repetitive tasks with a single click (or a single command).

In this article, we'll take on specific scenarios that web creators often face in their daily work, such as "initial project setup," "cleaning up unnecessary files," and "simple backups," and explain from scratch how to automate them with super-beginner-friendly scripts. By the time you finish this article, you should have the power to create your own "magic wand"!


Getting Ready to Run Scripts: Changing the Execution Policy

Before you can create and run a PowerShell script (with a .ps1 extension), there's one preparation step. For security, Windows restricts the execution of scripts by default. Let's change this restriction so that you can safely run scripts that you've created locally.

First, open PowerShell as an administrator and check the current execution policy.

Get-ExecutionPolicy

It will probably display "Restricted." Change this with the following command.


Set-ExecutionPolicy RemoteSigned

RemoteSigned is a safe and balanced setting for developers, meaning "scripts created locally are OK to run, but scripts downloaded from the internet are NG unless they have a signature from a trusted publisher." When the confirmation message appears, type "Y" and press Enter. You only need to do this setting once.


Practical Example 1: Automatically Generate an Initial Web Project Structure

When you start creating a new website, it's a bit of a pain to manually create folders like `images`, `css`, and `js`, and an `index.html` file every time, isn't it? Let's create a script, `New-Project.ps1`, to automate this task.

Script Content

Paste the following code into a text editor and save it with the name `New-Project.ps1`.

# Use the first argument passed at script runtime as the project name
$projectName = $args[0]

# Create a directory with the project name
New-Item -Path ".\$projectName" -ItemType Directory

# Move into the created directory
Set-Location -Path ".\$projectName"

# Create subdirectories all at once
New-Item -Path ".\images" -ItemType Directory
New-Item -Path ".\css" -ItemType Directory
New-Item -Path ".\js" -ItemType Directory

# Create template HTML and CSS files
New-Item -Path ".\index.html" -ItemType File
New-Item -Path ".\css\style.css" -ItemType File

Write-Host "Project '$projectName' is ready!" -ForegroundColor Green

Running the Script

In PowerShell, navigate to the directory where you saved the script and run the following command. The `./` signifies the current directory.

./New-Project.ps1 "MyNewSite"

Verifying the Result

After running it, let's check the contents with `Get-ChildItem`.

Get-ChildItem -Path ".\MyNewSite"

A folder with the specified name and all the necessary subfolders and files inside it should have been created in an instant. Now you're free from the tedious initial setup!


Practical Example 2: Automatically Clean Up Old Downloaded Files

Next, a slightly more advanced script. Let's think about a script that automatically finds and deletes old files in the "Downloads" folder that are older than 30 days.

Script Content (Safe Confirmation Mode First)

Since deleting files immediately is risky, let's first create a safe version that only displays which files *would* be deleted if it were run. The key is to add the -WhatIf switch to Remove-Item.

# Path to the folder you want to clean
$targetFolder = "$HOME\Downloads"
# Delete files older than how many days
$days = 30
# Calculate the cutoff date
$limitDate = (Get-Date).AddDays(-$days)

Write-Host "Searching for files older than [$limitDate] in [$targetFolder]..."

# Use -WhatIf to perform a "simulation" of the deletion
Get-ChildItem -Path $targetFolder -File -Recurse | Where-Object { $_.LastWriteTime -lt $limitDate } | Remove-Item -WhatIf

When you run this script (saved as `Clean-Downloads.ps1`, for example), it will only display a list of the files that would be targeted for deletion, like "What if: Performing the operation "Remove File" on target...", without actually deleting anything.


The Final Version of the Script (Actually Deletes)

Once you've confirmed with -WhatIf that the correct files are being targeted, it's time for the version that actually deletes. Remove -WhatIf and, for friendliness, add -Verbose instead to display which files were deleted.

# (Previous code omitted)
$limitDate = (Get-Date).AddDays(-$days)

Get-ChildItem -Path $targetFolder -File -Recurse | Where-Object { $_.LastWriteTime -lt $limitDate } | Remove-Item -Force -Verbose

-Force is an option to forcibly delete read-only files as well. With this, your periodic file cleanup is complete with a single command.


Practical Example 3: Backing Up a Specified Folder to a Dated ZIP File

Finally, a script to automate the important task of backing up for web creators. It compresses a specified folder into a ZIP file that includes the date and time of execution in its name.

# The folder you want to back up
$sourceFolder = "C:\path\to\your\project"
# Where to save the backup file
$destinationFolder = "D:\backups"

# Get the current date and time in yyyyMMdd-HHmm format
$timestamp = Get-Date -Format "yyyyMMdd-HHmm"
# Decide the name of the ZIP file to save
$zipFileName = "project-backup_$timestamp.zip"
$destinationPath = Join-Path -Path $destinationFolder -ChildPath $zipFileName

# Compress the folder and back it up
Compress-Archive -Path $sourceFolder -DestinationPath $destinationPath

Write-Host "Backup complete: $destinationPath" -ForegroundColor Green

By running this script, you can easily create a backup with a clear name, like project-backup_20250706-1130.zip.


Conclusion

This time, we introduced the basic way to write PowerShell scripts and three practical examples of automation scripts that are useful in web development. How did you find it?

By turning these manual tasks into scripts, you can reduce mistakes, save time, and focus on more creative work. The trick to creating scripts is to "break down the steps you do manually into individual cmdlets and write them out." We encourage you to try creating your own scripts to automate the "tedious tasks" around you.

The world of PowerShell is still very deep. In the next article, we'll do a thorough comparison, with diagrams, of the differences between PowerShell and the good old (?) Command Prompt, which many people often confuse!

Let's Compare and Understand the Differences Between PowerShell and cmd [With Diagrams]