Question

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'
Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top