我想检查我的联系人管理系统中的电子邮件地址是否有效,我能想到的最好的方法是获取其域的 MX 记录,然后打开 SMTP 连接,看看远程服务器是否接受该电子邮件地址作为有效的“TO”。
答案1
使用此功能您可以执行以下操作:
PS> $allRecords = Get-Dns -Name mydomain.com -Type MX
PS> write-host $allRecords.RecordsMX
$allRecords
是 PoshNet.Dns.Response 类型,因此您可以读取其属性来获取您的记录。
此 cmdlet 的另一个优点是您可以让它在单个查询中返回多种类型的记录。
答案2
function Get-DnsAddressList
{
param(
[parameter(Mandatory=$true)][Alias("Host")]
[string]$HostName)
try {
return [System.Net.Dns]::GetHostEntry($HostName).AddressList
}
catch [System.Net.Sockets.SocketException] {
if ($_.Exception.ErrorCode -ne 11001) {
throw $_
}
return = @()
}
}
function Get-DnsMXQuery
{
param(
[parameter(Mandatory=$true)]
[string]$DomainName)
if (-not $Script:global_dnsquery) {
$Private:SourceCS = @'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace PM.Dns {
public class MXQuery {
[DllImport("dnsapi", EntryPoint="DnsQuery_W", CharSet=CharSet.Unicode, SetLastError=true, ExactSpelling=true)]
private static extern int DnsQuery(
[MarshalAs(UnmanagedType.VBByRefStr)]
ref string pszName,
ushort wType,
uint options,
IntPtr aipServers,
ref IntPtr ppQueryResults,
IntPtr pReserved);
[DllImport("dnsapi", CharSet=CharSet.Auto, SetLastError=true)]
private static extern void DnsRecordListFree(IntPtr pRecordList, int FreeType);
public static string[] Resolve(string domain)
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
throw new NotSupportedException();
List<string> list = new List<string>();
IntPtr ptr1 = IntPtr.Zero;
IntPtr ptr2 = IntPtr.Zero;
int num1 = DnsQuery(ref domain, 15, 0, IntPtr.Zero, ref ptr1, IntPtr.Zero);
if (num1 != 0)
throw new Win32Exception(num1);
try {
MXRecord recMx;
for (ptr2 = ptr1; !ptr2.Equals(IntPtr.Zero); ptr2 = recMx.pNext) {
recMx = (MXRecord)Marshal.PtrToStructure(ptr2, typeof(MXRecord));
if (recMx.wType == 15)
list.Add(Marshal.PtrToStringAuto(recMx.pNameExchange));
}
}
finally {
DnsRecordListFree(ptr1, 0);
}
return list.ToArray();
}
[StructLayout(LayoutKind.Sequential)]
private struct MXRecord
{
public IntPtr pNext;
public string pName;
public short wType;
public short wDataLength;
public int flags;
public int dwTtl;
public int dwReserved;
public IntPtr pNameExchange;
public short wPreference;
public short Pad;
}
}
}
'@
Add-Type -TypeDefinition $Private:SourceCS -ErrorAction Stop
$Script:global_dnsquery = $true
}
[PM.Dns.MXQuery]::Resolve($DomainName) | % {
$rec = New-Object PSObject
Add-Member -InputObject $rec -MemberType NoteProperty -Name "Host" -Value $_
Add-Member -InputObject $rec -MemberType NoteProperty -Name "AddressList" -Value $(Get-DnsAddressList $_)
$rec
}
}
Get-DnsMXQuery -DomainName "gmail.com"
答案3
Get-WmiObject -Class MicrosoftDNS_MXType -Namespace root\microsoftdns -ComputerName DC1 -Filter “DomainName='domain.com.'”
答案4
在 Server 2012/Windows 8 及以上版本中,您可以使用解析 DNS 名称:
Resolve-DnsName -Name mydomain.com -Type MX