Reputation: 11
I have the following piece of PowerShell 2.0 code that mostly works.
#$UserProfilePath is the path to recursively search
$MailBody = $MailBody + "`r`n`r`n Potential Valuable Files located in $NLEFriendlyName's profile include:`r`n`r`n"
$FileList = get-childitem -path $UserProfilePath -Recurse
ForEach ($File in $FileList) {
if ($File.Extension -eq ".doc") {$UsefulFiles = $UsefulFiles + "`r`n" + $File.name}
elseif ($File.Extension -eq ".docx") {$UsefulFiles = $UsefulFiles + "`r`n" + $File.name}
elseif ($File.Extension -eq ".xls") {$UsefulFiles = $UsefulFiles + "`r`n" + $File.name}
elseif ($File.Extension -eq ".xlsx") {$UsefulFiles = $UsefulFiles + "`r`n" + $File.name}
elseif ($File.Extension -eq ".ppt") {$UsefulFiles = $UsefulFiles + "`r`n" + $File.name}
elseif ($File.Extension -eq ".pptx") {$UsefulFiles = $UsefulFiles + "`r`n" + $File.name}
elseif ($File.Extension -eq ".pdf") {$UsefulFiles = $UsefulFiles + "`r`n" + $File.name}
elseif ($File.Extension -eq ".txt") {$UsefulFiles = $UsefulFiles + "`r`n" + $File.name}
}
$MailBody = $MailBody + $UsefulFiles
And it does mostly what I expect it to which is generating a list of files found in a user's profile directory.
The problem is that the carriage return (`r`n)
isn't always respected. My $MailBody
variable ends up looking like the below snippet where it starts out fine, but stops doing it.
20150114-Error.txt
Server List.txt
Server Port Breakdown.xlsx
ds_time.txt
Business Continuity - Call Center Services 2009a (2) (4)-old.pdf Business Continuity - Call Center Services 2009a (2) ....pdf New Text Document.txt Office2013Rearm.txt UserList.txt StopScreensaver.txt Testing Doc 201501081355.txt Antivirus KB.docx Antivirus-Deployment.txt
This posting somewhat alludes to a possibility, but I'm not sure on how to translate it to my script:
I'm sure there is a more optimal way to list all the file extensions as well.
Upvotes: 1
Views: 510
Reputation: 2214
I tried to clean up the selection process a bit too.
#sample variables
#$UserProfilePath = 'C:\Users\bob'
#$NLEFriendlyName='bob'
#select extensions to search
$ext = ".doc",".docx",".xls",".xlsx",".ppt",".pptx",".pdf",".txt"
$FileList = get-childitem -path $UserProfilePath -Recurse
$UsefulFiles = $FileList | Where-Object {$_.extension -in $ext} | select -expand name
$MailBody = $MailBody + "`r`n`r`n Potential Valuable Files located in $NLEFriendlyName's profile include:`r`n`r`n"
$MailBody = $MailBody + ($UsefulFiles -join "`r`n")
Upvotes: 1