我有以下代码用于创建与SQL Server的可信连接并将结果作为DataTable返回:
function Execute-SQLQuery {
param (
[Parameter(Mandatory = $true)]
[string]$DbInstance
,
[Parameter(Mandatory = $true)]
[string]$DbCatalog
,
[Parameter(Mandatory = $true)]
[string]$Query
,
[Parameter(Mandatory = $false)]
[int]$CommandTimeoutSeconds = 30 #this is the SQL default
,
[Parameter(Mandatory = $false)]
[System.Management.Automation.Credential()]
[System.Management.Automation.PSCredential]$Credential=[System.Management.Automation.PSCredential]::Empty
)
begin {
$connectionString = ("Server={0};Database={1};Integrated Security=True;" -f $DbInstance,$DbCatalog)
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
#$connection.Credential = $Credential #this is for SQL credentials only
$connection.Open()
}
process {
$command = $connection.CreateCommand()
$command.CommandTimeout = $CommandTimeoutSeconds
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object “System.Data.DataTable”
$table.Load($result)
Write-Output $table
}
end {
$connection.Close()
}
}
我想启用它,以便我可以指定不同的域凭据。
连接对象上的Credential
属性用于SQL凭据(System.Data.SqlClient.SqlCredential
);这不是我所追求的;我想冒充不同的域用户。
我可以使用凭据添加运行invoke-command
的代码,然后在其中调用此函数;然而,这种解决方案有难闻的气味/我确定应该存在更好的东西...
更新
根据找到的一些代码here我修改了我的代码如下
if($Credential -and ($Credential -ne [System.Management.Automation.PSCredential]::Empty)) {
#remove integrated security to allow credential to be specified
$connectionString = ("Server={0};Database={1};" -f $DbInstance,$DbCatalog) #Integrated Security=True;
#make password read only to allow for conversion
$Credential.Password.MakeReadOnly();
#convert to SQL credential and assign to credential property
$connection.Credential = New-Object System.Data.SqlClient.SqlCredential($Credential.UserName, $Credential.Password);
}
然而,这没有工作/给出错误:Exception calling "Open" with "0" argument(s): "Login failed for user 'myDomain\myUsername'
。
我认为这是我原先的想法;即它期望一个真正的SQL用户,而不仅仅是一个有权访问SQL DB的用户。
注意:我已经通过SSMS确认该用户确实可以访问相关数据库。
现在,我的解决方法是将凭证参数保留其默认值(将其保留到位,以便以后可以轻松实现此功能;即使此参数不执行任何操作可能会产生误导)我正在运行我的powershell ISE会话作为相关的用户帐户;不理想,但足以满足我的直接需求。