Tuesday, March 10, 2015

Powershell - search a folder tree and remove select objects.

Had an interesting issue the other day. We're migrating user data from a different domain, and all the user folders which were copied, showed up in windows explorer as "documents" instead of their real names.

This was an issue with the desktop.ini file under each of the folders, which was causing windows explorer to display the folders with a different name. The fix was a simple "delete" of the desktop.ini from under each user directory . . however getting powershell to help me out with this took me a little bit of tinkering.

Desktop.ini by default is a hidden system file. Powershell, has known bugs with it's "remove-item" command, and the common work around is "get-childitem". Most references I could find for having powershell recursively search a directory structure didn't find the files I wanted to delete, so I built the following:

----------------------------Begin Script----------------------------------------------------------------------------

$path="c:\RootFolderToBeSearched"
$folders=Get-ChildItem -path $path -force | Where-Object{$_.PsIsContainer} | ForEach-Object{$_.FullName}
foreach ($folder in $folders)
{
$BadItem=Get-ChildItem $folder -Filter desktop.ini -Force
If ($BadItem -ne $null)
{
$bad=$folder + "\" + $BadItem
remove-item $bad -force
}
ELSE
{
write-host "$folder is clean..." -foregroundcolor Green
}
}

-----------------------------End Script-----------------------------------------------------------------

In my case, i was looking specifically for the file desktop.ini, to search and remove other files, simply replace the file name. 

This script is specifically only looking 2 folders deep into a folder tree, adding a "-recurse" to either of the "get-childitem" lines, will return content from all subfolders. If you wish to play with this particular option, you'll want to edit the "remove" lines, as well since they won't work based on paths returned from 'recursive' searches of the folders. 

No comments:

Post a Comment