How to Add a Windows Domain Login to SQL Server via T-SQL

Using the SQL Server Management Studio (SSMS) GUI to add logins is slow and inefficient. If you need to quickly add a Windows domain account to your SQL Server and grant it full administrative privileges, using T-SQL is the most direct approach.

Here is the exact script to create the domain login, assign it to the sysadmin role, and verify the permissions, along with the command-line steps to test it.

The Script

This script provisions a Windows account in SQL Server and elevates it. Replace DOMAIN\UserName and ServerName with your actual environment variables.

-- Switch to the master database
USE master;
GO

-- Create the domain login (Example: [DOMAIN\UserName])
CREATE LOGIN [DOMAIN\UserName] FROM WINDOWS; GO -- Add the login to the sysadmin server role -- Note: Only run this once. Running it multiple times is unnecessary. ALTER SERVER ROLE sysadmin ADD MEMBER [DOMAIN\UserName]; GO -- Verify the login exists SELECT name, type_desc FROM sys.server_principals WHERE name = 'DOMAIN\UserName'; GO -- Verify sysadmin membership SELECT p.name, r.name AS ServerRole FROM sys.server_role_members rm JOIN sys.server_principals p ON rm.member_principal_id = p.principal_id JOIN sys.server_principals r ON rm.role_principal_id = r.principal_id WHERE p.name = 'DOMAIN\UserName' AND r.name = 'sysadmin'; GO /* ========================================= TESTING VIA COMMAND LINE (CMD) ========================================= */ -- Test login if you are currently logged into Windows as the target user: -- sqlcmd -S ServerName -E -- Test login if you are logged in as a different user: -- runas /netonly /user:DOMAIN\UserName "sqlcmd -S ServerName -E"

Key Technical Details

  • Security Warning: The sysadmin role grants unrestricted, complete control over the SQL Server instance. Only assign this to required DBAs or critical service accounts.
  • Role Assignment: You only need to run the ALTER SERVER ROLE command once. Do not duplicate it in your scripts.
  • Impersonation Testing: The runas /netonly flag is the fastest way to test the new credentials over the network without having to log out of your current Windows desktop session.

Identify VM RAM Consumption in VMware using PowerCLI

Native vCenter reporting is clunky. It gives you graphs and raw data dumps, but it will not hand you a perfectly formatted, easily readable spreadsheet without manual effort or expensive add-ons. If you want a clean report of your cluster's CPU and Memory utilization, you must automate it with PowerCLI.

Here is how to extract exact capacity and utilization percentages for every host in your cluster.

The Script

This script calculates the CPU and Memory usage percentages for the hosts in a target cluster and exports the clean data directly to a CSV file.

# Connect to your vCenter Server
Connect-VIServer -Server "YOUR_VCENTER_IP_OR_FQDN"

$ClusterName = "YOUR_CLUSTER_NAME"
$Hosts = Get-Cluster -Name $ClusterName | Get-VMHost
$Report = @()

foreach ($VMHost in $Hosts) {
    $CpuUsagePct = [math]::Round(($VMHost.CpuUsageMhz / $VMHost.CpuTotalMhz) * 100, 2)
    $MemUsagePct = [math]::Round(($VMHost.MemoryUsageGB / $VMHost.MemoryTotalGB) * 100, 2)

    $Report += [PSCustomObject]@{
        HostName         = $VMHost.Name
        Cluster          = $ClusterName
        CpuTotalMHz      = $VMHost.CpuTotalMhz
        CpuUsageMHz      = $VMHost.CpuUsageMhz
        CpuUsagePercent  = "$CpuUsagePct %"
        MemTotalGB       = [math]::Round($VMHost.MemoryTotalGB, 2)
        MemUsageGB       = [math]::Round($VMHost.MemoryUsageGB, 2)
        MemUsagePercent  = "$MemUsagePct %"
    }
}

$Report | Export-Csv -Path "C:\Host_Utilization_Report.csv" -NoTypeInformation
Disconnect-VIServer -Confirm:$false

Key Technical Details

  • Calculated Metrics: It translates raw MHz and GB into a readable percentage using native math functions to round to two decimal places.
  • Prerequisites: You must have the VMware.PowerCLI module installed and be able to authenticate to the vCenter server.
  • Execution: Simply replace the vCenter and Cluster variables with your actual environment names.

Generate an ESXi Host CPU and Memory Utilization Report using PowerCLI

Native vCenter reporting is clunky. It gives you graphs and raw data dumps, but it will not hand you a perfectly formatted, easily readable spreadsheet without manual effort or expensive add-ons. If you want a clean report of your cluster's CPU and Memory utilization, you must automate it with PowerCLI.

Here is how to extract exact capacity and utilization percentages for every host in your cluster.

The Script

This script calculates the CPU and Memory usage percentages for the hosts in a target cluster and exports the clean data directly to a CSV file.

# Connect to your vCenter Server
Connect-VIServer -Server "YOUR_VCENTER_IP_OR_FQDN"

$ClusterName = "YOUR_CLUSTER_NAME"
$Hosts = Get-Cluster -Name $ClusterName | Get-VMHost
$Report = @()

foreach ($VMHost in $Hosts) {
    $CpuUsagePct = [math]::Round(($VMHost.CpuUsageMhz / $VMHost.CpuTotalMhz) * 100, 2)
    $MemUsagePct = [math]::Round(($VMHost.MemoryUsageGB / $VMHost.MemoryTotalGB) * 100, 2)

    $Report += [PSCustomObject]@{
        HostName         = $VMHost.Name
        Cluster          = $ClusterName
        CpuTotalMHz      = $VMHost.CpuTotalMhz
        CpuUsageMHz      = $VMHost.CpuUsageMhz
        CpuUsagePercent  = "$CpuUsagePct %"
        MemTotalGB       = [math]::Round($VMHost.MemoryTotalGB, 2)
        MemUsageGB       = [math]::Round($VMHost.MemoryUsageGB, 2)
        MemUsagePercent  = "$MemUsagePct %"
    }
}

$Report | Export-Csv -Path "C:\Host_Utilization_Report.csv" -NoTypeInformation
Disconnect-VIServer -Confirm:$false

Key Technical Details

  • Calculated Metrics: It translates raw MHz and GB into a readable percentage using native math functions to round to two decimal places.
  • Prerequisites: You must have the VMware.PowerCLI module installed and be able to authenticate to the vCenter server.
  • Execution: Simply replace the vCenter and Cluster variables with your actual environment names.

How to Verify File Integrity Using PowerShell (SHA256)

When you download ISO files, patches, or software packages, corruption and tampering are real risks. Installing a corrupted infrastructure file, like a VMware ESXi image, will break your system. Don't assume a download finished perfectly—verify it.

Windows has a built-in way to do this using the PowerShell Get-FileHash command.

The Basic Command

To calculate the SHA256 hash of a file, use the following syntax:

Get-FileHash "C:\Path\To\Your\File.iso" -Algorithm SHA256

Real-World Example

Running the command against an ESXi ISO looks like this:

Get-FileHash "C:\Downloads\ESXi.iso" -Algorithm SHA256

Output:

Algorithm       Hash                                                                   Path
---------       ----                                                                   ----
SHA256          3F2A9C6D5B3...                                                         C:\Downloads\ESXi.iso

The Hash value is the unique digital fingerprint of your file.

Extracting Just the Hash

If you only need the raw hash string for a script or a quick comparison, wrap the command in parentheses and call the .Hash property. This drops the formatting and path details:

(Get-FileHash "C:\Downloads\ESXi.iso" -Algorithm SHA256).Hash

Automating the Comparison

Vendors provide the expected checksum on their download pages. Instead of manually comparing a 64-character string, let PowerShell do it:

$expected = "PUT_EXPECTED_HASH_HERE"
$actual = (Get-FileHash "C:\Downloads\ESXi.iso" -Algorithm SHA256).Hash

if ($actual -eq $expected) {
    Write-Output "File is valid."
} else {
    Write-Output "File is corrupted or modified. Do not use."
}

Key Technical Details

  • Case-Insensitive: SHA256 string comparisons do not care about uppercase or lowercase letters.
  • Compatibility: This command works natively on PowerShell 5+ and PowerShell 7.
  • Primary Use Cases: Validating ISO files, software installers, and critical patch updates.

Verifying hashes is a mandatory step for secure system administration. Use Get-FileHash to confirm file integrity before moving anything into production.

How to Build a 1-Line PowerShell Ping Scanner (Subnet Sweep)

When you need to know which IP addresses are active on a network, you do not need to download a sketchy third-party GUI tool. You already have PowerShell.

You can perform a full subnet ping sweep in seconds using a single line of code.

However, I will be brutally honest: the standard command most people find online is flawed.

Usually, people suggest this:

1..200 | ForEach-Object { Test-Connection -ComputerName 192.168.4.$_ -Count 1 -Quiet }

That command executes perfectly, but the output is useless. Because it uses the "-Quiet" parameter by itself, PowerShell simply outputs a massive, unreadable wall of "True" and "False". You will not know which IP address is actually returning the "True".

Here is the corrected, practical version that actually tells you which IP addresses are online.

The Corrected 1-Line Scanner

Use this to print the IP address only if the machine responds.

My PowerShell 1-Liner

1..200 | ForEach-Object { $ip = "192.168.4.$_"; if (Test-Connection -ComputerName $ip -Count 1 -Quiet) { Write-Output "$ip is UP" } }

Output :

Stop Wasting Time Clicking "Properties": A PowerShell Script to Find Folders Over 1GB

Windows disk management is fundamentally broken. When your C: drive turns red, the native tools are useless. Clicking "Properties" on every single folder to see what is eating your storage is a massive waste of time.

You need automation. You need to see exactly where the heavy data lives without digging through nested directories.

Here is a straightforward PowerShell script that scans a specific path, calculates the size of every subfolder, and prints a clean, visual tree of anything over 1GB.

The Script

Copy this directly into your PowerShell environment or save it as a .ps1 file

The PowerShell Script

function Get-FolderTreeSize {
    param (
        [string]$Path = "C:\",
        [int]$Level = 0,
        [double]$MinSizeGB = 1
    )

    $folders = Get-ChildItem -Path $Path -Directory -ErrorAction SilentlyContinue

    foreach ($folder in $folders) {
        $size = (Get-ChildItem $folder.FullName -Recurse -File -ErrorAction SilentlyContinue |
                 Measure-Object Length -Sum).Sum

        $sizeGB = $size / 1GB

        # Show only if greater than 1 GB
        if ($sizeGB -ge $MinSizeGB) {
            $indent = "  " * ($Level * 2)
            $sizeFormatted = [math]::Round($sizeGB, 2)

            Write-Output "$indent|-- $($folder.Name) [$sizeFormatted GB]"

            # Go deeper only for large folders
            Get-FolderTreeSize -Path $folder.FullName -Level ($Level + 1) -MinSizeGB $MinSizeGB
        }
    }
}

# Run for Program Files
Get-FolderTreeSize -Path "C:\Program Files" -MinSizeGB 1

How It Works

This is not a complex script, but it is highly efficient. Here is exactly what it is doing

  • Targeted Scanning ($Path): It starts at your designated path. The example above defaults to checking C:\Program Files.

  • Silent Error Handling (-ErrorAction SilentlyContinue): Windows will block access to system or hidden folders. This parameter tells the script to ignore those access denied errors and keep moving, rather than filling your screen with red text.

  • Math on the Fly (Measure-Object): It looks inside every folder, grabs the byte size of every file, adds them up, and divides by 1GB to give you a readable number.

  • Recursive Logic (Get-FolderTreeSize calls itself): If it finds a folder over 1GB, it dives into that specific folder to see what is causing the bloat, automatically indenting the output so you can read it like a map.

How to Run It

  1. Open Windows PowerShell (Run as Administrator if you want to scan restricted system folders).

  2. Paste the entire block of code above and press Enter.

  3. The script will immediately output a clean list of every folder over 1GB in your Program Files.

If you want to scan your entire C:\ drive instead, just change the last line to: Get-FolderTreeSize -Path "C:\" -MinSizeGB 1