문제

with following code you list all users that are connected to certain DB

[System.Reflection.Assembly]::LoadWithPartialName(‘Microsoft.SqlServer.SMO’) | out-null
$Sql = New-Object (‘Microsoft.SqlServer.Management.Smo.Server’) “DEVSQL”
$DB = $Sql.Databases.Item("TestDB")
$DB.Users

Is there a way to get hostnames of the computers that users are connected from ? Something like query below.

select distinct hostname, loginame, db_name(dbid)
from master..sysprocesses 
where db_name(dbid) = 'TestDB'
도움이 되었습니까?

해결책

First, the PowerShell code you posted returns ALL database users, not just the ones that are currently connected.

In order to get the host and login info for current processes use this code:

[System.Reflection.Assembly]::LoadWithPartialName(‘Microsoft.SqlServer.SMO’) | out-null
$Sql = New-Object (‘Microsoft.SqlServer.Management.Smo.Server’) “DEVSQL”
$sql.EnumProcesses() | Where_Object {$_.Database -eq "TestDB"} | Select host,login

다른 팁

Normally I'd suggest sp_who2 but its output doesn't work with PowerShell. However, sp_who will.

invoke-sqlcmd -server $SERVERNAME -query "exec sp_who"|format-table -autosize

Or if you want just the hostnames

invoke-sqlcmd -server $SERVERNAME -query "exec sp_who"|select-object -property hostname -unique | format-table -autosize;

If you don't have the SQLPS module available, substitute in the appropriate ADO.NET methods.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top