Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get SMTP server name through PowerShell when $PSEmailServer is empty?

Windows 7, PowerShell 4.0. Computer is in the Windows domain.

I need to get SMTP server name (for using of the send-mailmessage cmdlet). The $PSEmailServer is empty.

I read this TechNet page about the Get-AcceptedDomain cmdlet. But I see this (on the TechNet page):

This cmdlet is available in on-premises Exchange Server 2016 and in the cloud-based service.

How can I get SMTP server name or its IP-address?

like image 949
Andrey Bushman Avatar asked Aug 12 '26 00:08

Andrey Bushman


1 Answers

If properly defined, the SMTP server address, either host name or IP, can be set through the SCP record in AD or Autodiscover DNS record of Exchange Server. There is a Powershell solution for querying SCP but Autodiscover solution is shorter, so I'll go on with it.

This works on Exchange Server 2010 and later. It should work with Exchange Server 2007 also but personally I have never used it.

You can get the host name; $MailServer = [Net.DNS]::GetHostByAddress([Net.DNS]::GetHostEntry("Autodiscover").AddressList[0]).Hostname

or IP address (as string); $MailServer = [Net.DNS]::GetHostByAddress([Net.DNS]::GetHostEntry("Autodiscover").AddressList[0]).AddressList[0].IPAddressToString

Since the GetHostByAddress(string) returns an instance of class System.Net.IPHostEntry, you can have some properties to make use of. For details, please read Microsoft Docs.

PS: I know, that's not the best practice to use the index of integers for values, but AddressList is an array of strings. So it does not define a method such as FirstOrDefault() or a property like DefaultAddress. So far, that is the most optimal and practical solution AFAIK.

like image 115
Zafer Balkan Avatar answered Aug 13 '26 13:08

Zafer Balkan