我正在尝试在PowerShell中创建Microsoft.SqlServer.Management.Smo.Mail.MailServer类的对象。我需要这样做的原因是因为我试图使用PowerShell在SQL的新实例上设置DBMail。我已成功使用默认邮件服务器创建MailAccount。但我需要创建自己的。
任何人都可以帮我指出任何示例或参考。
答案 0 :(得分:1)
取自this SQLServerCentral.com article:
# Step 1 - Set variables for mail options.
$sqlServer = 'YourServerName'
$accountName = 'dbMailDefaultAcct'
$accountDescription = 'Default dbMail Account'
$originatingAddress = "$sqlServer@yourDomain.com"
$replyToAddress = 'DO_NOT_REPLY@yourDomain.com'
$smtpServer = 'smtpServer.yourDomain.com'
$profileName = 'dbMailDefaultProfile'
$profileDescription = 'Default dbMail profile'
# Step 2 - Load the SMO assembly and create the server object, connecting to the server.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
$server = New-Object 'Microsoft.SqlServer.Management.SMO.Server' ($sqlServer)
# Step 3 - Configure the SQL Server to enable Database Mail.
$server.Configuration.DatabaseMailEnabled.ConfigValue = 1
$server.Configuration.Alter()
# Step 4 - Alter mail system parameters if desired, this is an optional step.
$server.Mail.ConfigurationValues.Item('LoggingLevel').Value = 1
$server.Mail.ConfigurationValues.Item('LoggingLevel').Alter()
# Step 5 - Create the mail account.
# ArgumentList contains the mail service, account name, description,
# display name and email address.
$account = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Mail.MailAccount `
-Argumentlist $server.Mail, $accountName, $accountDescription, $sqlServer, $originatingAddress
$account.ReplyToAddress = $replyToAddress
$account.Create()
# Step 6 - Set the mail server now that the account is created.
$account.MailServers.Item($sqlServer).Rename($smtpServer)
$account.Alter()
# Step 7 - Create a public default profile.
# ArgumentList contains the mail service, profile name and description.
$mailProfile = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Mail.MailProfile `
-ArgumentList $server.Mail, $profileName, $profileDescription
$mailProfile.Create()
# Step 8 - Associate the account to the profile and set the profile to public
$mailProfile.AddAccount($accountName, 0)
$mailProfile.AddPrincipal('public', 1)
$mailProfile.Alter()
# Step 9 - Configure the SQL Agent to use dbMail.
$server.JobServer.AgentMailType = 'DatabaseMail'
$server.JobServer.DatabaseMailProfile = $profileName
$server.JobServer.Alter()
请注意,我不会使用[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')
,但大多数人都这样做。
以SQL Server 2014为例,我更喜欢:
Add-Type -Path 'C:\Program Files (x86)\Microsoft SQL Server\120\SDK\Assemblies\Microsoft.SqlServer.Smo.dll';
或者:
Add-Type -AssemblyName 'Microsoft.SqlServer.Smo, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91';
这两个显式调用程序集的SQL Server 2014版本,并且显式调用正确的版本是您通常应该执行的操作。当程序集的错误版本被加载时你会得到一点,你就会理解。缺点是,如果您正在使用SQL Server 2012,2008等,则必须更改代码。
对于“哪个程序集包含此命名空间”的问题的一般答案,您可以在remarks on the MSDN page for the class中看到哪个程序集包含您所使用的代码。