Mark Allison
Mark Allison

Reputation: 7228

How to get date and time separately from Outlook MailItem in Powershell?

I want to get SentOn as both a short date and a short time. How can I do that?

$mailbox = "[email protected]"

$outlook = New-Object -com Outlook.Application
$ns = $outlook.GetNamespace("MAPI")
$inbox = $ns.Folders.Item($mailbox).Folders.Item("Inbox")
$searchItems = $inbox.Folders.Item("MySubFolder").Folders.Item("MyNestedSubFolder").Items
$searchItems | Select Subject, SentOn.ToShortTimeString()

This gives an error SentOn : The term 'SentOn' is not recognized as the name of a cmdlet, function, script file, or operable program.

I also tried $searchItems | Select Subject, [datetime](SentOn).ToShortTimeString() but got the same error.

Upvotes: 0

Views: 653

Answers (2)

Matt
Matt

Reputation: 46710

Upon inspection in the loop the property SentOn is of System.DateTime type so there is no reason to recast. Now you want to use a method from that type to change the property output. As you have seen you cannot edit the properties dynamically as you have done.

Calculated properties would fit nicely here as they are designed for that purpose.

select Subject, @{Name="SentOn";Expression={($_.SentOn).ToShortDateString()}}

If you need to change more properties than just the SentOn just add on more calculated properties separated with commas. Just like you would with normal preexisting properties.

Upvotes: 1

Richard
Richard

Reputation: 7000

Try:

$searchItems | %{[pscustomobject]@{
                     Subject=$_.Subject; 
                     ShortTime=(get-date $_.SentOn.DateTime).ToShortTimeString();
                     ShortDate=(get-date $_.SentOn.DateTime).ToShortDateString()}
                 }

Upvotes: 1

Related Questions