Blog

Blogging on programming and life in general.

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

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.”

blog comments powered by Disqus
;