Month: September 2023

List user logon sessions on all servers in AD domain

# Define the OU path where your servers are located
$ouPath = "OU=servers,DC=domain,DC=local"  # Replace with your OU path

# Get a list of servers in the specified OU
$servers = Get-ADComputer -Filter {OperatingSystem -like "Windows Server*"} -SearchBase $ouPath | Select-Object -ExpandProperty Name

# Loop through each server and query logged-on users
foreach ($server in $servers) {
    try {
        # Use WMI to query logged-on user information
        $loggedOnUsers = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $server | Select-Object -ExpandProperty UserName

        if ($loggedOnUsers) {
            Write-Host "Logged-on users on $server"
            $loggedOnUsers | ForEach-Object {
                Write-Host "  $_"
            }
        } else {
            Write-Host "No users logged on to $server"
        }
    } catch {
        Write-Host "Failed to query $server"
    }
}

If you want to search by specific names, you can adjust the filter to this –

Get-ADComputer -Filter {Name -like "AZ-EUW-*"} -SearchBase $ouPath

Remotely change all DNS IP’s on Windows Servers in AD

# Define the new DNS server IP addresses
$dnsServers = "8.8.8.8", "1.1.1.1", "8.8.4.4"

# Define the OU where you want to change DNS servers
$OU = "OU=server,DC=domain,DC=local"  # Replace with your actual OU path

# Create an array to store results
$results = @()

# Get all computer objects in the specified OU
$computers = Get-ADComputer -Filter {Name -like "AZ-EIW-DC01*"} -SearchBase $OU

# Loop through each computer object
foreach ($computer in $computers) {
    $computerName = $computer.Name
    $computerDN = $computer.DistinguishedName

    try {
        # Set the DNS server IP addresses on the remote computer
        Invoke-Command -ComputerName $computerName -ScriptBlock {
            $networkAdapter = Get-NetAdapter | Where-Object { $_.Status -eq 'Up' }
            Set-DnsClientServerAddress -InterfaceAlias $networkAdapter.Name -ServerAddresses $using:dnsServers -ErrorAction Stop
        }

        # Record the success in the results array
        $results += [PSCustomObject]@{
            ComputerName = $computerName
            Status = "Success"
        }
    }
    catch {
        # If an error occurs, record the failure in the results array
        $results += [PSCustomObject]@{
            ComputerName = $computerName
            Status = "Error: $_"
        }
    }
}

# Export the results to a CSV file
$results | Export-Csv -Path "C:\Temp\DNSChangeResults.csv" -NoTypeInformation

# Display the results on the console
$results