2016-05-31 163 views
0

这里是我当前的代码:如何通过PowerShell使用Windows身份验证而非本地身份验证连接到SQL?

[string] $Server= "server" 
[string] $Database = "database" 
[string] $UserSqlQuery= $("SELECT * FROM [dbo].[User]") 
[string] $UserID = "userid" 
[string] $Pass = "pass" 

$resultsDataTable = New-Object System.Data.DataTable 
$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery $UserId $Pass 

# executes a query and populates the $datatable with the data 
function ExecuteSqlQuery ($Server, $Database, $SQLQuery, $UserID, $Pass) { 
    $Datatable = New-Object System.Data.DataTable 

    $Connection = New-Object System.Data.SQLClient.SQLConnection 
    $Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;User ID = '$UserID';Password='$Pass';" 
    $Connection.Open() 
    $Command = New-Object System.Data.SQLClient.SQLCommand 
    $Command.Connection = $Connection 
    $Command.CommandText = $SQLQuery 
    $Reader = $Command.ExecuteReader() 
    $Datatable.Load($Reader) 
    $Connection.Close() 

    return $Datatable 
} 

#validate we got data 
Write-Host ("The table contains: " + $resultsDataTable.Rows.Count + " rows") 

所以我知道我可以为了使用Windows身份验证与集成安全性=真更换用户名和密码。问题是我试图使用一个Windows身份验证,而不是我当前的身份验证来获取SQL。有没有办法做到这一点?谢谢。

回答

0

如果SQL连接字符串需要指定然后集成安全性,将需要用户模拟。如果按住shift键并右键单击powershell图标,则可以通过选择“运行方式”并输入正确的Windows凭据来以另一用户身份运行PowerShell进程。

如果脚本必须在一个Windows用户下开始运行,但是为SQL连接模拟不同的Windows用户,则需要一些额外的脚本来设置该模拟。这里有一个可能有用的链接 - http://poshcode.org/1867

相关问题