PowerShell
Is a shell and programming language designed for task automation and configuration. Aim to replace Batch.
See the powershell-cheat-sheet.pdf - Source
Concept¶
- Unix is object-based, while Windows is API-based
- Usually note case-sensitive
CommandletsorCmdlets- Verb - Noun
- Commands are small, so users can write what they want
- Commands that can be used
- Specific to PowerShell
- Standard Windows and Linux via alias
- Aliases naming is consistent
get-aliasto list them allget-alias sa*to get all aliases starting withsaget-alias -Definition get-processto get all aliases for commandget-process
- Help system to find how you want to do
get-help get-serviceto bring help onget-service... -Detailedto have more things, like parameters... -Fullfor even more... -Onlineto get the web version... -ShowWindowto get a windowed version of the help
get-help about_*for conceptual helpsget-help g*service*to list all commands with start withgthen haveservicein the nameupdate-help -Forceto update all helps
- Modules to have more functionalities
Get-Moduleto view currently loaded modulesGet-Module - ListAvailableto list all modules
Language¶
Syntax¶
| Command | Action |
|---|---|
# comment |
Comment |
<# comment block #> |
Comment block |
get-service -Name XYZ |
Call the command get-service with parameter Name and variable XYZ |
net view |
Call the parameter set view of the command net |
abc; def |
Call abc, then def |
abc (def) |
Call def, then abc |
abc \| def |
Call abd, then pipe the output object into def (new line can be added after \| for visibility) (without \) |
*string* |
Wildcard |
$_ or $PSItem |
Current object in the pipeline |
{} |
Script block to be called within another command |
$a |
Call variable a |
backtick |
Escape character, or Go to a next line for clarity in script |
Set-PSDebug -Trace 2 |
Trace everything on the console |
Value type¶
- Object
get-memberorgmto find themproperties: Thing the object has- Can be browsed with
.within the object - Called
ByPropertyXin the documentation
- Can be browsed with
method: Thing the object can do
- String
- Arrays with
[]
Piping¶
- Objects are piped from one command to another using
|, not the text representation - A carriage return can be done after
|for clarity - Allow chain of commands like
get-service -name bits | stop-service
- Sender
- Use
gmto find the Type of object sent
- Use
- Receiver
- Check the documentation to verify if an input can take pipeline
get-help abc -Full- "Accept pipeline input": true
-InputObject xyz[]acceptxyzobject type - must match the Sender Object Type name- Sometime the Receiver that accepts pipe has a different name
- Sometime the receiver doesn't accept Object
- Build the sender query and filter using
selectdown to the necessary information - Use
select -ExpandProperty xto convert to a string - Bundle that in parenthesis
(get-xyz | select -ExpandProperty y)and pass it as a parameter - Dot syntax:
(get-xyz).name - Script block:
get-abc | get-xyz {$_.Name}to doget-abc, then callget-xyzfor each valueNameofget-abc
- Build the sender query and filter using
- Check the documentation to verify if an input can take pipeline
- If the Sender and receiver have a match noun, t
Loops & Conditions¶
foreach {}
Useful commands¶
- Some parameter commands are common to any cmdlet - check
help about_CommonParameters- Output
abc -OutVariable ato output to variablea
- Risk Mitigation
abc -whatif: Dry-call the functionabcand describe what could happen, without doing itabc -confirm: Call a confirm box before executingabc
- Output
Variables¶
$MyVar = "hello"to setMyVartohello$MyVar = Get-service xyzwill put the object in it$is necessary to differentiate variables to programs${path\to\file} = "content"will assign"content"to a variable stored inpath\to\file
$MyVarto read it$MyVar.statusto get the propertystatusof variableMyVar- Sometime the property isn't refreshed in real-time, so maybe you need to call
.refresh()or similar
- Sometime the property isn't refreshed in real-time, so maybe you need to call
$MyVar.stop()to call methodstop
Remove-Variableto delete a variable- Useful in scripts, as a
""variable doesn't have the same effect than a non-existing variable
- Useful in scripts, as a
- If in a script, parameters variables can also be defined in
param ()- see PowerShell - Advanced help:
get-help *variable* - Environment variable in Batch are defined as
$Env:ENVIRONMENT_VARIABLE_NAME
Interaction with CLI¶
- Input
read-host
- Output
write-hostbut consume the objectwrite-outputwrite-warningwrite-error: throw an error
Interaction with scripts or other commands¶
Get-State A1: Call functionGet-Statewith parameterA1.\script.ps1: Callscript.ps1. .\script.ps1: Callscript.ps1in the current scope - see dot-sourcing operator& .\script.ps1: Callscript.ps1in a child scope - see call operator$?will contain last command's execution status withTrueif it succeeded - see about_Automatic_Variables
$output = pwd 2>&1- 1 is standard output descriptor (
stdout) and 2 is error output (stderr) - See about_redirection 2>&1redirect stream from 2 to 1,>send to file and>>appends
- 1 is standard output descriptor (
Analysis of output¶
Select-objectorselect-Property xto show columnxonly-Property @{n='abc';e={$_.Name}}to create columnabcthat will contain theNamenfor name - orlfor label (but it looks like1)efor expression
@{}is a "hash table syntax", documented in manual
-ExpandProperty xto convert columnxto String
Where-objectorwhere{ }to define filter- Will return
$trueor$falsefor each row, and$trueobjects are kept get-help *comparison*andget-help *operators*
sortgroupsplitMeasure-Command {command}to measure the timecommandtakeTee-Objectto copy the output object into something, while passing it to the next in pipe
File manipulation¶
copy-item
Import & Export data¶
compare-objectexport-have a file output, whileConvertTo-can be piped- Text
out-fileto export content to fileget-content
- CSV
export-csvConvertTo-CSVimport-csv
- XML
export-clixml$x = [xml](cat .\file.xml)loadfile.xmlas XML object- Can be browsed via
x.a[0]to display content of 1st object - Or
x.ato list everything
- Can be browsed via
- HTML
ConvertTo-html
Windows-specific¶
- Processes
get-process
- Events
get-eventlog
Usage¶
- Check that you're admin before doing something
Setup¶
Linux¶
- List of supported Linux OS and how to install them
Raspberry Pi OS¶
Interface¶
- In the console window, right-click on icon ->
Properties
Remoting to other PCs¶
- Setup
- Called WinRM - Windows Remote Management
- Need to be enabled
- When a script is finished, the session is destroyed
- Control another PC
Enter-PSSessioninvoke-commandoricm
- Control sessions
New-PSSessionto open a session, can be assigned to a$varGet-PSSession
- Use modules from another session
Import-PSSession
Scripting¶
- Scripts saved as
.ps1files - Modules are saved as
.psm1- Import via via
Import-Module - Or place them in directories defined in
cat Env:\PSModulePath- The name of the subfolder need to be the name of the module file
- Import via via
- Can be called with
.\script.ps1- Doesn't work without
.\ - Need the Execution Policy to be set
. .\script.ps1to keep all the script in memory- By default, nothing is shown to the user except errors
Set-PSDebug -Trace 1to script each line, and2for more - see help
- Doesn't work without
- The PowerShell ISE can be used as an IDE
- Auto-completion with
CTRL+Space - Snippets with
CTRL+J
- Auto-completion with
param()to set parameters for Variables, set within and the whole script called with-MyVar- Mandatory parameters will be called out when calling the function via CLI
- It's already a string in that case, so no need to put
""for instance!
- It's already a string in that case, so no need to put
- Mandatory parameters will be called out when calling the function via CLI
function Verb-Noun{ ... }to set functionget-helpwill work with the script with info in<# #>
<#
.Synopsis
Short description
.Description
This is the long description
.Parameter MyVar
Description of MyVar
.Example
ScriptName -MyVar toto
#>
[CmdletBinding()] # To be able to set variables as mandatory
# Param must be on the 1st line
param (
$MyVar = 'helloWorld' # Variable that can be passed on as a parameter (-MyVar) with a default variable
[Parameter(Mandatory=$True)] # The next variable is mandatory
[string[]]$MyVar2 # String array variable
)
function Verb-Noun{ # Start a function
# Do something
}
# Call the function
Verb-Noun
Security¶
New-SelfSignedCertificate- Execution Policy direct scripting
Get-ExecutionPolicySet-ExecutionPolicyallsigned: Everything must be signed- And ask confirmation if untrusted publisher
remotesigned: Remote files must be signed, not local ones
get-psdrivewill bring you also theCertdrivedir Cert:\CurrentUser -Recurse -CodeSigningCert -OutVariable ato export all code signing certificate$cert = $a[0]to take the 1st certificate from last command
Set-AuthenticodeSignature -Certificate $cert -FilePath .\script.ps1to signScript.ps1- See kloppenborg.net - Restic Backup for Windows Client for tips on how to enable PowerShell scripts and automate them
External calls¶
- Parameters for the
PowerShell.execommands:- Path:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command "Set-Location /path/to/dir"to do a command-Command "& '/path/to/script.ps1'to run a script-File "/path/to/script.ps"to run a script-NoExitto keep the window open-WindowStyle Hiddento hide the window - Seems to work only with admin privilege-ExecutionPolicy Bypassto bypass the PowerShell check
- Path:
- Scheduling: See Windows Task Scheduler