Windows Commands
See also
Files
Clean up as much space as possible
$MAX_DAYS_TO_KEEP = 30 # keep files that were touched during the last N days
$EMPTY_RECYCLE_BIN = $true
$ErrorActionPreference = 'SilentlyContinue' #
Delete files older than N days recursively
# Delete files older than $days recursively and then display files (if any)
# which it failed to delete (because they were open or you don't have the right to delete).
# It also deletes hidden and/or read-only files (due to the -force option)
#
# OPTIONAL ARGUMENTS FOR Get-ChildItem IF YOU WANT TO SELECT A SUBSET OF FILES:
# -Filter "Auto_backups*.txt" # only supports * and ? wildcard#
# -Exclude important*
# -Include *.log # avoid this or read the manual
function deleteoldfiles($top_dir, $days) {
function getfiles() {Get-ChildItem -File -Recurse -Path $top_dir | ?{$_.LastWriteTime -lt (Get-Date).AddDays(-$days)}}
getfiles | rm -force -EA SilentlyContinue
$f = (Get-ChildItem -File -Recurse -EA SilentlyContinue -Path $top_dir | ?{$_.LastWriteTime -lt (Get-Date).AddDays(-$days)} | select -first 1000)
if ($f) {Write-Host -foregroundcolor red "`nThe following files were not deleted:"; $f.FullName | %{Write-Host -foregroundcolor red $_}
if ($f.count -eq 1000) {Write-Host -foregroundcolor red "...(stoped listing at 1000 files)"}
}}; deleteoldfiles $env:TEMP 90
System info and Health checks
General System Info
Get-WmiObject -Class win32_computersystem -ComputerName Localhost | select -Property * -ExcludeProperty Container,Site,Qualifiers,Qualifiers,Properties,SystemProperties,ClassPath,Options,Path,Scope,SystemStartupSetting,SystemStartupOptions,SystemStartupDelay,SupportContactDescription,ResetLimit,PrimaryOwnerContact,PCSystemTypeEx,PCSystemType,PauseAfterReset,OEMLogoBitmap,NetworkServerModeEnabled,NameFormat,LastLoadInfo,InitialLoadInfo,InfraredSupported,EnableDaylightSavingsTime,DomainRole,DaylightInEffect,CurrentTimeZone,CreationClassName,BootStatus,BootROMSupported,BootOptionOnWatchDog,BootOptionOnLimit,WakeUpType,InstallDate,AutomaticResetCapability,AutomaticResetBootOption,AutomaticManagedPagefile,__PATH,__NAMESPACE,__SERVER,__DERIVATION,__PROPERTY_COUNT,__RELPATH,__DYNASTY,__SUPERCLASS,__CLASS,__GENUS,ThermalState,FrontPanelResetStatus,PowerState,PowerSupplyState,PowerOnPasswordStatus,KeyboardPasswordStatus,BootupState,ChassisBootupState,PowerManagementCapabilities,PowerManagementSupported,ResetCapability,ResetCount | Format-List * | Out-String
# ---OR-- for all the info
Get-WmiObject -Class win32_computersystem -ComputerName Localhost | Format-List * | Out-String
PSComputerName : W10ND
BootupState : Normal boot
Name : W10ND
AutomaticManagedPagefile : True
AutomaticResetBootOption : True
AutomaticResetCapability : True
BootROMSupported : True
Caption : W10ND
CreationClassName : Win32_ComputerSystem
CurrentTimeZone : 180
DaylightInEffect : True
Description : AT/AT COMPATIBLE
DNSHostName : w10nd
Domain : WORKGROUP
DomainRole : 0
EnableDaylightSavingsTime : True
HypervisorPresent : True
InfraredSupported : False
Manufacturer : innotek GmbH
Model : VirtualBox
NetworkServerModeEnabled : True
NumberOfLogicalProcessors : 3
NumberOfProcessors : 1
OEMStringArray : {vboxVer_5.2.34, vboxRev_133883}
PartOfDomain : False
PrimaryOwnerName : user
Roles : {LM_Workstation, LM_Server, NT}
SystemFamily : Virtual Machine
SystemType : x64-based PC
TotalPhysicalMemory : 6391648256
UserName :
WakeUpType : 6
Workgroup : WORKGROUP
Scope : System.Management.ManagementScope
Path : \\W10ND\root\cimv2:Win32_ComputerSystem.Name="W10ND"
Options : System.Management.ObjectGetOptions
ClassPath : \\W10ND\root\cimv2:Win32_ComputerSystem
Properties : {AdminPasswordStatus, AutomaticManagedPagefile, AutomaticResetBootOption, AutomaticResetCapability...}
# Free space per Drive
Get-PSDrive -PSProvider FileSystem | ?{$_.Used+$_.Free -gt 0} | %{ [PSCustomObject]@{Used=[int]($_.Used/1GB); Free=[int]($_.Free/1GB); Drive=$_.Name }}
# Used and Free space for one drive
Get-PSDrive C | Select-Object Used,Free
How to start various GUI apps from the CLI
About Windows winver
Add Hardware Wizard hdwwiz.cpl
Add/Remove Programs appwiz.cpl
Administrative Tools control admintools
Advanced Startup Options bootim
Advanced User Accounts netplwiz
Application Data Folder %appdata%
Authorization manager azman.msc
Backup/Restore User Names and Passwords credwiz
Calculator calc
Certificate Manager certmgr.msc
Character Map charmap
Check Disk Utility chkdsk
ClearType Tuner cttune
Colour Management colorcpl
Command Prompt cmd
Compare files comp
Computer Management compmgmt.msc
Control Panel control
Device Manager devmgmt.msc
Disk Cleanup Utility cleanmgr
Disk Management diskmgmt.msc
Disk Partition Manager diskpart
Screen Resolution desk.cpl
Display Switch displayswitch
Ease of Access Center utilman
Event Viewer eventvwr.msc
File History filehistory
Firewall firewall.cpl
Folders Properties control folders
Fonts Folder fonts
Home Drive %homedrive%
Home Directory %homepath%
Internet Explorer iexplore
Internet Options inetcpl.cpl
Keyboard Properties control keyboard
Local Group Policy Editor gpedit.msc
Local Users and Groups lusrmgr.msc
Log Off Windows logoff
Magnifier magnify
Microsoft Management Console mmc
Microsoft Paint mspaint
Mouse Properties control mouse
Network Connections control netconnections
Notepad notepad
On Screen Keyboard osk
Paint mspaint
Performance Monitor perfmon
Performance Options systempropertiesperformance
Power Configuration powercfg.cpl
Program Files folder %programfiles%
Region and Language Settings intl.cpl
Registry Editor egedit
Remote Desktop mstsc
Restart Windows shutdown -r
Scheduled Tasks control schedtasks
Security Center wscui.cpl
Services services.msc
Shared Folders fsmgmt.msc
Shutdown Windows shutdown
Snipping Tool snippingtool
Sounds and Audio mmsys.cpl
System Configuration msconfig
System Information msinfo32
System Properties sysdm.cpl
System Properties - Advanced systempropertiesadvanced
Task Manager taskmgr
Temporary Folder %temp%
Time and Date Settings timedate.cpl
User Account Control Settings useraccountcontrolsettings
Volume Control sndvol
Windows Explorer explorer
Windows PowerShell ISE powershell_ise
Windows PowerShell powershell
Windows Root Directory %windir%
Windows Root Drive %systemdrive%
WMI Management wmimgmt.msc
WMI Tester wbemtest
XPS Viewer xpsrchvw
msconfig = system configuration, you can start A LOT of other tools from this one |
lusrmgr.msc = Local Users and Groups |
cmd.exe = command prompt |
explorer.exe = file explorer and the desktop |
wf.msc = firewall |
sysdm.cpl = system properties |
taskmgr = task manager |
services.msc = services
About the event-log
View logins/logouts during the last 30 days
Get-EventLog System -Source Microsoft-Windows-WinLogon -After (Get-Date).AddDays(-30) | Out-GridView
# | Out-GridView is optional, it displays the results in a nice GUI-----^
View errors during the last 10 days
$Days=10
$After = (Get-Date) - (New-TimeSpan -Day $Days)
echo "System"
Get-Eventlog -LogName 'System' -After $After | ? {($_.EntryType -Match "Error")} | Select -Property Message,Source,TimeGenerated | fl
echo
echo "Security"
Get-Eventlog -LogName 'Security' -After $After | ? {($_.EntryType -Match "Error")} | Select -Property Message,Source,TimeGenerated | fl
echo
echo "Application"
Get-Eventlog -LogName 'Application' -After $After | ? {($_.EntryType -Match "Error")} | Select -Property Message,Source,TimeGenerated | fl
Advanced filtering and processing of event logs
Windows support an advanced XML based language to write complex filters. In event viewer's GUI you can use it like this: In the "Filter Current Log" dialog box, click on the "XML" tab. In the "XML" tab, check the box next to "Edit query manually".
<QueryList>
<Query Id="0" Path="Application">
<Select Path="Security">*[
System[
(EventID=4624)
and TimeCreated[@SystemTime>='2022-05-01T09:00:00.000Z']
]
and EventData[Data[@Name='TargetUserName']!='SYSTEM']
and EventData[Data[@Name='LogonType']!='4']
and EventData[Data[@Name='IpAddress']!='-']
]</Select>
</Query>
</QueryList>
You can also use PowerShell to extract specific information from the message. Here's an example that displays user name and IP address for all remote desktop connections:
# If you want the Creation Time to be with the last 5min (300000msec) use this:
# TimeCreated[timediff(@SystemTime) <= 300000]
$xmlQuery = @'
<QueryList>
<Query Id="0" Path="Application">
<Select Path="Security">*[
System[
(EventID=4624)
and TimeCreated[@SystemTime>='2022-05-01T09:00:00.000Z']
]
and EventData[Data[@Name='TargetUserName']!='SYSTEM']
and EventData[Data[@Name='LogonType']!='4']
and EventData[Data[@Name='IpAddress']!='-']
]</Select>
</Query>
</QueryList>
'@
Get-WinEvent -FilterXML $xmlQuery
Get-WinEvent -FilterXML $xmlQuery | %{
$event = $_
$stream = $event.message.Split("`r`n")
# Keep messages lines that match specific patterns
# and do not match other patterns
$interesting_lines = ( $stream |
sls 'Source Network Address:|Account Name:|Account Domain:' |
sls -NotMatch 'Network Account'
).line
echo "Time=$($event.TimeCreated) EventId=$($event.id)"
echo $interesting_lines
}
Get-WinEvent -FilterXML $xmlQuery | %{
$event = $_
# Keep the messages lines after("Post") the "Logon Information:" heading
$stream = ( $event.Message.Split("`r`n") |
sls -Context 999 "Logon Information:"
).context.PostContext
# Keep messages lines that match specific patterns
# and do not match other patterns
$interesting_lines = (
$stream |
sls 'Source Network Address:|Account Name:|Account Domain:' |
sls -NotMatch 'Network Account'
).line
echo "Time=$($event.TimeCreated) EventId=$($event.id)"
echo $interesting_lines
}
Shutdown (/s) /Reboot (/r)
shutdown.exe /r /f # reboot now forcing programs to quit
shutdown.exe /s /t 300 # shutdown in 300" (/f is implied)
More info:
https://www.howtogeek.com/512012/how-to-shut-down-your-windows-10-pc-using-command-prompt/
Access the registry (PowerShell)
The branches of the registry are addressed like drives (
HKLM:\ and
HKCU:\). Use Set-Location command (alias — sl) to move and dir to see entries:
cd HKLM: Set-Location -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching
dir
# or:
Get-Item -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching
Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching' -Name SearchOrderConfig
# change values Set-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching' -Name SearchOrderConfig -Value 0 # Make sure that the value has changed:
More info here
About services
About all services in general
Restart-Service - Restart a stopped service
Start-Service - Start a stopped service
Stop-Service - Stop a running service
Get-Service - Get a list of services
# list services that are set to auto start but have NOT started yet (IGNORES A FEW services that I always see as stoped)
get-service | ?{$_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' -and $_.Name -notin 'gupdate','RemoteRegistry','sppsvc'}| ft -Property Status,DisplayName
# another way (ignores nothing):
Get-WmiObject Win32_Service | ?{ $_.StartMode -eq 'Auto' -and $_.State -ne 'Running' } | ft -Property Name,DelayedAutoStart,DisplayName,Description
# list services that are not "core" windows services
Get-WmiObject Win32_Service | ?{ $_.acceptstop -eq $true -and $_.PathName -notlike 'C:\windows\system32*'} | sort -Property PathName | ft -Property Name,PathName,DisplayName,Description
# Get services with names that contain "WMI" and sort the result by the service status (running/stopped):
get-service *wmi* | sort-object status
# Display only services that are currently running:
get-service | where-object {$_.Status -eq 'Running'}
# lists the dependant services of iis:
get-service iisadmin | format-list -property name, dependentservices
# Use -force to stop a service that has dependent services, the first command below
stop-service iisadmin -force
About specific services
Advanced restart printer spooler and flush files:
net stop spooler
del /F /Q %systemroot%\System32\spool\PRINTERS\*
net start spooler
Other
hosts file
notepad c:\windows\system32\drivers\etc\hosts
Change file's timestamp
# example of changing times based on another file
(Get-ChildItem $dstfile).LastWriteTime = (Get-ChildItem $srcfile).LastWriteTime
Get-ChildItem $dstfile).CreationTime = (Get-ChildItem $srcfile).CreationTime
# you can SET any of these:
(Get-ChildItem C:\file1.txt).LastWriteTime
(dir C:\file1.txt).CreationTime
# You can READ values like these:
(Get-ChildItem C:\file2.txt).CreationTime # another file's CreationTime/LastWriteTime
(Get-Date) # the current time
(Get-Date -Date "2017-10-24 11:50:00") # a specific time
System information, User name, PC name, Domain name
whoami
net config workstation
systeminfo # also boot time and Installation date
How to list/enable/disable windows features
Get-WindowsOptionalFeature -Online
Enable-WindowsOptionalFeature –FeatureName "name" -All -Online
Disable-WindowsOptionalFeature –FeatureName "name" -Online
IF YOU WANT TO SCAN FOR LOGICAL ERRORS (faster)
chkdsk C: /f /x /v
/f option will attempt to fix any found errors
/x option will force the volume you’re about to check to be dismounted before the utility begins a scan
/v verbose output
IF YOU WANT TO SCAN FOR BAD SECTORS ALSO (sloooooooow)
Add /r and wait for it to read all the sectors one by one
About winget
Install a program
(Find the id by a google search for:
winget install Adobe acrobat or by running:
winget search acrobat)
winget install --exact --id Adobe.Acrobat.Reader.64-bit --silent --accept-package-agreements
Upgrade all programs you installed with winget
winget upgrade --all --silent --accept-package-agreements
About WSL (Windows Subsystem for Linux)
How to access a UNC path (shared folder)
# you need to mount the UNC somewhere
sudo mkdir /mnt/x/
sudo mount -t drvfs '\\10.1.11.50\company' /mnt/x