Tag: windows

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

Report of DNS settings on all Windows Servers via powershell

$AllServers=Get-ADComputer -Filter {OperatingSystem -Like "Windows Server*" -and Enabled -eq 'True'}
$Servers = ForEach ($Server in $AllServers){

$Result=Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "IPEnabled = 'True'" -Property DNSServerSearchOrder -ComputerName $Server.Name

New-Object -TypeName PSObject -Property @{
ComputerName = $Server.Name -join ','
DNSServerSearchOrder = $Result.DNSServerSearchOrder -join ','

} | Select-Object ComputerName,DNSServerSearchOrder | Export-Csv -Path C:\Temp\ServerDNSSettings.csv -NoTypeInformation -Append
}

Run this from a domain controller and it will report the DNS servers set on the NIC card.

Find memory in use by sql databases

Run this query in SSMS to show how much memory the DB’s are currently using.

DECLARE @total_buffer INT;

SELECT @total_buffer = cntr_value
FROM sys.dm_os_performance_counters 
WHERE RTRIM([object_name]) LIKE '%Buffer Manager'
AND counter_name = 'Database Pages';

;WITH src AS
(
SELECT 
database_id, db_buffer_pages = COUNT_BIG(*)
FROM sys.dm_os_buffer_descriptors
--WHERE database_id BETWEEN 5 AND 32766
GROUP BY database_id
)
SELECT
[db_name] = CASE [database_id] WHEN 32767 
THEN 'Resource DB' 
ELSE DB_NAME([database_id]) END,
db_buffer_pages,
db_buffer_MB = db_buffer_pages / 128,
db_buffer_percent = CONVERT(DECIMAL(6,3), 
db_buffer_pages * 100.0 / @total_buffer)
FROM src
ORDER BY db_buffer_MB DESC;

Search group policies for specific setting

Sometimes you need to search in a domain environment for a specific setting in GPO’s. This script will search through all the GPO’s in the domain and list the results at the end!

# Get the string you want to search for
$string = Read-Host -Prompt "What string do you want to search for?"

# Set the domain to search for GPOs
$DomainName = $env:USERDNSDOMAIN

# Find all GPO's in the current domain of logged on user
write-host "Finding all the GPO's in $DomainName"
Import-Module grouppolicy
$allGposInDomain = Get-GPO -All -Domain $DomainName
[string[]] $MatchedGPOList = @()

# Look through each GPO's XML for the string
Write-Host "Starting search...."
foreach ($gpo in $allGposInDomain) {
    $report = Get-GPOReport -Guid $gpo.Id -ReportType Xml
    if ($report -match $string) {
        write-host "********** Match found in: $($gpo.DisplayName) **********" -foregroundcolor "Green"
        $MatchedGPOList += "$($gpo.DisplayName)";
    } # end if
    else {
        Write-Host "No match in: $($gpo.DisplayName)"
    } # end else
} # end foreach
write-host "`r`n"
write-host "Results: **************" -foregroundcolor "Yellow"
foreach ($match in $MatchedGPOList) {
    write-host "Match found in: $($match)" -foregroundcolor "Green"
}

Check password expiry Office365

$cred = Get-Credential “[email protected]

Connect-MsolService -Credential $cred

$domain = Get-MsolDomain | where {$_.IsDefault -eq $true}

$PasswordPolicy = Get-MsolPasswordPolicy -DomainName $domain.Name

$Account = “[email protected]” # Change HERE !!

$UserPrincipal = Get-MsolUser -UserPrincipalName $Account

$UserPrincipal | fl PasswordNeverExpires

$PasswordExpirationDate = $UserPrincipal.LastPasswordChangeTimestamp.AddDays($PasswordPolicy.ValidityPeriod)

Write-host “Password will Expire on : $PasswordExpirationDate”

$StartDate = (GET-DATE)
$DaysLeft = NEW-TIMESPAN -Start $StartDate -End $PasswordExpirationDate
$DaysLeft = [math]::Floor($DaysLeft.TotalDays)

Write-host “Password will Expire in # Days : $DaysLeft”

$UserPrincipal | select DisplayName, LastPasswordChangeTimeStamp,@{Name=”PasswordAge”;Expression={((Get-Date).ToUniversalTime())-$_.LastPasswordChangeTimeStamp}} | sort-object PasswordAge -desc

Replace registry keys

I was recently tasked with migrating a software which had all of it’s configuration stored in the registry. The only way to update it “officially” was by uninstalling and reinstalling the whole suite, since this would take too long for 30 machines, I decided to script it to quicken things up.

The way this works is by using the PowerShell functionality to search the registry –

foreach ($a in Get-ChildItem -Path ‘HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer’ -Recurse) {
  $a.Property | Where-Object {
    $a.GetValue($_) -Like “*value123*”
  } | ForEach-Object {
    $CurrentValue = $a.GetValue($_)
    $ReplacedValue = $CurrentValue.Replace(“value123", “value1234”)
    Write-Output “Changing value of $a\$_ from ‘$CurrentValue’ to ‘$ReplacedValue’”
    Set-ItemProperty -Path Registry::$a -Name $_ -Value $ReplacedValue
  }
}

The script explained –

i) It is searching in the Installer path with -Recurse, this means all the folder underneath it also.

ii) GetValue – This is going to first build the search index with any registry key containing value123. It will find values such as https://value123.domain.com or just value123 alone.

iii) ReplacedValue – We are giving it the value123 to identify and then replace it with value1234. It will not replace the whole string https://value123.domain.com, it will just replace it to https://value1234.domain.com

I hope this comes in handy for anyone searching to do something similar!

Re-install Windows 10 Store

We recently switched domains to have a central domain name instead of a location dependent setup. Whilst using a user profile migration tool, we came across a bug where the Windows Store would either disappear or just be unusable. This means that several useful applications for the end-users would stop working, for example : Sticky Notes, Calculator and even Microsoft Photos.

The solution was to download all the packages again and reset the store.

Run the below from powershell (run as admin) to download/install all packages

Get-AppxPackage -AllUsers| Foreach {Add-AppxPackage -DisableDevelopmentMode -Register “$($_.InstallLocation)\AppXManifest.xml”} 

The above command might throw a few errors, but will still complete. Once done, run the below from a command prompt ( run as admin )

wsreset

Once you have run the wsreset, you should either see the Store open up automatically or you’ll be able to find it to install all the applications required again.

SFTP Automatic using winSCP


This script is partially generated from WinSCP automation, however has been modified to put two files onto the remote server with a timestamp and remove any files which are over 14 Days old in that specific remote directory.

Please note that the SSH-RSA key has to be changed to match your host being accessed by winscp.

@echo off
“C:\Program Files (x86)\WinSCP\WinSCP.com” ^
/command ^
“open sftp://YOURUSERNAME:[email protected]/ -hostkey=””ssh-rsa 2048 X7f9U4Io2IKF8G/m/OenvXvkDGuMGm0PI5b0/BGOpRM=”” -rawsettings FSProtocol=2″ ^
“lcd “”E:\YOURFOLDER””” ^
“cd /REMOTEFOLDER” ^
“put “”FILE1.csv”” “”FILE1%%TIMESTAMP#yyyymmdd%%.csv”” ” ^
“put “”FILE2.csv”” “”FILE2%%TIMESTAMP#yyyymmdd%%.csv”” ” ^
“rm *<14D ” ^
“exit”


set WINSCP_RESULT=%ERRORLEVEL%
if %WINSCP_RESULT% equ 0 (
echo Success
) else (
echo Error
)

exit /b %WINSCP_RESULT%

Remove “Network” from Windows Server Explorer sidebar

This is a registry edit that will remove the “network” icon from the file explorer window on Server 2012 R2 and most likely even Windows 7/8/10.

This is done by creating a registry key via GPO under User Configuration.

User Configuration, Preferences, Registry

Right click and choose New, Registry Item


Hive: HKEY_LOCAL_MACHINE
Key Path: SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\NonEnum
Value name: {F02C1A0D-BE21-4350-88B0-7367FC96EF3C}
Value type: REG_DWORD
Value Data (hex): 00000001