One of the first scripts I wrote using PowerShell was pretty basic and was for educational purposes mainly. I had several DVDs containing images, applications, source code, a kitchen sink, and everything else on each of them. Not a big deal, right, isn’t that what DVDs are for? However, what if you need to grab all of the images to migrate them to a new hard drive to be shared on your home network? Well, if you are old school and still use cmd.exe and do not want to learn PowerShell you use xCopy D:\*.jpg C:\Dest /e. That is just boring, and certainly not worth a blog post! However, if you are excited to master the new command line that is everything DOS should have been, you script it by hand! Jogging in place may be a bit silly, but it is still exercise. So this is what I came up with:
[string]$sourceRoot = $args[0]
[string]$destRoot = $args[1]
[string]$fileType = "*." + $args[2]
Write-Host "Copying " $fileType " Files From" $sourceRoot "To" $destRoot
$files = Get-childItem $sourceRoot * -Recurse -Include $fileType
Write-Host "Found" $files.Length "Files"
foreach($file in $files){
[string]$destFolder = $file.Directory.FullName.Replace($sourceRoot.ToUpper(), $destRoot.ToUpper() + "\")
[string]$destFile = $destFolder + "\" + $file.Name
Write-Host "Copying" $file " To " $destFile
if(![System.IO.Directory]::Exists($destFolder)) {New-Item $destFolder -type directory}
copy-item $file -destination $destFile
}
Write-Host $files.Length " files copied."
This can then be wrapped in a loop or entered by hand to specify different file extensions. jpg, jpeg, gif, png, etc (dont forget the etc files! ;)
I am defiantly interested in hearing comments on the script. Can anyone say if it could be multithreaded or propose another performance enhancement I may have missed? I will be posting more scripts in the downloads section of this site in the future, and would be more than happy to improve this script based on your feedback!
|