Powershell: Difference between revisions

From miki
Jump to navigation Jump to search
Line 10: Line 10:
{{Note|See learn Powershell in Y minutes for more!}}
{{Note|See learn Powershell in Y minutes for more!}}


<div style="column-width:40em;-webkit-column-width:40em;-moz-column-width:40em;">
<source lang="powershell">
<source lang="powershell">
# Documentation, information
# Documentation, information
Line 26: Line 27:
ps | Get-Member
ps | Get-Member


# Frequent aliases
# Frequent aliases (sorted by definition)
# gcm -> Get-Command
# ps -> Get-Process
# help -> Get-Help
# help -> man
# alias -> Get-Alias
# alias -> Get-Alias
# gal -> Get-Alias
# gal -> Get-Alias
# dir -> Get-ChildItem
# ls -> Get-ChildItem
# gci -> Get-ChildItem
# gcm -> Get-Command
# cat -> Get-Content
# type -> Get-Content
# help -> Get-Help
# gm -> Get-Member
# gm -> Get-Member
# ps -> Get-Process
# man -> help
# ni -> New-Item
# ni -> New-Item
# md -> New-Item
# md -> New-Item
Line 44: Line 50:
# rmdir -> Remove-Item
# rmdir -> Remove-Item
# where -> Where-Object
# where -> Where-Object
# dir -> Get-ChildItem
# ls -> Get-ChildItem
# gci -> Get-ChildItem
# echo -> Write-Output
# echo -> Write-Output
# write -> Write-Output
# write -> Write-Output
Line 58: Line 61:
gal | where {$_.Definition -eq 'Get-Help'}
gal | where {$_.Definition -eq 'Get-Help'}
dir Alias: | where {$_.Definition -eq 'Get-Help'}
dir Alias: | where {$_.Definition -eq 'Get-Help'}
</source>
</div>


;Primitive types / operators
<div style="column-width:35em;-webkit-column-width:35em;-moz-column-width:35em;">
<source lang="powershell">
# Numbers
3
1 + 1 # 2
2 - 1 # 1
10 * 2 # 20
10 / 2 # 5
10 / 3 # 3.3333333
[int](10 / 3) # 3
[int]1.5 -eq [int]2.5 # True !
10 % 3 # 1
[Math]::Pow(2,3) # 8

# Boolean
$True # True
$False # False
$True -and $True
$False -or $False
0 -eq $False # True
2 -ne $True # True
[bool](0) # False

# Bitwise
0 -band 2 # 0
-5 -bor 0 # -5

# Comparison
1 -eq 1
1 -ne 0
0 -lt 1
1 -le 1
1 -gt 0
1 -ge 1
</source>
</div>

; Strings / arrays / dictionaries / ...
<div style="column-width:35em;-webkit-column-width:35em;-moz-column-width:35em;">
<source lang="powershell">
# Strings
# Strings
$hello = "Hello"
$hello = "Hello"
Line 74: Line 120:
"foo" | gm # Get all methods / properties
"foo" | gm # Get all methods / properties


# Arrays
# TBC

# Dictionaries
# TBC
</source>
</div>

;Control flow
<div style="column-width:35em;-webkit-column-width:35em;-moz-column-width:35em;">
<source lang="powershell">
# if-then-else
if ($someVar -gt 10) {
Write-Output "..."
}
elseif ($someVar -lt 10) {
Write-Output "..."
}
else {
Write-Output "..."
}
</source>

<source lang="powershell">
# foreach
foreach ($animal in ("dog", "cat", "mouse")) {
# You can use -f to interpolate formatted strings
"{0} is a mammal" -f $animal
}
</source>

<source lang="powershell">
# for
$letters = ('a','b','c','d','e','f','g','h')
for($i=0; $i -le $letters.Count-1; $i++){
Write-Host $i, $letters[$i]
}
</source>

<source lang="powershell">
# while
$x = 0
while ($x -lt 4) {
Write-Output $x
$x += 1 # Shorthand for x = x + 1
}
</source>

<source lang="powershell">
# switch
$val = "20"
switch($val) {
{ $_ -eq 42 } { "The answer equals 42"; break }
'20' { "Exactly 20"; break }
{ $_ -like 's*' } { "Case insensitive"; break }
{ $_ -clike 's*'} { "clike, ceq, cne for case sensitive"; break }
{ $_ -notmatch '^.*$'} { "Regex matching. cnotmatch, cnotlike, ..."; break }
default { "Others" }
}
</source>

<source lang="powershell">
# try-catch-finally
# ...
</source>

</div>

;IO
<div style="column-width:35em;-webkit-column-width:35em;-moz-column-width:35em;">
<source lang="powershell">
# read / write
# read / write
Write-Output "Hello World!" # alias: echo, write
Write-Output "Hello World!" # alias: echo, write
Line 79: Line 196:
$bar = Read-Host ("Enter {0}" -f $foo)
$bar = Read-Host ("Enter {0}" -f $foo)
</source>
</source>
</div>

;Functions
<div style="column-width:35em;-webkit-column-width:35em;-moz-column-width:35em;">
<source lang="powershell">
# Functions: keep 'Verb-Noun' convention!

function Add-Numbers { # No explicit args
$args[0] + $args[1]
}

function Add-Numbers($first,$second) { # Explicit args
$first + $second
}

Add-Numbers 1 2 # => 3
$res = Add-Numbers 1 2
$res = $(Add-Numbers 1 2)
</source>

</div>


== Tips ==
== Tips ==

Revision as of 13:57, 22 February 2022

Links

Reference

Files

Powershell scripts have a .ps1 extension.

Syntax

 ✐  See learn Powershell in Y minutes for more!
# Documentation, information
Update-Help              # Update help system - to run as Administrator
help Test-Path           # Get help on a command, on an alias...
help Test-Path -full     # ... and on all options
help Test-Path -examples # ... see examples. VERY USEFUL. Eg. help save-help examples

Get-Command about_*      # DOES NOT WORK
Get-Command -Verb Add

Get-Alias ps                      # 'Get-Process'
Get-Alias -Definition Get-Process # 'ps'
gal | findstr Get-Process         # Unix style

ps | Get-Member

# Frequent aliases (sorted by definition)
#   alias  ->  Get-Alias
#   gal    ->  Get-Alias
#   dir    ->  Get-ChildItem
#   ls     ->  Get-ChildItem
#   gci    ->  Get-ChildItem
#   gcm    ->  Get-Command
#   cat    ->  Get-Content
#   type   ->  Get-Content
#   help   ->  Get-Help
#   gm     ->  Get-Member
#   ps     ->  Get-Process
#   man    ->  help
#   ni     ->  New-Item
#   md     ->  New-Item
#   mkdir  ->  New-Item
#   del    ->  Remove-Item
#   erase  ->  Remove-Item
#   rd     ->  Remove-Item
#   ri     ->  Remove-Item
#   rm     ->  Remove-Item
#   rmdir  ->  Remove-Item
#   where  ->  Where-Object
#   echo   ->  Write-Output
#   write  ->  Write-Output

# Options can be abbreviated
Get-Alias -Definition Get-Process
gal -def Get-Process

# Grep-like
gal | findstr Get-Process
gal | where {$_.Definition -eq 'Get-Help'}
dir Alias: | where {$_.Definition -eq 'Get-Help'}
Primitive types / operators
# Numbers
3
1 + 1                  # 2
2 - 1                  # 1
10 * 2                 # 20
10 / 2                 # 5
10 / 3                 # 3.3333333
[int](10 / 3)          # 3
[int]1.5 -eq [int]2.5  # True !
10 % 3                 # 1
[Math]::Pow(2,3)       # 8

# Boolean
$True                  # True
$False                 # False
$True  -and $True
$False -or  $False
0 -eq $False           # True
2 -ne $True            # True
[bool](0)              # False

# Bitwise
0 -band 2              # 0
-5 -bor 0              # -5

# Comparison
1 -eq 1
1 -ne 0
0 -lt 1
1 -le 1
1 -gt 0
1 -ge 1
Strings / arrays / dictionaries / ...
# Strings
$hello = "Hello"
$world = "World"
'Hello, World!'                        # No interpolation
"Hello, $world!"                       # 'Hello, World!'
"Hello, World!".Length                 # Length
"{0}, {1}!" -f $hello, $world          # f-string
"$world is $($world.length) char long"
'Hello, World!'[0]                     # 'H'
'Hello, World!'[0..5]                  # 'H', 'e', 'l', 'l', 'o'
'Hello, World!'.Substring(0,5          # 'Hello'
'Hello, ' + 'World!'                   # 'Hello, World!'
'First line`nSecond line'              # Escape with backtick
"foo" | gm                             # Get all methods / properties

# Arrays
# TBC

# Dictionaries
# TBC
Control flow
# if-then-else
if ($someVar -gt 10) {
   Write-Output "..."
}
elseif ($someVar -lt 10) {
   Write-Output "..."
}
else {
   Write-Output "..."
}
# foreach
foreach ($animal in ("dog", "cat", "mouse")) {
    # You can use -f to interpolate formatted strings
    "{0} is a mammal" -f $animal
}
# for
$letters = ('a','b','c','d','e','f','g','h')
for($i=0; $i -le $letters.Count-1; $i++){
    Write-Host $i, $letters[$i]
}
# while
$x = 0
while ($x -lt 4) {
    Write-Output $x
    $x += 1  # Shorthand for x = x + 1
}
# switch
$val = "20"
switch($val) {
  { $_ -eq 42 }           { "The answer equals 42"; break }
  '20'                    { "Exactly 20"; break }
  { $_ -like 's*' }       { "Case insensitive"; break }
  { $_ -clike 's*'}       { "clike, ceq, cne for case sensitive"; break }
  { $_ -notmatch '^.*$'}  { "Regex matching. cnotmatch, cnotlike, ..."; break }
  default                 { "Others" }
}
# try-catch-finally
# ...
IO
# read / write
Write-Output "Hello World!"            # alias: echo, write
$foo = Read-Host "Enter foo"
$bar = Read-Host ("Enter {0}" -f $foo)
Functions
# Functions: keep 'Verb-Noun' convention!

function Add-Numbers {  # No explicit args
 $args[0] + $args[1]
}

function Add-Numbers($first,$second) { # Explicit args
 $first + $second
}

Add-Numbers 1 2 # => 3
$res = Add-Numbers 1 2
$res = $(Add-Numbers 1 2)

Tips

Measure execution time of a command

Measure-Command { dir }
Measure-Command { dir | Out-default}   # To get output
Measure-Command { choco list }

Update help on offline computers

From MS devblogs:

<source lang="powershell">

  1. On online computer

New-Item c:\tmp\help Save-Help -DestinationPath c:\tmp\help -Module * -Force

  1. On offline computer
  2. ... transfer files to c:\tmp\help
  3. ... start powershell in admin (Win-X-A)

Update-Help -SourcePath c:\tmp\help -Module * -Force </source