Find who is connected to MS SQL.

Find usernames and IP of connections to Microsoft SQL

SELECT DB_NAME(database_id) as [DB]
    , login_name
    , nt_domain
    , nt_user_name
    , status
    , host_name
    , program_name
    , COUNT(*) AS [Connections]
FROM sys.dm_exec_sessions
WHERE database_id > 0 -- OR 4 for user DBs
GROUP BY database_id, login_name, status, host_name, program_name, nt_domain, nt_user_name;

Function for Powershell to test if TCP port answers

function Test-Port($hostname, $port)
    # This works no matter in which form we get $host - hostname or ip address
    try {
        $ip = [System.Net.Dns]::GetHostAddresses($hostname) | 
            select-object IPAddressToString -expandproperty  IPAddressToString
        if($ip.GetType().Name -eq "Object[]")
            #If we have several ip's for that address, let's take first one
            $ip = $ip[0]
    } catch {
        Write-Host "Possibly $hostname is wrong hostname or IP"
    $t = New-Object Net.Sockets.TcpClient
    # We use Try\Catch to remove exception info from console if we can't connect
    } catch {}



Powershell: Start all services with startuptype: Automatic on remote server


param (
$services = Get-Service -Computer $Computer| Where-Object { $_.Starttype -like "Automatic*" -and $_.status -notlike "Running" } |select name, starttype, status

if ($services) {
foreach ( $service in $services){
get-service -computername $computer -name $ | start-service
write-host "Starting service:" $ "on Computer:" $computer -ForegroundColor green
else {
write-host "No services to start" -ForegroundColor yellow

Remote powershell

Allow remote powershell
Enable-PSRemoting -Force 
Enable-WSManCredSSP -Role Server -Force
Get-Service winrm | Start-Service 
Enable-WSManCredSSP -Role Client -DelegateComputer * -Force 
Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowFreshCredentials -Name WSMan -Value WSMAN/* 
Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\Lsa\Credssp\PolicyDefaults\AllowFreshCredentialsDomain -Name WSMan -Value WSMAN/*  

Test from an other machine: 
Invoke-Command -ComputerName Remote-Server -ScriptBlock {Get-host}

Allow crossdomain:
On remote server do the above and:
New-Itemproperty -name LocalAccountTokenFilterPolicy -path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -propertyType DWord -value 1

On remote and local machine run:
Set-item wsman:localhost\client\trustedhosts -value 'server1,server2,server3'

Test from an other machine: 
$credential = Get-Credential
Invoke-Command -ComputerName RM-SERVER -ScriptBlock {Get-Process} -Credential $credential