= Cheatsheet Windows Management =
**Summary**: Windows Management hints, tips, oneliners and best practices. \\
**Date**: 8 December 2024 \\
{{tag>cheatsheet windows powershell}}
== Windows Version ==
To find out which windows edition and version you run simply run this command, this will show you a screen with information about the edition, service pack and build number:
winver.exe
== Windows Service Management ==
> Stop Windows Service
# Stop the service while checking the state for x² seconds and kill it if that doesn't work
Write-Host "Stopping Service: $servicename; Status: Initiating"
$sleeper = 1
while (((Get-Service -Name "$servicename").Status -ne "Stopped") -AND ($sleeper -lt 128)){
if ($sleeper -eq 1){
Stop-Service -Name "$servicename"
} elseif ($sleeper -eq 32){
Stop-Service -Name "$servicename" -Force -NoWait
} elseif ($sleeper -eq 64){
# Try to kill the process now
$servicepid = (Get-CimInstance win32_service -Filter "Name = '$servicename'").ProcessId
try{
Stop-Process -id $servicepid -Force
}catch{
Throw "Stopping Service: $servicename; Stopping process: $servicepid; Status: Failed; Error: $($_.Exception.Message)"
}
}
if ($alllogs -eq "True"){Write-Host "Stopping Service: $servicename; Sleeptime: $sleeper seconds"}
Start-Sleep -Seconds $sleeper
$sleeper = $sleeper * 2
}
\\
>Restart all Windows Services
get-service -name grn* -ComputerName appprd02 | Restart-Service -Verbose
\\
>Start all stopped Windows Services
Get-Service -Name grn* -ComputerName appprd01,appprd02,appprd03,appacc01,appacc02,apptst01,apptst02,appdev01,appdev02 | Where-Object {$_.Status -eq 'Stopped'} | Start-Service -Verbose
Get-Service | where {($_.Status -eq 'Stopped') -and ($_.name -like 'Grn*') -and ($_.StartType -eq 'Automatic')} | Start-Service
Note: -ComputerName only works in PS 5
\\
> Install Windows Service depends on Powershell version
if ($($PSVersionTable.PSVersion).Major -eq 7){
New-Service -Name $serviceName -BinaryPathName $binaryAppExecutable -StartupType "AutomaticDelayedStart" -Credential $appuserCredentials
}else {
New-Service -Name $serviceName -BinaryPathName $binaryAppExecutable -StartupType "Automatic" -Credential $appuserCredentials
sc.exe config $serviceName start= delayed-auto
}
Note: PS 5 does not understand the startuptype AutomaticDelayedStart
\\
> Delete Windows Service
sc.exe delete windows.service
Note: In cmd you can use sc, in powershell sc is an alias for set-content, so you need to use sc.exe
== Telnet Client ==
Windows Server comes by default without a telnet client which is a no go in my opinion.
I used these steps to add the telnet client to Windows Server active features:
# Open Server Manager by clicking Start -> 'Server Manager'
# Click on 'features' from the left panel in Server Manager
# Click on 'Add Features'
# From the available list of features select 'Telnet Client' and click 'Next'
# Click on 'Install'
# Click 'Close'
Now telnet client works!
== Windows IIS Management ==
> Restart all App Pools
& $env:windir\system32\inetsrv\appcmd list apppools /state:Started /xml | & $env:windir\system32\inetsrv\appcmd recycle apppools /in
Note: This does not start stopped app pools
\\
> Restart all App Pools Remotely
$servers = 'web01','web02','web03'
Invoke-Command -ComputerName $servers { & $env:windir\system32\inetsrv\appcmd list apppools /state:Started /xml | & $env:windir\system32\inetsrv\appcmd recycle apppools /in }
Note:This does not start stopped app pools
\\
> Get the process for a IIS Site (always running under w3wp):
# Site and Appool have the same name:
$site = "customerapi"
processId = (Get-WmiObject -Class win32_process -filter "name='w3wp.exe'" | Where-Object { ($_.CommandLine).Split("`"")[1] -eq $site } ).ProcessId
Note: This one is also listed under Windows Process Management
== Windows Certificates ==
> View cert info
certutil -v -dump
\\
> Open Current User Certificate store:
certmgr.msc
\\
> Open Local Machine Certificate store:
certlm.msc
\\
> Get specific details from specific certificates from a list of servers and export to csv
$servers = @("server1","server2","server3")
Invoke-Command -ComputerName $servers {Get-ChildItem Cert:\LocalMachine\My | where-object {(($_.DnsNameList -like "*rabobank*") -OR ($_.Subject -like "*rabobank*"))} |select-object @{name="hostname";expression={$(hostname)}},DnsNameList,NotAfter,Thumbprint,Subject,Issuer,FriendlyName} | Export-Csv certs.csv -NoTypeInformation
== Windows Processes ==
> Get all processes
$processes = Get-CimInstance -ClassName Win32_Process | Select-Object ProcessName,ProcessId,CommandLine,Path | sort processid
\\
> Kill a process
try{
$processid = (Get-CimInstance win32_process -Filter "Name = 'mmc.exe'").ProcessId
if ($null -ne $processid){
Stop-Process -id $processid -Force
}
}catch{
Write-Host "Error killing mmc: $_"
}
\\
> Get the process for a IIS Site (always running under w3wp):
# Site and Appool have the same name:
$site = "customerapi"
processId = (Get-WmiObject -Class win32_process -filter "name='w3wp.exe'" | Where-Object { ($_.CommandLine).Split("`"")[1] -eq $site } ).ProcessId
\\
> Get the process and child processes:
$id = (Start-Process cmd.exe -PassThru).id
Get-WmiObject -Class Win32_Process -Filter "ParentProcessId = '$id' or ProcessId ='$id'" | Select-Object ParentProcessId,ProcessId,CommandLine
\\
> Get all process from a specific path
$dir = "appdir"
Write-Host "Alle processen in Path -like $dir"
Get-CimInstance win32_process -Property * | Where-Object {$_.path -like "*$dir*"}
=== Kill processes ===
> Kill process and child processes
$id = (Start-Process cmd.exe -PassThru).id
Get-WmiObject -Class Win32_Process -Filter "ParentProcessId = '$id' or ProcessId ='$id'" | Select-Object ParentProcessId,ProcessId,CommandLine | ForEach-Object {Stop-process $_.processId}
\\
> Using taskkill
$id = (Start-Process cmd.exe -PassThru).id
# Killing the PID
taskkill /pid $id /t /f
# Or using the image name (executable name without path)
taskkill /im cmd.exe /t /f
== Windows System Info ==
> Collect uptime, patches, windows version and more
systeminfo
== System Variables ==
> Set an environment variable until the end of the current command prompt session
set AWS_DEFAULT_REGION eu-west-1
\\
> Set an environment variable in both the current command prompt session and all command prompt sessions that you create after running the command
setx AWS_DEFAULT_REGION eu-west-1
== Windows GPO ==
> Group policy result to html
gpresult /h gpreport.html
\\
> Local Group Policy editor
gpedit.msc
\\
> GPO Management console:
gpmc.msc
\\
> Force GPO update
gpupdate /force
== Windows Firewall ==
> Allow incoming icmp rule to windows firewall
netsh advfirewall firewall add rule name="ICMP Allow incoming V4 echo request" protocol=icmpv4:8,any dir=in action=allow
== Windows Shutdown ==
> Reboot in 1 second
shutdown -r -t 1
\\
> Shutdown in 0 seconds (force option implied)
shutdown -s -t 0
== Windows Updates ==
Use this command to tell Windows Update to start the downloading of updates:
wuauclt /resetauthorization /detectnow
== Windows Management Tool ==
Use the msconfig command to configure Windows in one easy tool
msconfig
== Add User ==
Add the user Maintenance to a system and add it to the local administrators group
net user Maintenance Welkom01 /ADD
net localgroup administrators maintenance /add
== Execute Commands From Remote ==
When working in a Windows environment it could really be nice if you could perform commands on remote computers by default. You could use psexec for this, a lightweight telnet substitute that can be used to launch processes on remote Windows computers. It's originally from [[http://technet.microsoft.com/en-us/sysinternals/default.asp|Sysinternals]] and can be downloaded [[http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx|here]] .
Once you've downloaded psexec, open a command prompt and type
psexec \\computer cmd
where computer is the name or IP address of the remote desktop computer you are targeting. Once you've done this, you're looking at an interactive command prompt on the remote computer, and any command (like gpupdate /force) you now type will be executed on the remote machine instead of the local one. Of course, this can also be done on several computers automatically, when you use a computerlist:
Psexec.exe -@ComputerList.txt Gpupdate.exe /Target:User /force
Psexec.exe -@ComputerList.txt Gpupdate.exe /Target:Computer /force
Of course you can substitute the gpupdate command for any command you might need to use.
== Network ==
|{{{Net use j: \\servername\sharename “password”}}} |Creates a drive mapping J to {{{\\servername\sharename}}} with the logged in username and the given password |
|Net use j: /delete |Deletes the drive mapping J |
|Net use |Gives an overview of the mappings on the box |
|Ping -t -L 1450 -w 5000 www.website.nl |-t continues \\ -L 1450 packetsize \\ -w timeout in milliseconds |
== User Sessions on Terminal Servers ==
=== Enable/Disable logons ===
You can enable / disable logons on terminal servers like this:
change logon /enable
change logon /disable
Query the current setting:
change logon /query
== CMD ==
|cmd.exe /T:0A |Gives a DOS box with a black background and bright green characters |
=== Menu ===
This is the way to get a menu in a dos batch file. The menu in this example is used to install groupwise in a few different ways:
@echo off
color A
goto menu
:menu
echo.
echo What do you want to do?Choose and press ENTER!
echo.
echo 1 Installing English version of Groupwise 7.0.3 HP1
echo 2 Installeer Nederlandse versie van Groupwise 7.0.3 HP1
echo 3 Update Groupwise with current settings to 7.0.3 HP1
echo 4 Remove Groupwise 7
echo 5 Quit!
:choice
set /P C=[1,2,3,4,5]?
if "%C%"=="1" goto GWEN
if "%C%"=="2" goto GWNL
if "%C%"=="4" goto GWUP
if "%C%"=="4" goto GWREMOVE
if "%C%"=="5" goto QUIT
goto choice
:GWEN
start msiexec -i "gw703hp1\win32\groupwise.msi" TRANSFORMS="gw703hp1\win32\GwEngDefNl.mst" /qb+ /promptrestart
goto menu
:GWNL
start msiexec -i "gw703hp1\win32\groupwise.msi" TRANSFORMS="gw703hp1\win32\GwEngNlDef.mst" /qb+ /promptrestart
goto menu
:GWUP
start msiexec -i "gw703hp1\win32\groupwise.msi" /qb+ /promptrestart
:GWREMOVE
start msiexec -x "gw703hp1\win32\groupwise.msi" /qb+ /promptrestart
goto menu
:QUIT
exit
:end