My First PowerShell Script - Moving Files From One Directory to Another

Published on
-
1 min read

Microsoft’s new command-line tool, PowerShell has been out for quite a few years now and I thought today will be the day I would start using it. I needed to write a script that would move n number of files from one directory to another. This job seemed a perfect fit for PowerShell.

#Get 'n' number of files
$FileLimit = 10 

#Destination for files
$DropDirectory = "C:\Drop\"

$PickupDirectory = Get-ChildItem -Path "C:\Pickup\"

$Counter = 0
foreach ($file in $PickupDirectory)
{
    if ($Counter -ne $FileLimit)
    {
        $Destination = $DropDirectory+$file.Name

        Write-Host $file.FullName #Output file fullname to screen
        Write-Host $Destination   #Output Full Destination path to screen
        
        Move-Item $file.FullName -destination $Destination
        $Counter++
    }  
}

From the get go, I was really impressed with the flexibility of the scripting language. This is where command line fails. It is sufficient for simple tasks but not so much for complex jobs.

As you can see from the code above, I can implement complex operations that supports variables, conditional statements, loops (while, do, for, and foreach), and that’s just the start. I don’t know why I hadn’t used PowerShell sooner. If I didn’t have the option to use PowerShell, I would have probably created a C# service or executable to do the exact same thing. Time saver!

Since PowerShell is built on the .NET Framework, Windows PowerShell helps control and automate the administration of the operating system and applications that run on Windows. So if you are a C# programmer, you should feel comfortable in writing PowerShell scripts. All you need to be aware of is syntax differences when declaring variables and keywords.

To end with, I will quote an amusing forum post I found when researching the difference between good ol’ Command Prompt and PowerShell:

PowerShell has a default blue background and Command Prompt has a default black background.”

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. I do get inundated with messages regarding my posts via LinkedIn and leaving a comment below is a better place to have an open discussion. Your comment will not only help others, but also myself.