介绍 (Introduction)

In a previous article on Connecting PowerShell to SQL Server I went over how you use various methods in PowerShell to connect to SQL Server. In those examples though I only touched on using the current user that is running “PowerShell.exe”. In this article I want to pick up and go over how you would use the same methods, but as a different account. I will cover using both Windows Authentication (where supported) and SQL Login authentication.

在上一篇有关将PowerShell连接到SQL Server的文章中,我介绍了如何在PowerShell中使用各种方法连接到SQL Server。 在这些示例中,尽管我仅涉及使用正在运行“ PowerShell.exe”的当前用户。 在本文中,我想介绍一下如何使用相同的方法,但使用不同的帐户。 我将介绍如何使用Windows身份验证(在支持的地方)和SQL登录身份验证。

There is one object in PowerShell utilized for making connections as a separate account: PSCredential. This object is used to capture the new credentials. In most cases it allows you to securely pass in those credentials without making the account information visible in your script. In the examples below I am just going to use the “Get-Credential” command to build this object. The article referenced at the end of this article for securing your passwords in PowerShell goes over this command and others in more detail.

PowerShell中有一个对象用于作为独立帐户进行连接:PSCredential。 该对象用于捕获新的凭证。 在大多数情况下,它使您可以安全地传递这些凭据,而无需在脚本中显示帐户信息。 在下面的示例中,我将使用“ Get-Credential”命令来构建此对象。 本文末尾引用的有关在PowerShell中保护密码的文章更详细地介绍了此命令和其他命令。

选件 (Options)

As the previous article, the following are the options we will cover:

与上一篇文章一样,以下是我们将介绍的选项:

  • SQL Server PowerShell (SQLPS) SQL Server PowerShell(SQLPS)
  • SQL Server Management Objects (SMO) SQL Server管理对象(SMO)
  • .NET (System.Data.SqlClient) .NET(System.Data.SqlClient)

SQL Server PowerShell(SQLPS) (SQL Server PowerShell (SQLPS))

While SQLPS is still around a better module that Microsoft released with SSMS 2016 was renamed to “SqlServer”. This module is being expanded upon as SSMS updates are released so is more robust that SQLPS module. The methods shown below would work with either module though.

尽管SQLPS仍然围绕着一个更好的模块,但微软随SSMS 2016发布的模块被重命名为“ SqlServer”。 随着SSMS更新的发布,此模块正在扩展,因此比SQLPS模块更强大。 不过,以下所示的方法可与任一模块一起使用。

SqlServer提供程序 (SqlServer Provider)

SQLPS.exe, the utility, is not going to be touched on because it does not support changing the account before you connect. When you open that utility you are placed directly into the “SQLSERVER:” provider, without being able to change the account. The provider itself though, can be adjusted to use a separate account. If you have used the file provider in PowerShell to connect to remote shares (equivalent to”net use“) it works the same way.

实用程序SQLPS.exe不会被触及,因为它不支持在连接前更改帐户。 当您打开该实用程序时,将直接将其放置在“ SQLSERVER:”提供程序中,而无需更改帐户。 但是,提供者本身可以进行调整以使用单独的帐户。 如果您已使用PowerShell中的文件提供程序连接到远程共享(相当于“ net use”),则其工作方式相同。

The command to create a new drive in PowerShell is “New-PSDrive”. This command requires the following parameters to create the drive:

在PowerShell中创建新驱动器的命令是“ New-PSDrive”。 此命令需要以下参数来创建驱动器:

  • Name – this is used to do directory lookup, so instead of “SQLSERVER:” you would use the name provided 名称–用于执行目录查找,因此可以使用提供的名称代替“ SQLSERVER:”
  • PSProvider – this tells the command what provider to actually use, in our case it is SqlServer PSProvider –告诉命令实际使用哪个提供程序,在我们的例子中是SqlServer
  • Root – the root path you want to connect to (e.g. “SQLSERVER:”) 根–您要连接的根路径(例如“ SQLSERVER:”)
  • Credential – the account you want to make the connection under 凭据–您要建立连接的帐户
New-PsDrive -Name DefaultSql -PSProvider SqlServer -Root
'SQLSERVER:\SQL\SERVERNAME\DEFAULT' -Credential (Get-Credential)

The limitation you have with the SqlServer provider (both module and PSDrive) is it only supports SQL Login authentication. It creates the drive with a Windows account, but when you try to do a directory lookup on the drive you will see the exception:

SqlServer提供程序(模块和PSDrive两者)所具有的限制是它仅支持SQL登录身份验证。 它使用Windows帐户创建驱动器,但是当您尝试在驱动器上进行目录查找时,会看到以下异常:

You can see from this screen shot it errors that it does not exist. There is no associated login failure logged to SQL Server, so my belief is it was not implemented to properly handle using Windows Account as SMO supports. If you try using a SQL Login though, you can see a successful attempt to browse the drive:

您可以从该屏幕快照中看到它不存在的错误。 没有关联的登录失败记录到SQL Server,因此我相信,由于SMO支持,因此未实现使用Windows帐户正确处理它。 但是,如果尝试使用SQL登录名,则可以成功浏览驱动器:

SqlServer模块 (SqlServer Module)

The module is slowly growing with new commands each month, and has officially replaced the SQLPS module. I have found not all of the commands support the “-Credential” parameter though, only 24 out of 82 as of this article. You can easily find the ones that do by using the following command:

该模块每个月都有新命令在缓慢发展,并已正式取代SQLPS模块。 我发现虽然并非所有命令都支持“ -Credential”参数,但截至本文为止,仅82个命令中的24个支持。 您可以使用以下命令轻松找到要执行的操作:

Get-Command -Module SqlServer -ParameterName Credential

You will notice that the command “Invoke-Sqlcmd” is not listed. The “Invoke-Sqlcmd” command does let you pass in a username and password for a SQL Login, but only in plain text. The commands that do support the credential parameter have the same limitation as the provider, only accepting SQL Login authentication.

您会注意到命令“ Invoke-Sqlcmd”未列出。 “ Invoke-Sqlcmd”命令确实允许您输入SQL登录名的用户名和密码,但只能使用纯文本。 支持凭据参数的命令与提供程序具有相同的限制,仅接受SQL登录身份验证。

A short example that uses “Get-SqlErrorLog”:

一个使用“ Get-SqlErrorLog”的简短示例:

$cred = Get-Credential
Get-SqlErrorLog -ServerInstance MyServer -Credential $cred | select -Last 3

SQL Server管理对象(SMO) (SQL Server Management Objects (SMO))

SMO supports Windows or SQL Authentication, but connecting with SMO is a bit unique based on which authentication type you want to use. To just refresh, the lines to create our SMO server object are noted below and include just creating the PScredential object:

SMO支持Windows或SQL身份验证,但是根据要使用的身份验证类型,与SMO的连接有点独特。 为了刷新,下面将介绍创建SMO服务器对象的行,其中包括仅创建PScredential对象的行:

$cred = Get-Credential
Add-Type -AssemblyName
"Microsoft.SqlServer.Smo,Version=13.0.0.0,Culture=neutral,PublicKeyToken=8984
5dcd8080cc91"
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server MyServer

Once you have the server object create we work out passing in the account desired, based on which type is needed.

创建服务器对象后,我们将根据需要的类型来计算出所需的帐户。

SMO – Windows身份验证 (SMO – Windows Authentication)

To use a Windows account you have to let SMO know by setting some properties to true:

要使用Windows帐户,您必须通过将一些属性设置为true来让SMO知道:

$srv.ConnectionContext.LoginSecure = $true
$srv.ConnectionContext.ConnectAsUser = $true

We can then pass in the username and password from the credential variable and connect.

然后,我们可以从凭据变量中传入用户名和密码并进行连接。

``powershell $srv.ConnectionContext.ConnectAsUserName = $cred.username
$srv.ConnectionContext.ConnectAsUserPassword =
$cred.GetNetworkCredential().Password $srv.ConnectionContext.Connect() ```

SMO – SQL登录 (SMO – SQL Login)

In comparison to use a SQL Login account you set the LoginSecure to false, and then just pass in the username and password but we have to use a different set of properties:

与使用SQL登录帐户相比,将LoginSecure设置为false,然后仅传递用户名和密码,但是我们必须使用一组不同的属性:

$srv.ConnectionContext.LoginSecure = $false
$srv.ConnectionContext.set_Login($cred.username)
$srv.ConnectionContext.set_SecurePassword($cred.password)
$srv.ConnectionContext.Connect()

dbatools (dbatools)

The module dbatools is helping to make DBA’s lives easier where we do not have to remember all that SMO syntax. Instead of remembering all of the above properties based on which authentication type wouldn’t it be easier to just use a function to create the server object? Let me introduce you to “Connect-DbaSqlServer”, one of many commands in the dbatools module. This command is based on an internal function that is used within each command to build the needed server object for SMO. After you install dbatools it is as simple as the following lines:

dbatools模块正在帮助我们简化 DBA的工作,而不必记住所有SMO语法。 除了记住基于哪种身份验证类型的上述所有属性,仅使用函数创建服务器对象会更容易吗? 让我向您介绍“ Connect-DbaSqlServer”,它是dbatools模块中的许多命令之一。 该命令基于内部功能,该内部功能在每个命令中使用,以构建SMO所需的服务器对象。 安装dbatools之后,它就像下面几行一样简单:

Import-Module dbatools
$cred = Get-Credential
$srv = Connect-DbaSqlServer -Sqlserver MyServer -Credential $cred

Isn’t that much easier to use?

使用起来不是那么容易吗?

.NET(System.Data.SqlClient) (.NET (System.Data.SqlClient))

SqlClient only allows a SQL Login account to be provided. Which is expected as .NET utilizes the login that initiated the process for Windows Authentication. To utilize a SQL Login account we need to build a specific credential object, System.Data.SqlClient.SqlCredential. You have to pass in the username and the password (as SecureString). There is one extra thing required for the password. The SqlCredential requires that the password is read-only, so it cannot be altered once the connection is made. Which means once you set it as read-only it cannot be reverted, you would have to rebuild the object. Any attempt to modify that password will give you an invalid exception error.

SqlClient仅允许提供SQL登录帐户。 .NET可以利用启动Windows身份验证过程的登录名来实现。 要使用SQL登录帐户,我们需要构建一个特定的凭据对象System.Data.SqlClient.SqlCredential。 您必须输入用户名和密码(作为SecureString)。 密码还需要一件事。 SqlCredential要求密码为只读,因此一旦建立连接便无法更改密码。 这意味着一旦将其设置为只读,便无法还原,则必须重建该对象。 任何尝试修改该密码的操作都会给您一个无效的异常错误。

We can still use our PSCredential to collect the username and password. The following are the steps to take for building the SqlCredential object:

我们仍然可以使用我们的PSCredential来收集用户名和密码。 以下是构建SqlCredential对象要采取的步骤:

# First create the PSCredential object
$cred = Get-Credential#set the password as read only
$cred.Password.MakeReadOnly()# Create the SqlCredential object
$sqlCred = New-Object
System.Data.SqlClient.SqlCredential($cred.username,$cred.password)

After we have that we just need to set the credential for our connection:

有了之后,我们只需要设置连接的凭据即可:

$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = “Server=localhost\sql12;Initial Catalog=master”
$sqlConn.Credential = $sqlCred

结语 (Wrap Up)

As you probably noticed, SQL Login gets the most support in the options above. If you need to use Windows Authentication you have a few options but for the most part will need to start PowerShell as the needed Windows Account. PowerShell offers multiple options for connecting as a different Windows Account that are not directly related to SQL Server, if SQL Login is just not an option. You can look into commands like “Invoke-Command” or “Start-Process”, these provide an option to also pass in a Windows credential.

您可能已经注意到,SQL Login在上面的选项中获得了最大的支持。 如果您需要使用Windows身份验证,则可以选择几种方法,但大多数情况下需要以所需的Windows帐户启动PowerShell。 如果不选择SQL登录,PowerShell提供了多个选项作为不同的Windows帐户进行连接,这些选项与SQL Server没有直接关系。 您可以查看“ Invoke-Command”或“ Start-Process”之类的命令,这些命令提供了也可以传递Windows凭据的选项。

I hope the above information provides some help in better understanding using alternate credentials to connect to SQL Server.

我希望以上信息可以帮助您更好地理解使用备用凭据连接到SQL Server。

翻译自: https://www.sqlshack.com/connecting-powershell-to-sql-server-using-a-different-account/

将PowerShell连接到SQL Server –使用其他帐户相关推荐

  1. 将PowerShell连接到SQL Server

    介绍 (Introduction) PowerShell (aka Posh or just PS) is becoming more and more of a tool for operation ...

  2. 如何使用PowerShell创建简单SQL Server数据库登录对话框

    In this article, we'll be creating a SQL Server login form, as shown in the example below, using Pow ...

  3. 无法链接到SQL Server远程服务器的解决

    今天连接机房服务器的SQL Server 2005时出现错误,错误信息如下:   在建立与服务器的连接时出错.在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许 ...

  4. 若不能连接到sql server的localhost

    不能连接到sql server的localhost Windows+r打开命令,输入services.msc SQL服务没启动,我的电脑---管理---服务---SQL Server (MSSQLSE ...

  5. 开发常见错误解决(7)连接到SQL Server 2005出错

    在建立与服务器连接时出错.在连接到SQL Server 2005时,默认情况下SQL Server 2005不允许进行远程连接可能导致此失败.(provider:SQL网络连接,Error:26-定位 ...

  6. 成功解决无法连接到YLMF-201404228CG,在建立与服务器的连接时出错。在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许进行远程连接可能会导致此失败

    成功解决无法连接到YLMF-201404228CG,在建立与服务器的连接时出错.在连接到 SQL Server 2005 时,在默认的设置下 SQL Server 不允许进行远程连接可能会导致此失败 ...

  7. iis6上安装PHP5.3.2及连接到SQL Server 2005/2008的设置(原创)

    iis6上安装PHP5.3.2及连接到SQL Server 2005/2008的设置(原创) 新增一台win2003 server系统的服务器.以前其他的服务器上使用php5.0/5.1,数据库是SQ ...

  8. java sql 登录失败_java – 接收连接到SQL Server 2008的SQLException“用户登录失败”

    我试图通过 Java连接到SQL Server 2008. >我已将sqljdbc4.jar添加到我的项目库中. >没有为访问数据库的数据库设置用户名和密码(Windows身份验证). & ...

  9. 一个不知名的网站复制来的: java怎样连接到SQL server 2008

    教程:java怎样连接到SQL server 2008 为了写学校的实训课作业,想给数据库加个前端口,结果为了看似简单的java连解sql server 2008,刚才试验了不知道多少次,来来回回数不 ...

最新文章

  1. html动态加载js方法,如何通过JavaScript动态加载js
  2. Karrigell介绍
  3. ubuntu系统下matplotlib中文乱码问题
  4. SQL -- 是否或推断线相交以在其内部的平面
  5. notepad正则表达式替换_正则表达式装逼(实用)指南
  6. 多线程计算0-100 0-200 的和
  7. Flask框架(flask中对cookie的处理(设置cookie、获取cookie、删除cookie))
  8. Java黑皮书课后题第8章:**8.17(金融风暴)银行会互相借款……银行的总资产是它当时的余款减去它欠其他银行的贷款。如果一个银行的总资产在某个限以下,那么这个银行是不安全的。编写程序,找出所有不安
  9. 数组动态初始化【应用】
  10. Redis面试 - 如何保证 redis 的高并发和高可用?
  11. Linux运行级别介绍
  12. LA 4254 贪心
  13. 使用 Gogs 搭建自己的 Git 服务器
  14. hulu往届笔试题及解题思路
  15. 万字拆解孩子王:充满矛盾的母婴零售之王
  16. LLVM 系统入门¶
  17. 判断邮箱格式是否正确
  18. webrtc 快速搭建 视频通话 视频会议
  19. 解决WPS每点击一下保存,就会出现tmp文件
  20. MES的发展历程及功能模块

热门文章

  1. 海康威视面试-java应用开发
  2. bzoj 4337 树的同构
  3. UVA116 单向 DSP(多段图最短路)
  4. MySQL主从复制的原理及配置方法(比较详细)
  5. 低姿态生活,高境界做人
  6. ASP.NET MVC+LINQ开发一个图书销售站点(6):创建数据层
  7. http,tcp的长连接和短连接
  8. Linux---高级IO
  9. 【零基础学Java】—多线程(四十九)
  10. Intellij IDLE 中javafx使用与配置