I was reading Joe Keohan’s Blog about copying files via PowerShell and that got me to thinking about a process I already had. Each night we copy files from a shared folder and post them to our intranet site for internal use. We currently are using a batch file to handle this but I thought it was time to rewrite it in PowerShell.
I had two main processes that I needed to handle. The first was to copy the files to the local folder for the intranet and the second was to send an email to someone with those files attached so he can open them on his mobile device.
So the first step of my script was to define some variables to stand in for my file locations.
$SourceDir = "\\SVR1\data\Reports\Trading\*.pdf" $DestDir = "c:\inetpub\intranet\research\reports\" $BlotterSource = "\\SVR1\data\Reports\Blotters\*.pdf"
Then I use the Test-Path cmdlet to determine if the reports exist at the source location. Normally this cmdlet would return True if the files exist and False if they do not. But I use it in an If statement to say if it evaluates to True then do something else. The something else is to start the file copy.
If (Test-path $SourceDir ) { Copy-Item $SourceDir -Destination $DestDir -Force } If (Test-path $BlotterSource) { Copy-Item $BlotterSource -Destination $DestDir -Force }
I do this twice, once for one location and then again for the second location.
And once my script is finished copying the files I use the send-mailmessage cmdlet to email the files to the recipient. Since I have multiple files I’d like to attach I use a Get-ChildItem cmdlet to get all the file names and pipe them into the send-mailmessage cmd.
This is what the finished script looks like.
$SourceDir = "\\SVR1\data\Reports\Trading\*.pdf"
$DestDir = "c:\inetpub\intranet\research\reports\"
$BlotterSource = "\\SVR1\data\Reports\Blotters\*.pdf"
If (Test-path $SourceDir )
{ Copy-Item $SourceDir -Destination $DestDir -Force }
If (Test-path $BlotterSource)
{ Copy-Item $BlotterSource -Destination $DestDir -Force }
Get-ChildItem $DestDir | Where {-NOT $_.PSIsContainer} | foreach {$_.fullname} | send-mailmessage -from "Reporting <reporting@anyone.com>" -to "Jonathan <jonathan@anyone.com>", "Rob <rob@anyone.com>" -Cc "Greg <greg@anyone.com"> -subject "Daily Research Reports" -smtpServer mailserver.anyone.com -Body "Here are the daily research files for your review"
Now that the script is done I just schedule it via Windows Task Scheduler and we’re all set. Now the files will get copied and emailed quickly and efficiently.
Filed under: PowerShell, System Admin, Windows Server Tagged: email, FileCopy, Powershell
