1

I'm assigning the Get-Mailbox command to a variable so that I can output this to a log file:

$SmtpForwardingAddress = Get-Mailbox -Identity $Upn | Select ForwardingSmtpAddress
"Email forwarding set to $($SmtpForwardingAddress)" | Tee-Object $logfilepath -Append

The variable $SmtpForwardingAddress returns:

"Email forwarding set to @{ForwardingSmtpAddress=smtp:[email protected]}"

I'd like to trim this to just the [email protected] value. I've tried a couple of things but get errors like the below:

Method invocation failed because [Selected.System.Management.Automation.PSCustomObject] does not contain a method named 'substring'.

Method invocation failed because [Selected.System.Management.Automation.PSCustomObject] does not contain a method named 'Trim'.

Any ideas as to what I can do to get the desired result?

2
  • What is the output for $SmtpForwardingAddress? Commented Jul 19, 2017 at 15:36
  • As shown above: "@{ForwardingSmtpAddress=smtp:[email protected]}" Commented Jul 19, 2017 at 15:38

2 Answers 2

3

An object is being stored into $SmtpForwardingAddress instead of a [String] like you're expecting which does not have those methods.

Try this:

"Email forwarding set to $(($SmtpForwardingAddress.ForwardingSmtpAddress).TrimStart('smtp:'))
Sign up to request clarification or add additional context in comments.

4 Comments

Ah spot on thanks. So because it's an object that's being stored, the property .ForwardingSmtpAddress needs to be added to provide the trim method with something to work with?
I'm assuming the object's property points to a string that is smtp:[email protected]. You can confirm for certain by using the .GetType() method. @{} indicates a PowerShell object. @() is an array, for example.
Yes, $SmtpForwardingAddress.GetType() returns PSCustomObject whereas $SmtpForwardingAddress.ForwardingSmtpAddress.GetType() returns string. Good to know thanks
@jshizzle additionally, you can pipe an object to Get-Member to see all of its properties and methods. Because .ForwardingSmtpAddress is a string, it contains the .Trim* and .Substring methods. e.g. $SmtpForwardingAddress.ForwardingSmtpAddress | Get-Member
1

In PowerShell there always is more than one solution.

$ForwardingAddress = (Get-Mailbox -Identity $Upn).ForwardingSmtpAddress.Split(':')[1]
"Email forwarding set to $ForwardingAddress" | Tee-Object $logfilepath -Append

2 Comments

Nice one thanks although this doesn't like the .[1] at the end. leaving this out splits the results on three separate lines but obviously just want the one which I dare say is what the .[1] was meant to do?
Cracking stuff. Always nice to have an alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.