?
Solved

PowerShell Script to Search for PST files

Posted on 2016-10-10
5
Medium Priority
?
484 Views
Last Modified: 2016-11-22
I had this question after viewing Powershell script to find files on network computers..

I am trying to create a script on how to search for pst files in the hard drive. How can I achieve this? Any help on the script would be appreciated.

Thanks
0
Comment
Question by:Junior Sofe
5 Comments
 
LVL 7

Expert Comment

by:Niten Kumar
ID: 41837821
This line of code does the trick, which can be typed directly in PowerShell ISE, in order to avoid script signing:

   1. Start Windows PowerShell ISE
   2. Type gci -path c:\ -recurse -include *.pst|select-object fullname,lastwritetime|export-csv c:\temp\pst.csv and press enter.
    3. Wait until the script finishes

In this case the output is sent to a csv file in the c:\temp folder.


OR you can use the script below:


$strComputers = Get-Content -Path "C:\computernames.txt"
[bool]$firstOutput = $true
foreach($strComputer in $strComputers)
{
$colFiles = Get-Wmiobject -namespace "root\CIMV2" `
-computername $strComputer `
-Query "Select * from CIM_DataFile `
Where Extension = 'pst'"
foreach ($objFile in $colFiles)
{
if($objFile.FileName -ne $null)
{
$filepath = $objFile.Drive + $objFile.Path + $objFile.FileName + "." `
+ $objFile.Extension;
$query = "ASSOCIATORS OF {Win32_LogicalFileSecuritySetting='" `
+ $filepath `
+ "'} WHERE AssocClass=Win32_LogicalFileOwner ResultRole=Owner"

$colOwners = Get-Wmiobject -namespace "root\CIMV2" `
-computername $strComputer `
-Query $query
$objOwner = $colOwners[0]
$user = $objOwner.ReferencedDomainName + "\" + $objOwner.AccountName
$output = $strComputer + "," + $filepath + "," + $user + "," + $objFile.FileSize/1KB + "," + $objFile.LastModified
if($firstOutput)
{
Write-output $output | Out-File -Encoding ascii -filepath "C:\pstdetails.csv"
$firstOutput = $false
}
else
{
Write-output $output | Out-File -Encoding ascii -filepath "C:\pstdetails.csv" -append
}
}
}
}
0
 
LVL 8

Expert Comment

by:Senior IT System Engineer
ID: 41837883
Is it just for one user only or all users in all AD domain ?
0
 

Author Comment

by:Junior Sofe
ID: 41841098
@ ITSystemEngineer...

For a start, its just only for one user.
0
 
LVL 8

Accepted Solution

by:
Senior IT System Engineer earned 2000 total points
ID: 41841121
Junior,

use the script below to find multiple extension of '*.PST', '*.OST'

Edit line:
27-31 for the paramater according to your environment
59 for the SMTP address

Function Convert-Size {
	[cmdletbinding()]
	Param (
		[parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
		[Alias("Length")]
		[int64]$Size
	)
	Begin {
		If (-Not $ConvertSize) {
			Write-Verbose ("Creating signature from Win32API")
			$Signature =  @"
				[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
				public static extern long StrFormatByteSize( long fileSize, System.Text.StringBuilder buffer, int bufferSize );
"@
			$Global:ConvertSize = Add-Type -Name SizeConverter -MemberDefinition $Signature -PassThru
		}
		Write-Verbose ("Building buffer for string")
		$stringBuilder = New-Object Text.StringBuilder 1024
	}
	Process {
		Write-Verbose ("Converting {0} to upper most size" -f $Size)
		$ConvertSize::StrFormatByteSize( $Size, $stringBuilder, $stringBuilder.Capacity ) | Out-Null
		$stringBuilder.ToString()
	}
}

$ScanPath = "C:\Users\"
$ResultFile = "C:\Temp\Files.csv"
$ResultEmailRecipient = "admin@domain.com"
$ResultEmailSender = "Powershell@localhost.com"
$IncludeFilter = @('*.PST', '*.OST')

#Powershell 3.0
$FileList = Get-ChildItem -Path $ScanPath -Include $IncludeFilter -Recurse -File

# Powershell 2.0
#$FileList = Get-ChildItem -Path $ScanPath -Include $IncludeFilter -Recurse | Where-Object {! $_.PSIsContainer}

$FileList |
	Select-Object FullName, LastWriteTime, @{Name='Size'; Expression={$_.Length | Convert-Size}}, @{Name='ByteSize'; Expression={$_.Length}} |
	Export-Csv -NoTypeInformation -Path $ResultFile

$Summary = $FileList | Group-Object Extension | ForEach-Object {
	$ByteSize = ($_.Group | Measure-Object Length -Sum).Sum
	$_ | Select-Object -Property `
		@{Name='Type'; Expression={$_.Name}},
		@{Name='Size'; Expression={$ByteSize | Convert-Size}},
		@{Name='ByteSize'; Expression={$ByteSize}}
} | Sort-Object -Property ByteSize -Descending

$Body = @"
User File Report for $($ENV:ComputerName):

$($Summary | Format-Table -AutoSize | Out-String)
"@

$Body

Send-MailMessage -Attachments $ResultFile -To $ResultEmailRecipient -From $ResultEmailSender -Subject 'File Report' -Body $Body -SmtpServer smtp.domain.com

Open in new window


Hope that helps and let me know how you go.
0
 
LVL 16

Expert Comment

by:Jason Crawford
ID: 41897207
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Accept: Senior IT System Engineer (https:#a41841121)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

exchangepro
Experts-Exchange Cleanup Volunteer
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
By default Outlook 2016 displays only one time zone in the Calendar. The following article explains how to display two time zones in one calendar view.
Many of my clients call in with monstrous Gmail overloading issues with Outlook. A quick tip is to turn off the All Mail and Important folders from synching. Here is a quick video I made to show you how to turn off these and other folders in Gmail s…
Screencast - Getting to Know the Pipeline
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question