PowerShell and CMD commands cheat sheet

This cheat sheet brings together the most useful commands for managing a Windows server, including a VPS, from files, processes, and services to networking, the firewall, users, and remote access, with a short explanation of each command. You can search for a command, filter by section, and copy it with one click.

Basics and help

  • Get-Help Get-Service -Examples

    Show usage examples for the Get-Service command. You can replace the command name with any other PowerShell command. The -Full option shows the full documentation, and when the local documentation is missing, the Update-Help command downloads it.

  • Get-Command *firewall*

    Search for commands by part of their name. This helps you find a command when you do not know its exact name.

  • Get-Command -Module NetSecurity

    List all the commands that a specific module provides. The NetSecurity module, for example, includes the commands for managing Windows Firewall.

  • Get-Module -ListAvailable -Name WebAdministration

    Check whether a specific module is installed on the server. When the command returns no output, the module is not installed and its commands are not available.

  • Get-Service | Get-Member

    Show the properties and methods of the objects that a command returns. The list helps you choose fields to filter and display with the Where-Object and Select-Object commands.

  • Get-Service | Select-Object Name, Status | Format-Table -AutoSize

    Show only the selected fields, in a table with column widths fitted to the content. In PowerShell, the output of every command is objects, so you can filter and format it without text processing.

  • Get-Service | Export-Csv -Path C:\reports\services.csv -NoTypeInformation -Encoding UTF8

    Save the output of a command to a CSV file that you can open in a spreadsheet. The -NoTypeInformation option prevents a technical details line at the top of the file, and the UTF8 encoding preserves non-English characters.

  • $PSVersionTable

    Show the version and edition details of the PowerShell that is currently running. The details help you tell whether the open window belongs to the built-in Windows PowerShell or to the newer PowerShell, which is installed separately.

  • Get-Alias ls

    Show which command a short alias points to. In PowerShell, the ls and dir aliases point to the Get-ChildItem command, and the cd alias points to the Set-Location command.

  • ipconfig /?

    Show the help for a CMD command or a command-line tool. You can replace ipconfig with any other tool. The help command in a CMD window lists the built-in commands.

  • cls

    Clear the screen. The command works in both CMD and PowerShell, and in a PowerShell window the cls alias points to the Clear-Host command.

  • Get-History

    Show the commands run in the current PowerShell window, with a sequence number for each command. The history alias does the same thing. Commands from previous windows are saved in a separate file, and the (Get-PSReadLineOption).HistorySavePath command shows its path.

Files and folders

  • Get-ChildItem C:\inetpub -Recurse -Filter *.log

    List all the log files in the folder and in all its subfolders. The -File option limits the results to files only.

  • Get-ChildItem C:\data -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10 FullName, Length

    Show the ten largest files in the folder and its subfolders, with the full path and the size in bytes. The command helps you find what is taking up disk space.

  • (Get-ChildItem C:\data -Recurse -File | Measure-Object -Property Length -Sum).Sum / 1GB

    Calculate the total size of a folder, including its subfolders, in gigabytes. On a large folder, the calculation may take a while.

  • dir /s /b *.log

    Show the full path of every log file in the current folder and its subfolders. The command works only in CMD, because in PowerShell the dir alias points to the Get-ChildItem command, which does not accept these options.

  • Set-Location C:\Windows\System32

    Change to another folder. The cd alias does the same thing. In CMD, changing to a folder on another drive requires the /d option, for example cd /d D:\backup.

  • Test-Path C:\scripts\backup.ps1

    Check whether a file or folder exists, and return True or False. The check is useful in scripts, before an action on a path.

  • New-Item -ItemType Directory -Path C:\backup

    Create a new folder, including any intermediate folders in the path that do not exist yet.

  • Copy-Item C:\source -Destination D:\backup -Recurse

    Copy a folder with all its contents. Without the -Recurse option, only the folder itself is copied, without the files inside it.

  • Move-Item C:\temp\report.txt -Destination D:\archive\

    Move a file or folder to another location. When a file with the same name already exists at the destination, an error is shown, and the -Force option overwrites it.

  • Remove-Item C:\temp\old -Recurse

    Delete a folder with all its contents. Caution: the files do not go to the Recycle Bin and you cannot undo the deletion, so check the path first with the -WhatIf option.

  • Get-ChildItem C:\inetpub\logs\LogFiles -Recurse -File | Where-Object LastWriteTime -lt (Get-Date).AddDays(-30) | Remove-Item -WhatIf

    Show which log files older than 30 days would be deleted, without actually deleting them. Caution: removing the -WhatIf option permanently deletes the files, so check the list and the path first.

  • Get-Content C:\logs\app.log -Tail 50 -Wait

    Show the last 50 lines of the file and keep showing new lines as they are written. The Ctrl+C key combination stops following the file.

  • Select-String -Path C:\logs\*.log -Pattern "error"

    Search for text in files and show the file name, the line number, and the line itself. The search is not case-sensitive, and the -CaseSensitive option changes that.

  • Get-FileHash C:\downloads\setup.exe -Algorithm SHA256

    Calculate the hash of a file. Comparing it with the value that the download source publishes confirms that the file was not changed or corrupted on the way.

  • Compress-Archive -Path C:\site -DestinationPath D:\backup\site.zip

    Compress a folder into a ZIP file. When the destination file already exists, an error is shown, and the -Force option overwrites it.

  • Expand-Archive -Path D:\backup\site.zip -DestinationPath C:\restore

    Extract a ZIP file to the specified folder. When files with the same name already exist at the destination, the -Force option overwrites them.

  • robocopy C:\source D:\backup /E /R:2 /W:5 /LOG:C:\logs\robocopy.log

    Copy a folder with all its subfolders, including empty ones, and save a report to a log file. The /R and /W options limit the number of retries and the wait time between them, because the default values are very high. In a script, an exit code of 8 or higher indicates a failure, and lower codes indicate success.

  • robocopy C:\source D:\backup /MIR /L

    Show which files a sync would copy and delete, without actually running it. The /L option is useful for a check before you run /MIR.

  • robocopy C:\source D:\backup /MIR

    Make the destination folder an exact copy of the source folder. Caution: files at the destination that do not exist in the source are deleted, and swapping the source and the destination by mistake deletes the original data.

  • xcopy C:\source D:\backup /E /I /H

    Copy a folder with its subfolders, including empty ones, hidden files, and system files. The /I option tells xcopy that the destination is a folder, without asking.

  • attrib -h -s C:\data\file.txt

    Remove the hidden and system attributes from the file. The + sign instead of the - sign adds the attributes, and the letter r stands for read-only.

  • icacls C:\site

    Show the permissions of a file or folder. The letter F stands for full control, the letter M stands for modify, and RX stands for read and execute.

  • Get-Acl C:\site | Format-List

    Show the owner of a file or folder and the full list of permissions, as an object that you can filter in a script.

  • icacls C:\site /grant "user:(OI)(CI)M" /T

    Grant the user named user modify permission on the folder, on all its files, and on all its subfolders, including items created in the future. Caution: overly broad permissions on a site folder let vulnerable code change files, so grant only the permission that is needed.

System information

  • systeminfo

    Show a summary of the system details, including the Windows edition, the last boot time, the memory, the network adapters, and the installed updates. The command works in both CMD and PowerShell.

  • Get-ComputerInfo

    Show detailed information about the operating system, the hardware, and the settings, as an object that you can filter. Collecting the information may take a while.

  • hostname

    Show the computer name. The command works in both CMD and PowerShell, and the $env:COMPUTERNAME variable returns the same value inside a script.

  • Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, LastBootUpTime

    Show the operating system name, the version number, and the last boot time of the server.

  • (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime

    Calculate how long the server has been running since the last boot, in days, hours, and minutes. The gcim alias is short for the Get-CimInstance command.

  • Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessors

    Show the processor model, the number of cores, and the number of logical processors available to the server.

  • (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB

    Show the total physical memory of the server, in gigabytes.

  • Get-Disk

    Show the physical and virtual disks on the server, with the size, the partition style, and the status of each disk. A new disk added to the server often shows as Offline until you bring it online and initialize it.

  • Get-Volume

    Show the volumes on the server, with the file system, the total size, and the free space of each volume.

  • Get-PSDrive -PSProvider FileSystem

    Show the used space and the free space on each drive, in gigabytes.

  • Get-WindowsFeature | Where-Object Installed

    Show the roles and features installed on the server, such as IIS, DNS, and Hyper-V. The command is available only on Windows Server editions.

  • Get-TimeZone

    Show the time zone of the server. The Set-TimeZone -Id "UTC" command changes it, and the Get-TimeZone -ListAvailable command lists all the possible IDs.

Processes

  • Get-Process

    List the processes running on the server, with the process ID, the memory usage, and the CPU time that each process has used.

  • Get-Process | Sort-Object CPU -Descending | Select-Object -First 10

    Show the ten processes that have used the most CPU time. The CPU column shows the total seconds since the process started, not the current usage percentage.

  • Get-Counter '\Processor(_Total)\% Processor Time' -SampleInterval 2 -MaxSamples 5

    Show the current CPU usage percentage, in five samples taken two seconds apart. On a server installed in another language, the counter names are localized, and the Get-Counter -ListSet * command lists the available names.

  • Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10 Name, Id, WorkingSet64

    Show the ten processes that use the most memory, with the usage in bytes.

  • Stop-Process -Name notepad

    Close all the processes with the specified name. Write the name without the .exe extension. Caution: the process closes immediately, and unsaved data in it is lost.

  • Start-Process notepad

    Start a program, or open a file in the program associated with it.

  • Start-Process powershell -Verb RunAs

    Open a new PowerShell window with administrator privileges. The action shows the User Account Control confirmation prompt.

  • tasklist

    List the processes with the ID and the memory usage of each process. The tool works in both CMD and PowerShell.

  • tasklist /svc

    Show which services run inside each process. The output helps you identify the service behind an svchost.exe process that uses a lot of resources.

  • taskkill /PID 1234 /F

    Force a process to close by its ID. The /IM option closes a process by its file name, for example /IM notepad.exe. Caution: the /F option closes the process immediately, without a chance to save data.

Services

  • Get-Service

    List all the services on the server, with the current status, the service name, and the display name of each service.

  • Get-Service | Where-Object Status -eq 'Running'

    Show only the services that are currently running. The Stopped value shows the services that are stopped.

  • Get-CimInstance Win32_Service | Select-Object Name, State, StartMode, StartName

    Show the status, the startup type, and the account of each service. The check helps you find services that run under an account with broader privileges than needed.

  • Start-Service -Name ServiceName

    Start a stopped service. The action requires administrator privileges.

  • Stop-Service -Name ServiceName

    Stop a service. Caution: when other services depend on the service, the command fails, and the -Force option also stops the dependent services.

  • Restart-Service -Name ServiceName

    Restart a service, for example after a change in its configuration file.

  • Set-Service -Name ServiceName -StartupType Automatic

    Set the service to start automatically when the server boots. The Manual value sets a manual start, and the Disabled value disables the service.

  • Get-Service -Name ServiceName -DependentServices

    List the services that depend on the specified service. Check the list before you stop a service.

  • sc.exe query ServiceName

    Show the status of a service. In CMD, you can write sc without the extension, but in Windows PowerShell the sc alias points to the Set-Content command, so write sc.exe.

  • sc.exe config ServiceName start= auto

    Change the startup type of a service to automatic. The space after the equals sign is required, and the demand and disabled values set a manual start or disable the service.

  • net stop ServiceName

    Stop a service. The net start ServiceName command starts it, and the net start command without a service name lists all the running services.

Networking

  • ipconfig /all

    Show the full network settings of every network adapter, including the IP addresses, the default gateway, the DNS servers, and the MAC address. The tool works in both CMD and PowerShell.

  • ipconfig /flushdns

    Clear the server's local DNS cache. The Clear-DnsClientCache command does the same thing in PowerShell. Clearing the cache is useful after a change in DNS records, when the server still connects to the old address.

  • Get-NetAdapter

    List the network adapters on the server, with the status, the link speed, and the MAC address of each adapter. The name in the Name column is used in other network commands.

  • Get-NetIPAddress -AddressFamily IPv4

    Show the IPv4 addresses configured on the server, with the network adapter name and the prefix length of each address.

  • Get-NetRoute -AddressFamily IPv4

    Show the routing table of the server. The 0.0.0.0/0 destination stands for the default gateway, and the route print command shows the same table in a CMD window.

  • Test-NetConnection example.com -Port 443

    Check whether you can connect to a specific port on a destination server. The True value in the TcpTestSucceeded field means that the port is open and reachable.

  • Resolve-DnsName example.com

    Show the records that a DNS query for the domain returns, including IP addresses and CNAME records.

  • Resolve-DnsName example.com -Type MX -Server 1.1.1.1

    Show records of a specific type from a specific DNS server, without using the local cache. The TXT type, for example, shows the SPF records of the domain.

  • nslookup example.com

    Show the IP address of the domain and the DNS server that answered the query. The tool works in both CMD and PowerShell.

  • ping -n 4 example.com

    Send four requests to the destination server and show the response time. The -t option sends requests nonstop until you press Ctrl+C. Many servers block ping requests, so no response does not necessarily mean that the server is down.

  • tracert example.com

    Show the router at each hop on the way to the destination server and its response time. The output helps you find the point where traffic slows down or stops.

  • Get-NetTCPConnection -State Listen

    Show the ports that the server listens on, with the local address and the process ID in the OwningProcess column.

  • Get-Process -Id (Get-NetTCPConnection -LocalPort 8080 -State Listen).OwningProcess

    Show which process listens on a specific port. Ports managed by HTTP.sys, such as IIS ports, show as belonging to the System process.

  • netstat -ano

    Show all the connections and open ports, with the process ID in the last column. The tool works in both CMD and PowerShell.

  • netstat -ano | findstr :3389

    Filter the output to connections on a specific port, here the default RDP port. The findstr tool works in both CMD and PowerShell.

  • curl.exe -I https://example.com

    Show the response headers of a URL, including the status code and the redirect target, when there is a redirect. In Windows PowerShell, the curl alias points to the Invoke-WebRequest command, so write curl.exe. The newer versions of PowerShell removed the alias, and curl.exe works in every environment.

  • Invoke-WebRequest -Uri https://example.com/file.zip -OutFile C:\temp\file.zip -UseBasicParsing

    Download a file from a URL and save it to the specified path. In Windows PowerShell, the -UseBasicParsing option prevents an error on servers where the built-in browser component is not available, and in the newer versions of PowerShell it has no effect.

  • New-PSDrive -Name Z -PSProvider FileSystem -Root \\fileserver\backup -Persist -Credential username

    Map a shared network folder to drive Z and prompt for the password of the user. The -Persist option creates a permanent network drive that also shows in File Explorer, and the net use command does something similar in a CMD window.

Firewall

  • Get-NetFirewallProfile | Select-Object Name, Enabled

    Show whether the firewall is enabled in each of the three profiles: Domain, Private, and Public.

  • netsh advfirewall show allprofiles

    Show the status and settings of the firewall in all the profiles, including the default policy for inbound and outbound traffic. The tool works in both CMD and PowerShell.

  • Get-NetFirewallRule -Enabled True -Direction Inbound | Select-Object DisplayName, Action

    List all the inbound rules that are currently enabled, with the action of each rule. On most servers, the list is long, so filter it by name, for example with the -DisplayName "*SQL*" option.

  • Get-NetFirewallPortFilter | Where-Object LocalPort -eq 8080 | Get-NetFirewallRule

    Show the rules defined explicitly for a specific port. The check helps you find out why a port is blocked or open. Rules that apply to all ports do not appear in the list.

  • New-NetFirewallRule -DisplayName "Allow TCP 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow

    Create a rule that allows inbound traffic to a specific TCP port from any address. A descriptive rule name makes the rule easier to find and remove later.

  • New-NetFirewallRule -DisplayName "Allow TCP 8080 from office" -Direction Inbound -Protocol TCP -LocalPort 8080 -RemoteAddress 203.0.113.10 -Action Allow

    Create a rule that allows access to the port only from a specific IP address. Restricting access by source address is especially suitable for management ports.

  • New-NetFirewallRule -DisplayName "Block 198.51.100.25" -Direction Inbound -RemoteAddress 198.51.100.25 -Action Block

    Block all inbound traffic from a specific IP address, for example an address that is trying to guess passwords. A block rule takes precedence over rules that allow the same traffic.

  • Set-NetFirewallRule -DisplayGroup "Remote Desktop" -RemoteAddress 203.0.113.10

    Restrict the built-in RDP rules so that connections are allowed only from a specific IP address. Caution: when the address of the connecting computer changes, access to the server is blocked, so make sure you have another way to access the server.

  • netsh advfirewall firewall add rule name="Allow TCP 8080" dir=in action=allow protocol=TCP localport=8080

    Create a rule that allows inbound traffic to a specific port, in netsh syntax. This form is useful in a CMD window and in existing scripts.

  • Disable-NetFirewallRule -DisplayName "Allow TCP 8080"

    Disable a rule without deleting it. The Enable-NetFirewallRule command enables it again. Disabling suits a temporary test, because you can easily undo it.

  • Remove-NetFirewallRule -DisplayName "Allow TCP 8080"

    Delete a rule by its display name. Caution: deleting the rule that allows RDP blocks remote access to the server, so check the rule name before you run the command.

  • Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True

    Enable the firewall in all the profiles. Caution: before you enable it, make sure that an enabled rule allows RDP, otherwise the remote connection may drop with no way back in.

Users and groups

  • Get-LocalUser

    List the local users on the server and the status of each user, enabled or disabled.

  • Get-LocalGroup

    List the local groups on the server. On a server installed in another language, the names of the built-in groups are localized, and the list shows the exact name to use in other commands.

  • Get-LocalGroupMember -Group "Administrators"

    List the members of the Administrators group, including domain users and groups. Check the list from time to time and remove accounts that are not needed.

  • New-LocalUser -Name "username" -Password (Read-Host -AsSecureString "Password")

    Create a new local user and prompt for the password as hidden input, so the password is not shown on the screen and is not saved in the command history. The password must meet the password policy of the server.

  • Set-LocalUser -Name "username" -Password (Read-Host -AsSecureString "New password")

    Change the password of a local user. The new password is typed as hidden input.

  • Disable-LocalUser -Name "username"

    Disable a local user without deleting it, so no one can log in with the account. The Enable-LocalUser command enables it again.

  • Add-LocalGroupMember -Group "Administrators" -Member "username"

    Add a user to the Administrators group. On a server installed in another language, the group name is localized, and the Get-LocalGroup command shows it. Caution: a member of the group gets full control of the server, so add only users who need it.

  • Remove-LocalGroupMember -Group "Administrators" -Member "username"

    Remove a user from the Administrators group. Caution: make sure that at least one enabled administrator account that you can log in with remains.

  • Add-LocalGroupMember -Group "Remote Desktop Users" -Member "username"

    Allow a user to connect to the server over RDP without administrator privileges. The name of this group is also localized on a server installed in another language.

  • net user

    List the local users. The net user username command shows details about a specific user, including the last logon time and the password expiration.

  • net user username *

    Change the password of a user and prompt you to type it twice, without showing it on the screen. The command works in both CMD and PowerShell.

  • net accounts

    Show the password and lockout policy of the server, including the minimum password length and the number of failed attempts before the account is locked.

  • net localgroup Administrators

    List the members of the Administrators group, in CMD syntax.

  • whoami /groups

    Show the groups that the current user belongs to. The High Mandatory Level line means that the window runs with administrator privileges.

RDP and remote access

  • Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnections

    Check whether RDP connections are allowed on the server. The value 0 means that connections are allowed, and the value 1 means that they are blocked.

  • Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnections -Value 0

    Allow RDP connections to the server. Caution: also enable a matching firewall rule, and make sure that all the users with access have strong passwords.

  • Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

    Enable the built-in Remote Desktop firewall rules. On a server installed in another language, the group name is localized, and you can find it with the Get-NetFirewallRule command.

  • Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name UserAuthentication

    Check whether Network Level Authentication is required before an RDP connection opens. The value 1 means that it is required, which is the recommended setting.

  • query user

    List the users connected to the server, with the session ID, the session state, and the idle time.

  • logoff 2

    Log off the session with the specified ID and close all the programs open in it. Caution: unsaved data in the session is lost, so check the session ID first with the query user command.

  • mstsc /v:server.example.com

    Open an RDP connection to a remote server from a Windows computer. The /admin option connects to the administrative session of the server.

  • Test-WSMan server.example.com

    Check whether the WinRM service on the remote server is available for PowerShell remoting.

  • Enable-PSRemoting -Force

    Enable WinRM and configure the server to accept PowerShell remoting connections. Caution: use the firewall to restrict access to the WinRM ports, 5985 and 5986, to known addresses only.

  • Set-Item WSMan:\localhost\Client\TrustedHosts -Value "server.example.com" -Concatenate

    Add a server to the trusted hosts list on the connecting computer. This setting is required for PowerShell remoting to a server that is not a domain member. Caution: in this mode, the identity of the server is not verified, so add only known servers and prefer an encrypted HTTPS connection.

  • Enter-PSSession -ComputerName server.example.com -Credential username

    Open an interactive PowerShell session on a remote server. The Exit-PSSession command closes the session.

  • Invoke-Command -ComputerName server.example.com -Credential username -ScriptBlock { Get-Service }

    Run a command on a remote server and return the result, without opening an interactive session. You can specify several servers, separated by commas.

Updates and events

  • Get-HotFix | Sort-Object InstalledOn -Descending

    List the installed updates, from newest to oldest. The list does not necessarily include every type of update, so it suits a general check only.

  • sconfig

    Open a text menu for basic Windows Server settings, including installing updates, network settings, and enabling RDP. The tool is available on Windows Server editions.

  • Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'

    Check whether an installed update is waiting for a server restart. The True value means that a restart is required.

  • Get-WinEvent -LogName System -MaxEvents 50

    Show the last 50 events in the System log. The Application and Security names show the application log and the security log.

  • Get-WinEvent -FilterHashtable @{LogName='System'; Level=2} -MaxEvents 20

    Show only the latest errors in the System log. The value 1 stands for critical events, and the value 3 stands for warnings.

  • Get-WinEvent -FilterHashtable @{LogName='Application'; Level=2; StartTime=(Get-Date).AddHours(-24)}

    Show the errors in the Application log from the last 24 hours. Filtering by time helps you find the source of a problem when you know when it started.

  • Get-WinEvent -FilterHashtable @{LogName='System'; Id=1074,6006,6008} -MaxEvents 20

    Show shutdown and restart events. Event 1074 marks a shutdown or restart started by a user or a process, event 6006 marks a clean shutdown, and event 6008 marks an unexpected shutdown.

  • Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625} -MaxEvents 20

    Show failed logon attempts, including the user name and the source address. A large number of such attempts usually indicates password guessing, for example over RDP. Reading the Security log requires administrator privileges.

  • Get-WinEvent -LogName 'Microsoft-Windows-TerminalServices-LocalSessionManager/Operational' -MaxEvents 20

    Show the latest RDP connections to the server, including the user name and the source address. Event 21 marks a logon, event 24 marks a disconnection, and event 25 marks a reconnection.

  • Get-EventLog -LogName System -Newest 20 -EntryType Error

    Show the last 20 errors in the System log. The command is available only in the built-in Windows PowerShell. In the newer PowerShell, use the Get-WinEvent command instead.

  • DISM /Online /Cleanup-Image /RestoreHealth

    Check and repair the Windows component store, which supplies the files used for repairs. Run the command before sfc /scannow, and note that the repair may take a long time. When Windows Update is not reachable, specify another source with the /Source option.

  • sfc /scannow

    Scan the system files and replace corrupted or missing files. The action requires administrator privileges and may take a long time.

  • shutdown /r /t 300 /c "Scheduled maintenance"

    Schedule a server restart in 300 seconds and show a message to the connected users. The shutdown /a command cancels the restart before the time runs out.

  • shutdown /r /t 0

    Restart the server immediately. The Restart-Computer command does the same thing in PowerShell. Caution: all the connections and services disconnect, so save any open work and make sure that the server is not in the middle of installing an update.

IIS

  • Get-WindowsFeature -Name Web-* | Where-Object Installed

    Show the IIS components installed on the server. The command is available only on Windows Server editions.

  • Install-WindowsFeature -Name Web-Server -IncludeManagementTools

    Install the IIS web server together with its management tools. The command is available only on Windows Server editions and requires administrator privileges.

  • Get-Website

    List the sites configured in IIS, with the status, the physical path, and the bindings of each site. The command requires the IIS WebAdministration module, which is installed with the IIS management tools.

  • Stop-Website -Name "SiteName"

    Stop one site in IIS without affecting other sites on the server. The Start-Website command starts it again. These commands also require the WebAdministration module.

  • Restart-WebAppPool -Name "AppPoolName"

    Recycle a single application pool without affecting other sites on the server. Use it after a change in the settings of a site, or when a site stops responding.

  • iisreset /status

    Show the status of the IIS services, without making any change.

  • iisreset

    Restart all the IIS services. Caution: all the sites on the server are unavailable for a short time, so to fix one site, recycle only its application pool.

Scheduled tasks

  • Get-ScheduledTask -TaskPath "\"

    List the scheduled tasks in the root folder of Task Scheduler, where manually created tasks are usually saved.

  • Get-ScheduledTaskInfo -TaskName "TaskName"

    Show the last run time, the next run time, and the result code of a task. The result code 0 means that the run succeeded.

  • Start-ScheduledTask -TaskName "TaskName"

    Run a scheduled task immediately, without waiting for its scheduled time. Running it helps you check that the task works as expected.

  • schtasks /query /fo LIST /v

    List all the scheduled tasks with full details, including the command that each task runs and the account it runs under. The tool works in both CMD and PowerShell.

  • schtasks /create /tn "DailyBackup" /tr "powershell.exe -NoProfile -ExecutionPolicy RemoteSigned -File C:\scripts\backup.ps1" /sc daily /st 02:00 /ru backupuser /rp *

    Create a task that runs a PowerShell script every day at 02:00 under the backupuser account, and prompt for the password of that user. Running under a dedicated account with only the privileges it needs is safer than running under the SYSTEM account, which has full privileges. Caution: after the password of the user changes, the task fails until you update the password in the task too.

  • Unregister-ScheduledTask -TaskName "TaskName"

    Delete a scheduled task after a confirmation prompt. Caution: you cannot recover the task, so to pause it, use the Disable-ScheduledTask command.

Scripts

  • Get-ExecutionPolicy -List

    Show the script execution policy at each scope, in order of precedence. The effective policy is set by the first scope in the list that has a value, and the Get-ExecutionPolicy command without options shows it.

  • Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

    Allow the current user to run local scripts, and require a digital signature for scripts downloaded from the internet. Caution: run only scripts from a known source, and do not weaken the policy for the whole computer unless you need to.

  • .\script.ps1

    Run a script from the current folder. For security reasons, PowerShell does not run files from the current folder without the .\ prefix, even when you type the full file name.

  • powershell -ExecutionPolicy Bypass -File C:\scripts\script.ps1

    Run one script while bypassing the execution policy, without changing the permanent setting. Caution: the option skips the check, so use it only for a script whose contents you have reviewed.

  • Unblock-File -Path C:\scripts\script.ps1

    Remove the mark that the file was downloaded from the internet, so the RemoteSigned policy allows it to run. Do this only after you check the contents.

  • notepad $PROFILE

    Open the profile file for editing. The profile loads every time PowerShell opens and suits permanent aliases and functions. When the file does not exist, the New-Item -Path $PROFILE -ItemType File -Force command creates it.

  • Start-Transcript -Path C:\logs\session.txt

    Start saving all the commands and output of the current window to a file. The Stop-Transcript command stops saving. The file documents the maintenance work done and lets you review it later.

Windows servers have two command-line environments, CMD and PowerShell, and this page includes commands for both. External tools such as ipconfig, ping, robocopy, and netstat work in both environments. Commands such as Get-Service and Get-NetFirewallRule work only in PowerShell, and some options of built-in CMD commands, such as dir /s, work only in a CMD window. Where there is a difference, the explanation of the command notes where it works.

Many commands on this page change system settings, so they require a window opened with administrator privileges: right-click the PowerShell icon and select Run as administrator. To create a strong, unique password for a new user or a password change, especially for accounts with RDP access, use the password generator.

Three habits prevent many problems. Before you delete or move files, run the command with the -WhatIf option, and run robocopy with the /L option. Before you change the firewall or the RDP settings, make sure you have another way to access the server, such as a remote console in the control panel of your server provider. In addition, back up important data before an update or a major change.

Did you know?

A Windows VPS comes with full RDP administrator access.

Windows VPS plans

PowerShell and CMD commands FAQ

What is the difference between PowerShell and CMD?

The main difference is the type of output. CMD passes only text between commands and suits short commands and legacy batch files, while PowerShell passes objects with fields between commands, so you can filter and sort results without text processing. Most modern Windows server management tools are available as PowerShell commands, so PowerShell is the better choice for everyday work.

What is the difference between Windows PowerShell and PowerShell?

Windows PowerShell is built into the system and starts with the powershell command, while the newer PowerShell is installed separately, also runs on other operating systems, and starts with the pwsh command. Most of the commands on this page work in both environments, and the explanation of each command notes the differences. The $PSVersionTable command shows which environment the current window runs.

Why do I get an Access is denied error?

In most cases, the window was opened without administrator privileges, even when the user is a member of the Administrators group, because User Account Control opens windows with standard privileges by default. The whoami /groups command shows whether the current window runs with administrator privileges, and the Start-Process powershell -Verb RunAs command opens a new window with those privileges.

Why does a script fail to run with a message that running scripts is disabled?

The script execution policy blocks the script, or the file is marked as downloaded from the internet. The Get-ExecutionPolicy -List command shows the policy at each scope, and the Set-ExecutionPolicy RemoteSigned -Scope CurrentUser command allows local scripts to run. For a downloaded file that you have reviewed, you can remove the mark with the Unblock-File command.

How do I check whether a port is open on the server?

The check has three steps: listening, the firewall, and access from outside. The Get-NetTCPConnection -State Listen command shows whether a service listens on the port, the Get-NetFirewallPortFilter command shows whether a firewall rule allows it, and the Test-NetConnection command with the -Port option, run from another computer, checks whether the port is reachable from outside.

How do I find out why the server restarted?

The reason is recorded in the System log. The Get-WinEvent -FilterHashtable @{LogName='System'; Id=1074,6008} command shows the relevant events: event 1074 shows the user or process that started the restart and the reason given, for example installing updates, and event 6008 indicates an unexpected shutdown, such as a power outage or a crash.

Shopping cart

Your cart is emptyYou can start with one of our popular plans.

Site search

Accessibility

Text size
100%
Accessibility statement