content.php

Powershell Script – Search for a file containing text

The customer was moving file servers and needed to know which of their users had a desktop shortcut to the old mapped drive. They used roaming profiles, so all users desktop directories were subfolders under a single parent folder.

One of the biggest advantages of using Powershell for this task is that it can access these protected folders that even domain admins can’t access directly.

#This is the parent directory where all the all users’ home dirs are
$allHomeDirs = Get-ChildItem -Path \\Server\homelocation

#This is a list where I want to put the desktop dirs for each user
#I’m going to save each desktop filepath as a String
$listallDirs = New-Object Collections.Generic.List[string]

foreach($homedir in $allHomeDirs){
$Desktop = “\\Server\homelocation” + $homedir + “\Desktop”
$listasllDirs.Add($Desktop)
}
#i like to check periodically in my scripts to make sure I’m picking up good data
write-host $listallDirs

$hash = @()

Now it’s simply a matter of searching each of these file locations for the specified pattern. In my case I’m looking for shortcut files that contain the pattern E:\\

foreach($homedir in $listallDirs){
$matchingFiles = Get-ChildItem -Path $homedir | Select-String -Pattern “E:\\”
foreach($match in $matchingFiles){
$hash += New-Object PSObject -Property @(
‘Path’ = $match.Path
‘LineNumber’ = ‘$match.LineNumber
‘Line’ = $match.Line
‘Filename’ = $match.Filename
}
}
}

And finally, we want to export this to a CSV file

$hash | Export-Csv “C:\Some\Location\Filename.csv” -NoTypeInformation

Leave a Reply

Your email address will not be published. Required fields are marked *