The PowerShell
This chapter describes the PowerShell.
Table of contents
- Introduction
- Execution policies
- Profile and path
- Passwordless remote login
- Some PowerShell commands
- PowerShell scripts
- Final word
Introduction
The primary command line interface (CLI) in Microsoft Windows 10 is the Windows PowerShell. It is designed to run commands and scripts to change system settings and automate tasks. It's similar to Command Prompt (CMD), but PowerShell is a more sophisticated and provides an extensive set of tools and offers more flexibility and control, especially for scripting.
To open the PowerShell, open the PowerUser menu (Win+X
) and select
“Windows PowerShell” or, if you need to run as Admin: “Windows PowerShell (Admin)”.
Execution policies
On MS Windows 10, PowerShell offer these six execution policies:
- Undefined
- Equivalent to “Restricted”, but is not given precedence. This is the default.
- Restricted
- Prevents all scripts from running.
- AllSigned
- Scripts will run if they have been signed by a trusted publisher. Unsigned scripts created on the LocalMachine will not run.
- RemoteSigned
- Scripts created on the LocalMachine will run. Scripts created on another machine will not run unless they are signed by a trusted publisher.
- Unrestricted
- Runs all scripts without any restrictions, but warns the user before running scripts and configuration files that are not from the local intranet zone.
- Bypass
- Nothing is blocked and there are no warnings or prompts (special use only).
The “Scope” values are listed in precedence order. The policy that takes precedence is effective in the current session, even if a more restrictive policy was set at a lower level of precedence. The scopes are:
- MachinePolicy
- Set by a Group Policy for all users of the computer.
- UserPolicy
- Set by a Group Policy for the current user of the computer.
- Process
- The Process scope only affects the current PowerShell session. The execution policy is saved in the environment variable
$env:PSExecutionPolicyPreference
, rather than the registry. When the PowerShell session is closed, the variable and value are deleted. - CurrentUser
- The execution policy affects only the current user. It's stored in the
HKEY_CURRENT_USER
registry subkey. - LocalMachine
- The execution policy affects all users on the current computer. It's stored in the
HKEY_LOCAL_MACHINE
registry subkey.
The following command will change the execution policy for “LocalMachine” (default) to “RemoteSigned”.
PS C:\> Set-ExecutionPolicy RemoteSigned Execution Policy Change The execution policy helps protect you from scripts that you do not trust. Changing the execution policy might expose you to the security risks described in the about_Execution_Policies help topic at https:/go.microsoft.com/fwlink/?LinkID=135170. Do you want to change the execution policy? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "N"): A
There is a long list of possible reponses. Typing “A” (Yes to All) completes all remaining steps of the command. In this case, there is just one step, so it is equivalent to “Y” (Yes).
To change the execution policy for a specific scope, use:
PS C:\> Set-ExecutionPolicy -Scope CurrentUser AllSigned
Use one of the commands below to inspect the excution policy or policies. The first command below gets the effective execution policy. The second command below gets the effective execution policy for the “CurrentUser” scope. The third gets all of the execution policies that affect the current session and display them in precedence order.
PS C:\> Get-ExecutionPolicy RemoteSigned PS C:\> Get-ExecutionPolicy -Scope CurrentUser AllSigned PS C:\> Get-ExecutionPolicy -List Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser AllSigned LocalMachine RemoteSigned
In this case, the effective execution policy is “AllSigned” because the execution policy for the CurrentUser takes precedence over the execution policy set for the LocalMachine. If the policy is “Undefined”, this is equivalent to to “Restricted” (but without precedece).
Source: Microsoft: About Execution Policies.
Profile and path
Your the user profile path is:
PS C:>: echo $env:userprofile C:\Users\gisle
You can create a PowerShell profile to customize your environment and to add session-specific elements to every PowerShell session that you start. The following command will tell you where the profile is located:
PS C:>: echo $profile C:\Users\gisle\OneDrive\Dokumenter\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
The path output in the example above is the real location for HNM-PC, and it is an oddball location compared to the examples on Microsoft: About Profiles. It has been configured automagically by Windows 10. The location may be due to the PC initially being set up Norwegian as the display language and me messing around with OneDrive. For good measure, when navigating in the File Explorer, the navigation path uses “Documents” (English) and not “Dokuments” (Norwegian). I.e.: . Rather than trying to fix this (and make it even more fubar of I get it wrong), I shall live with it.
To see the path used to find executable files and scripts, do the following:
PS C:>: echo $env:path C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem; C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\; C:\Program Files\PuTTY\;C:\Users\gisle\AppData\Local\Microsoft\WindowsApps;
To append a subdirectory named “Scripts” below the user profile to
this path, put this in the file named in $profile
:
$env:path += "$env:userprofile\Scripts;"
This appends “C:\Users\gisle\Scripts;
”.
See also: ComputerPerformance.co.uk: Environment variables. StackOverflow: Setting Windows PowerShell environment variables, Where to put PowerShell scripts?
Passwordless remote login
Place the matching public key is on in the
directory .ssh
on the web server. Place
id_rsa
in the directory ~/.ssh
(the
directory .ssh
in the user's home directory) on the
PC.
This works for both ssh and unison.
Some PowerShell commands
To get information about a PowerShell command, first try to use the
option /?
(e.g. ping /?
will get
information about ping
). Typically this will be usage and
a complete list of options. If this does not work, try running the command with no arguments.
You could also try:
PS C:>: get-help topic
… where topic may be a lot of different things.
A lot of PowerShell commands are aliased to commands that is provided by the Unix CLI. To list all of these:
PS C:>: get-alias * CommandType Name Version Source ----------- ---- ------- ------ Alias % -> ForEach-Object Alias ? -> Where-Object Alias ac -> Add-Content Alias asnp -> Add-PSSnapin Alias cat -> Get-Content Alias cd -> Set-Location …
In the list below, Unix aliases are given presedence over the native commands (shown in italics) since I am more familiar with Unix.
- cat
- Alias for Get-Content.
- cd
- Alias for Set-Location. The command “
cd ~
” wil take you to your home directory. - cls
- Alias for Clear-Host. Clear the screen. Unlike
Ctrl+L
, it limits back-scrolling. - echo
- Alias for Write-Output.
- exit
- Exit the shell and close shell window.
- findstr
- Find string in file.
- gin
- alias for Get-ComputerInfo.
- help
- Displays onscreen help about cmdlets and concepts.
- ipconfig
- Displays Windows IP configuration. May be helpful for debugging networking issues. The “Default Gateway” is the IP address of your router, and can be used to log on to the router to configure it.
- ls
- Alias for Get-ChildItem. Will display all of the files and folders within the current folder.
- man
- Alias for Get-Help.
- mkdir
- Make directory – will create a new subdirectory in the current directory.
- more
- Print the file given as argument to the screen, one page at the time..
- net
- General command to manage a network. This includes users.
- netstat
- Displays all sorts of information about existing connections to your PC, including TCP connections, ports on which your system is listening, Ethernet statistics and the IPRouting table.
- ping
- Useful for checking your network connection. Also useful for checking if local network systems are functioning properly, and for checking if a particular remote server is reachable.
- pwd
- Alias for Get-location. Print working directory.
- resolve-dnsname
- Get IP-address, like GNU/Linux host.
- shutdown
- CLI alternative to the GUI , with a lot of options.
- ssh
- OpenSSH client to connect to a remote ssh server.
- xcopy
- Extended comamnd to copy files and folders.
You should run the PoweShell as Admin to use the commands listed below. Some of them may make low level changes to your system, so becareful!
- chkdsk
- Check disk. Checks your chosen drive for physical errors.
Running this without any options will scan the disk and only produce a
status report. Running
chkdsk /F
will attempt to fix errors. Although there are plenty of tools for checking a disk for errors, chkdsk is a classic that works well and could save you from losing data if it finds a problem. - diskpart
- To manage drives (disks, partitions, volumes, or virtual hard disks). The comand
list volume
is the most useful. - dism
- Deployment Image Servicing and Management tool.
- sfc
- System File Checker.
Repair missing or corrupted system files
Microsoft recommends this procedure to examine all system files and replaced those that are missing or corrupted with a pristine copy. The steps are reproduced below.
First, make sure you've installed the latest updates for Windows 10. Then restart the PC. Start the PowerShell as Admin, and do the following:
PS C:>: DISM.exe /Online /Cleanup-image /Restorehealth The operation completed successfully PS C:>: sfc /scannow … Verification 100% complete …
Just type dism
and sfc
in
the PowerShell to see a list of options available for these
two commands. The most used options for “sfc
” are
“/verifyonly
” and “/scannow
”. The former
will scan through all of Windows' system files to look for any errors
but not repair them. The latter will do the same, and try to repair
them if it can. A full scan can take some time. The log from a scan
is located at C:\WINDOWS\Logs\CBS\CBS.log
.
Findstr
The command “findstr” is similar to the Unix command “grep”. However, by default it searches for fixed strings, not regexps.
Below are some examples of using it.
To extract all header lines from filename to a file named “toc.txt” for the TOC:
PS C:>: findstr '<h' filename > toc.txt
Then four options /spim
or /spin
are very handy for a recursive, case insensitive search for a word in or below the current directory:
PS C:>: findstr /spim netcraft * PS C:>: findstr /spin netcraft *
Meaning of options:
/s
: recurse directories./p
: skip files with non-printable characters./i
: ignore case./m
: only print the filename./n
: print line numbers.
Xcopy
To recursively copy (/S
) all directories and files
below C:\Users\Username
, except empty directories
(/I
), to the current directory, use:
PS E:\>xcopy /SI C:\Users\Username .
An ending backslash (C:\Users\Username\
) won't
fly.
To see all option:
PS E:\>xcopy /?
PowerShell scripts
A PowerShell script is just a collection of commands saved
into a text file (using the .ps1
extension)
that PowerShell can understand and execute in order to
perform one or multiple actions.
Unlike the Command Prompt, that provides no restrictions, the effective execution policy determines whether a PowerShell script will run or not. Enable the “RemoteSigned” execution policy before proceeding.
For a first script, use an editor to create a file named
helloworld.ps1
. Put the following single line in it:
Write-Host "Hello, World!"
To test it:
PS C:\>.\helloworld.ps1 Hello, World!
Here is a one-line PowerShell recursive script
named purge.ps1
that purges all backup files left behind
by emacs in the current directory and all directories
below:
Get-ChildItem . -Recurse -Include *~ | Remove-Item -Verbose
The common parameter
(see below) Verbose
outputs the name
of the file that is removed.
Source: StackOverflow.
Common parameters
The common parameters are a set of cmdlet parameters that you can use with any cmdlet. They're implemented by PowerShell, not by the cmdlet developer, and they're automatically available to any cmdlet.
Verbose (vb)
: Generate verbose output.
For a complete list of common parameters see the official documentation at Microsoft.com.
Windows PowerShell ISE
On top of the standard PowerShell CLI, there is the Windows PowerShell ISE (Integrated Scripting Environment). This is a GUI that allows you to run commands and create, modify and test scripts without having to type all the commands in the command line. The tool allows the development of scripts which are collections of commands where you can add complex logic for their execution.
The ISE is designed for the needs of the administrators of Windows systems that need to run repeatedly sequences of commands that manipulate the configuration of these systems.
To start ISE, search for it, or pin it to the start menu and use that.
Scheduled tasks
The MS Windows 10 equivalent of cron is known as scheduled tasks. It can be used from the GUI or from the PowerShell.
Final word
Last update: 2020-03-28 [gh].