Quantcast
Channel: Scripting – Robin CM's IT Blog
Viewing all articles
Browse latest Browse all 27

Script comparison: CMD, VBScript, Powershell

$
0
0

This was going to be a short scripting exercise for a new member of staff, but has been ditched due to time constraints. I’d written some sample scripts to see how long it’d take, so thought I’d post them as interesting comparison of the three languages.

They’re perhaps more a reflection of my abilities than being textbook examples of the three languages. I know there are better ways that bits of them could be done, but these were knocked up by me in as little time as possible so needed to be functional rather than perfect.

The brief was to write a short script, around 10-20 lines, that would move files from one folder to another if they had a certain text string in the filename. The folders were both located in the current user’s Documents folder. Source folder was called TestFiles, destination folder for matching files was called NewFiles. The text string to look for in the filenames was “robin” (minus the quotes). I wanted the script to be easily changed to use different folders or to look for a different text string. I also wanted the script to write some basic activity information to screen.

CMD (Windows Command processor/batch file)

@echo off
set Folder=%userprofile%\Documents\TestFiles
set NewFolder=%userprofile%\Documents\NewFiles
set FindText=robin
for /f "delims=" %%i in ('dir /b %Folder%') do (
   echo %%i
   call :FindAndMove "%Folder%\%%i" %FindText%
)
:FindAndMove
echo %1 | find /i "%2" >nul:
if %errorlevel%==0 (
   move %1 %NewFolder%\ >nul:
   echo Moved to new location
)
goto :eof
echo Done.

VBScript

Option Explicit
Dim oFSO, oFolder, oShell, oFile
Dim sFolderPath, sFindText, sNewFolder
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
sFolderPath = "%userprofile%\Documents\TestFiles"
sNewFolder = "%userprofile%\Documents\NewFiles"
sFindText = "robin"
sFolderPath = oShell.ExpandEnvironmentStrings(sFolderPath)
sNewFolder = oShell.ExpandEnvironmentStrings(sNewFolder)
Set oFolder = oFSO.GetFolder(sFolderPath).Files
For Each oFile In oFolder
   WScript.Echo oFile.Name
   If InStr(oFile.Name,sFindText) Then
      oFSO.MoveFile oFile.Path,sNewFolder&"\"
      WScript.Echo "Moved to new location"
   End If
Next
WScript.Echo "Done."

PowerShell

$Folder = $env:USERPROFILE+"\Documents\TestFiles"
$NewFolder = $env:USERPROFILE+"\Documents\NewFiles"
$FindText = "robin"
$FolderObj = Get-ChildItem -Path $Folder
foreach($File in $FolderObj){
   Write-Host $File.Name
   if($File.FullName -match $FindText){
      Move-Item -Path $File.FullName -Destination $NewFolder
      Write-Host "Moved to new location"
   }
}
Write-Host "Done."

 



Viewing all articles
Browse latest Browse all 27

Trending Articles