Powershell script to retrieve email from archived mailbox in Exchange2007

The other powershell script I worked on was to retrieve a detached mailbox that was still retained in exchange, archive the mail to a pst file, move the pst file to the managers home directory and then delete the mailbox again.
The following script does this – note some paths are hardcoded and I already have a temporary account in AD called tempuser that does not have a mailbox. This is the account that the deleted mailbox is attached to.
The main disadvantage to this method is that at the end of the script all of the detached mailboxes will appear as tempuser in the exchange console. In this particular script I also do very little error checking as this was designed for my use but hopefully helps others too.


$user=$args[0] #user is the first parameter passed
$fname=$args[1] #first name
$lname=$args[2] #last name
$fullname=$fname + " " + $lname
$manager=$args[3] #manager windows accountname is the last parameter passed
if ($manager -eq $null) {exit} # if not enough parameters are provided then quit the script

write-host $user
write-host $manager
$Host.UI.RawUI.WindowTitle = "attaching mailbox to tempuser account"

$result=Connect-Mailbox -Identity $fullname -Database 'servername\First Storage Group\Standard User Mailbox' -User 'domain\tempuser' -Alias 'tempuser'

$Host.UI.RawUI.WindowTitle = "Sleeping 60 until moving mailbox"
start-sleep -s 60 # sleep 60 seconds after moving mailbox to tempuser account before doing the export

$Host.UI.RawUI.WindowTitle = "exmerging mailbox"
export-mailbox tempuser -pstfolderpath d:\mailboxes -confirm:$false

$Host.UI.RawUI.WindowTitle ="sleep 20 seconds"
start-sleep -s 20 # sleep 20 seconds after exporting mailbox to tempuser account before doing the mailbox move

$Host.UI.RawUI.WindowTitle = "Moving pst file to managers mailbox"
$newdir="\\archiveserver\c$\users\" + $manager + "\" + $user
$result=mkdir $newdir
$newpst=$newdir + "\" + $user + ".pst"
$newpst
Move tempuser.pst $newpst

$Host.UI.RawUI.WindowTitle = "disabling tempuser mailbox for reuse"
disable-mailbox tempuser -confirm:$false

Note that I use the $Host.UI.RawUI.WindowTitle statement a lot – this enables me to easily see whereabouts in the script I have got to. I much preferred to use the command title in my batch files to do the same thing. Likewise the $null = $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”) is the equivalent of the batch command pause

Powershell script to retrieve list of emails from Exchange2007 in the past 24 hours.

As in my previous post I needed to obtain a list of emails that have gone through a mail server within the past 24 hours (so it can be run on a daily basis). I struggled with the code initially but ended up with the following.

$yesterday = (get-date).adddays(-1).tostring(“g”)
$rightnow = (Get-Date).ToString(“g”)
get-messagetrackinglog -Start $Yesterday -End $rightnow -EventID RECEIVE -Result size 5000| select-object EventID,Sender,@{name=’Recipients’;expression={[string]::join(“;”,($_.Recipients))}},MessageSubject,TimeStamp | export-csv receive.csv
get-messagetrackinglog -Start $Yesterday -End $rightnow -EventID SEND -Resultsize 5000| select-object EventID,Sender,@{name=’Recipients’;expression={[string]::join(“;”,($_.Recipients))}},MessageSubject,TimeStamp | export-csv send.csv

My next step is to automate this and send it via email

Twitter helped me with powershell this week.

This week at work I’ve been doing a fair amount of work with powershell. It has been a slow process as I’ve had no training in powershell and was basically teaching myself as I went along. I had two goals in mind.

The first was to automatically attach a mailbox to a temporary account, export the mail within this mailbox to a pst file, move the pst file to a folder and then delete the account again.  As Exchange2007 needs to use powershell to export the data I had to change my user deletion script to run within powershell.

My other goal was to write a report for all mail sent or received through the exchange server in the past 24 hours. Using the exchange tracking logs I was able to pull the information required to do this.

The second problem was causing me more hassles  as I could not work out how to retrieve the time from 1 day ago AND have the result in the format needed for the next part of the script. I could get the current time in the correct format OR I could get the time from 1 day ago but not in the current format. I went onto the #powershell room on irc.freenode.net but it looked like everyone was asleep as I didn’t get any response to my query.  I decided to post a tweet on twitter about the problem and within 5 minutes I had about 3 or 4 responses which was great. At the same time I also got a response in the chatroom. As usual with coding, there are several ways to get an answer.  However Jaykul was very helpful in telling me that “get-date (get-date).addays(-1) -f g”  is 2 ten thousandths of a second quicker than “[datetime]::now.adddays(-1).tostring(“g”)”
Best way to get the Time from 24 hours ago.
Now you can probably see why I was confused and struggling to get the code working!

I’m going to post the resulting code in the next posts to make it easier to search on.

Latest malware removals.

I had two pc’s given to me last weekend to fix various speed issues. Thankfully I had downloaded the AntiMalwareToolkit from Lunarsoft recently so I did a quick update which meant I had a lot of antivirus and antispyware tools with up to date definitions ready on a cd.
The first machine was pretty straightforward and just needed ad-aware removing and reinstalling to fix ad-aware crashing on bootup. At the same time I scanned for virus and was pleasantly surprised to see none on the machine. The combination of Norton 360, adaware and malwarebytes had done a good job. Norton was crippling the speed of the machine though and I had to disable Norton whilst I ran other diagnostics on the machine as it was just painfully slow whilst running.

The other machine was a whole other story. Norton AV2004 does not do a good job of keeping machines protected when the definitions were last updated in 2005, although I think you’d all agree that no other product would either! Running MalwareBytes detected 400 antivirus files ranging from vundo,trojans, spyware2009 and other infestations. My initial scan was run after booting the machine into safe mode – normal mode was unusable, taking 6 minutes to launch regedit after eventually managing to hit start/run and type in regedit.
The initial scan took over 8 hours to run. Unfortunately I had not cleaned out the temporary internet files on the machine – all 18gb of them! After the first scan completed I selected all the temporary internet files and deleted them. It took about 20 minutes for windows to finish the “preparing to delete” stage. I’m not sure what exactly it is doing, but it is incredibly annoying to hit delete, walk away from the computer and come back 20 minutes later to see it then popup and say “are you sure you want to delete these files?”. I could have deleted the files from a dos prompt but it was taking forever to do anything, so opening a dos prompt and then navigating would have been very painful.
So after 3 hours of deleting files, a reboot I did another scan. This time it took 2 hours. So the moral of the story is to delete temporary internet files first. Interestingly I later ran AdAware and that actually asked me if I wanted to delete these files before it did the scan.
The machine was now fairly responsive…..in safe mode, but still took forever to do anything in normal mode. Scans were coming up clean so the configuration was obviously still screwed up somewhere. I tried to uninstall symantec using their uninstall package but that just hung using no cpu usage so it was a hard reboot and I tried the Norton Removal Tool. The first time it would unpack the self extracting exe but do nothing after that.
At this point I came across a thread in software tips and tricks with the same symptoms of the machine running slowly and the start button being unavailable. This thread was started in 2004 so I was a bit pessimistic about the solution of running a reg cleaner (as most of them are not really worth bothering with). However several people had responded saying that the solution worked, with a couple of posts from Jan 2009 so I figured it was worth a try. I had never heard of the registry cleaner, but I had heard of Jv16 Powertools, so I downloaded RegSupreme and let it do it’s registry cleanup. I looked briefly through the results and could see nothing really unusual so I rebooted and was really surprised that the machine started to respond normally. I was then able to run the Norton Removal Tool and remove Norton from the machine completely.
I haven’t completely finished with the machine yet, but I’m nearly there. You may be wondering why I took so long on this machine. To be truthful, if it was mine I’d have wiped it straight away, but as the issues got harder to fix, my stubbornness and curiosity got the better and I needed to know how to fix the problem and retain the data on the machine. After all, formatting is the easy way out and one day I’ll have a machine that I MUST repair in order to get data and this experience will have given me some helpful experience and preparation for that day.

64bit Symantec Antivirus does not update from Management Server

Discovered that 64bit clients of Symantec Antivirus have to be set to get their updates from Symantec servers using LiveUpdate, not from the Management server (as you would normally set the configuration to be). This may involve creating a new management group in Symantec’s Administration console and setting the update to not use the parent server as per the screenshot below.
Set this to ensure Symantec Antivirus 64 bit clients update  (by absoblogginlutely)

BackupExec 12 fails to LiveUpdate on Windows 2008

When trying to run LiveUpdate from within BackupExec v12 running on Windows 2008 you may get the error message “To receive updates, Backup Exec must be registered with LiveUpdate. To automatically register now, Click Yes. If you choose not to register now, you will be prompted again when you click LiveUpdate.” The solution is to right click the BackupExec icon and run as Administrator. LiveUpdate will work.

Quick way to get BIOS information without rebooting

If you want to get the BIOS version of a pc without rebooting or the Dell service tag then use the following useful command(s)
wmic bios >c:\temp\1.txt
notepad c:\temp\1.txt

The reason I pipe to 1.txt and then display in notepad is that the formatting looks all messed up in a dos prompt due to line wrapping but looks ok in notepad. The BIOS version and service tag will be displayed (among other things).
This beats my previous preferred method when doing remote support of going to Dell’s support site, going to warranty information and then loading their activex component to detect the hardware information.
Update: You do need to have admin rights to run this command.

-1056749164 when exporting a mailbox in Exchange 2007

Trying to export an Exchange2007 mailbox using the export-mailbox cmdlet I was getting the error message “Failed to copy messages to the destination mailbox store with error: MAPI or an unspecified service provider. ID no: 00000000-0000-00000000, error code: -1056749164”

A lot of the tips online suggested that I excluded the inbox folder, but that doesn’t help as I needed to export the entire mailbox as this was for a user who had left the company.

Microsoft has a kb article on this and states the problem is fixed with Rollup4 for Exchange, but I was already on Rollup5.

Thanks to kyBOSH on the Technet forums , it turns out that I needed to give my account FullAccess to the mailbox using the command “Add-mailboxpermission account -accessrights fullaccess -user myaccount” Obviously you need to replace account with the accountname of the user that is being exported and myaccount is the accountname that is doing the export.

Whilst searching for these results I discovered how bad Microsoft’s Live Search is.

Searching for -1056749164 on technet gives 619,000 resultsThe initial search for “-1056749164” on Technet came up with 619000 results (although when I reran it later it dropped to 512000!).

Searching for -1056749164 on the internet gives zero results As the results were completely useless I expanded the search to the entire internet – this time the search returned zero results!

Sigma flash almost here….

The only downside with the various tracking systems that UPS,DHL and other companies provide is that they provide a tantalising glimpse into the fact that shipments are SOOOO close but not quite here!  I purchased a flash for my camera and got notice from UPS that it arrived in Columbus yesterday evening but I have to wait until Monday before they attempt to deliver it.  The weird thing is that I actually got the tracking information the day before UPS even had it in their online system.

Windows7 installs fast.

I downloaded Windows7 as part of my technet plus subscription and got a few minutes to try the installation whilst listening to the Hyper-V deep dive training session this evening. The time taken to install from my iso image to  a running installation was 31 minutes – thats VERY good going.

The client not surprisingly uses ie8 which was a bit of a pain for me. I use SGP for my online password management and that relies on the links bar within the browser. Now called the Favorites bar, for some reason this would not allow me to save the SGP bookmarklet in the bar – instead I had to add it to my favourites and then drag it into the bar afterwards.

It is too soon to make any more comments on it at the moment as it is time for bed, but so far it looks nice.

The one big plus is that Microsoft have FINALLY got the time zone problem fixed. Now they actually remember the timezone preference set during the installation and keep it afterwards rather than setting it to GMT-8 which theyhave been doing ever since Windows95!

I am getting some quirky things going on with my keyboard missing some characters, but I’m not sure if that is due to my bluetooth keyboard, ie8 or the fact I’m running in a hyper-v client where the parent server has been up for several days now.