Home > Net >  Powershell: Converting Headers from .msg file to .txt - Current directory doesn't pull header i
Powershell: Converting Headers from .msg file to .txt - Current directory doesn't pull header i

Time:06-01

So I am trying to make a script to take a batch of .msg files, pull their header information and then throw that header information into a .txt file. This is all working totally fine when I use this code:

$directory = "C:\Users\IT\Documents\msg\"
$ol = New-Object -ComObject Outlook.Application
$files = Get-ChildItem $directory -Recurse
foreach ($file in $files)
{
  $msg = $ol.CreateItemFromTemplate($directory   $file)
  $headers = $msg.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")
  $headers > ($file.name  ".txt")
}

But when I change the directory to use the active directory where the PS script is being run from $directory = ".\msg\", it will make all the files into text documents but they will be completely blank with no header information. I have tried different variations of things like:
$directory = -Path ".\msg\"
$files = Get-ChildItem -Path $directory
$files = Get-ChildItem -Path ".\msg\"

If anyone could share some ideas on how I could run the script from the active directory without needing to edit the code to specify the path each location. I'm trying to set this up so it can be done by simply putting it into a folder and running it.

Thanks! Any help is very appreciated!

Note: I do have outlook installed, so its not an issue of not being able to pull the headers, as it works when specifying a directory in the code

CodePudding user response:

The easiest way might actually be to do it this way

$msg = $ol.CreateItemFromTemplate($file.FullName)

So, the complete script would then look something like this

$directory = ".\msg\"
$ol = New-Object -ComObject Outlook.Application
$files = Get-ChildItem $directory

foreach ($file in $files)
{
    $msg = $ol.CreateItemFromTemplate($file.FullName)
    $headers = $msg.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")
    $headers > ($file.name  ".txt")
}

All that said, it could be worthwhile reading up on automatic variables (Get-Help about_Automatic_Variables) - for instance the sections about $PWD, $PSScriptRoot and $PSCommandPath might be useful.

Alternative ways - even though they seem unnecessarily complicated.

$msg = $ol.CreateItemFromTemplate((Get-Item $directory).FullName   $file)

Or something like this

$msg = $ol.CreateItemFromTemplate($file.DirectoryName   "\" $file)
  • Related