Your basic ITPro blog... What's going on at work, what I'm interested in.

Friday, March 14, 2008

PowerShell Exercise

In case you haven't heard, Microsoft has a new Management Tool out. It's getting a lot of buzz!  :-)

The Scripting Guys (one of my favorite resources) post a script each day (or so). Most of these are in VBscript, from what I have seen.

As a daily exercise, I am translating their non-PowerShell scripts into PowerShell. I thought I would post my work here.

Please feel free to comment on my solutions. I am not spending a ton of time tightening them up. And, as a complete beginner, I am sure there are going to be better ways to do what I do. So, if you have comments, I would love to hear them.

With all of that said, here is today's script --

This script polls your computer for removable drives and copies files to that drive. This could be used to automate backups to a USB key or some such task.

Here is the Scripting Guys solution:

Const OverwriteExisting = TRUE

Set objFSO = CreateObject("Scripting.FileSystemObject")

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colDrives = objWMIService.ExecQuery _ ("Select * From Win32_LogicalDisk Where DriveType = 2")

For Each objDrive in colDrives
    strDrive = objDrive.DeviceID
    strTarget = strDrive & "\" 
    objFSO.CopyFile "C:\Scripts\Test.txt", strTarget, OverWriteExisting
Next

Here is my PowerShell version:

# Find removable drives and copy file(s) to it

# Get list of removable drives
$colDrives = Get-WmiObject -Namespace "root/cimv2" -Query "Select * From Win32_LogicalDisk Where DriveType = 2"

# Cycle through drives and copy file
foreach ($objDrive in $colDrives) {
    $strTarget = $objDrive.DeviceID + "\"
    Copy-Item "C:\scripts\Test.txt" -Destination $strTarget -Force
}

1 comment:

Additional Info

My photo
email: support (AT) mangrumtech (DOT) com
mobile: 480-270-4332