One of the things that a customer does every couple months in IT is moving one folder into another. Usually, they don’t know or even realize that they have moved it until the next time they (or someone else) need it. It can be hard to find it when there are a dozen other folders they could have moved it too but this problem is compounded when there are thousands of folders.

I have been messing with PowerShell the last couple weeks in preparation for using PowerCLI to manage our VMware cluster. This was one of the scripts I worked through to help me learn it (the others are suited for print). That being said PowerShell is crazy like perl in how a complex script can be written in two lines so there’s most likely a simpler way to write this. If there is by all means let me know in the comments.


# This script does a breadth first search of the file system

# check the argument length
$intCount = $args.count;
if($intCount -ne 2){
echo 'Usage: breadthfirstsearch.ps1 ';
exit;
}

# store the arguments
$strPath = $args[0];
$strSearch = $args[1].ToLower();

# verify the path exists
if((Test-Path -path $strPath) -eq $False){
# this is a not a valid path so error out
echo ('Invalid path: ' + $strPath.ToString());
exit;
}

# create the queue
$queue = New-Object System.Collections.Queue;

# add the first directory
$queue.Enqueue($strPath);

# loop through the queue
while($queue.count -gt 0){
# get the current item
$strCurrent = $queue.Dequeue();

if($strCurrent.ToString().ToLower().Contains($strSearch)){
echo $strCurrent;
}

# find the objects
$objListing = (get-childitem $strCurrent);

# check to see if there were results
if($objListing.count -gt 0){
# loop through the files
foreach($strFile in $objListing){
# make sure we aren't looking at a file
if($strCurrent -ne $strFile){
# add the item to the queue
$queue.Enqueue($strFile.fullname);
}
}
}
}