Powershell: Difference between revisions
Jump to navigation
Jump to search
Line 658: | Line 658: | ||
} |
} |
||
} |
} |
||
</source> |
|||
== Issues == |
|||
=== Resolve-Path / Directory.Parent returns wrong path === |
|||
<source lang="powershell"> |
|||
# This fails in PS 5.1, but is fixed in PS 7.2 at least |
|||
mkdir -f foo > $null |
|||
mkdir -f backup\foo\bin |
|||
echo "bar" > backup\foo\bin\bar.txt |
|||
$bar = $(gi backup\foo\bin\bar.txt) |
|||
$bar.Directory.Parent | Resolve-Path -Relative # foo -- BAD |
|||
gi $bar.Directory.Parent.FullName | Resolve-Path -Relative # backup\foo -- GOOD |
|||
</source> |
</source> |
Revision as of 20:04, 8 March 2022
Links
- Learn powershell in Y minutes — A MUST-READ to learn rapidly.
- Everything you wanted to know about arrays - microsoft.com
- Everything you wanted to know about hashtables - microsoft.com
- About preference variables - microsoft.com
- Getting to Know ForEach and ForEach-Object - microsoft.com
- Get-Content - microsoft.com
- about_Scopes - microsoft.com
Reference
Files
Powershell scripts have a .ps1 extension.
Environment
Powershell uses preference variables [1]:
$ErrorActionPreference
: value can be'SilentlyContinue'
,'Stop'
,'Continue'
(default),'Inquire'
,'Ignore'
,'Suspend'
, or'Break'
.
To get powershell version:
Get-Host
Get-Host | select version
# or
$PSVersionTable
Syntax
✐ | See learn Powershell in Y minutes for more! |
Scopes
Primitive types / operators
Strings / arrays / hashtables / ...
# 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!'[0,2,4] # 'H', '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
$fixed=1,2,3
$fixed.Add(4) # ! Exception
$fixed.Item(1) # 2
$fixed[1] # 2
# Use .Net for variable (and faster!) arrays
[System.Collections.ArrayList]$array = @()
[System.Collections.ArrayList]$array = @(1,2,3)
$array.Add(4) # 3 -- index of last element
$array.Add(5) > $null # ... to absorb output
# Hash table
$emptyHash = @{} # Empty hash
$filledHash = @{"one"= 1
"two"= 2
"three"= 3}
$filledHash["one"] # => 1
$filledHash.Values # => [1, 2, 3]
"one" -in $filledHash.Keys # => True
1 -in $filledHash.Values # => False
$filledHash["four"] # $null
$filledHash.Add("five",5) # $filledHash["five"] is set to 5
$filledHash.Add("five",6) # exception "Item with key "five" has already been added"
$filledHash["four"] = 4 # $filledHash["four"] is set to 4, running again does nothing
$filledHash.Remove("one") # Removes the key "one" from filled dict
Control flow
IO / Files
Functions
# Functions: keep 'Verb-Noun' convention!
function Add-Numbers { # No explicit args
$args[0] + $args[1]
}
Add-Numbers 1 2 # 3
function Add-Numbers($first,$second) { # Explicit args
$first + $second
}
function Add-Numbers { # Explicit args with type
param( [int]$first, [int]$second )
$first + $second
}
Add-Numbers 1 2 # 3, still works
Add-Numbers -first 1 -second 2 # 3
Add-Numbers 1 -second 2 # 3
$params=@{first=1; second=2}
Add-Numbers @params # 3, can pass hashtable as params
$res = $(Add-Numbers 1 2)
$res = Add-Numbers 1 2 # same
# Use Switch to build toggle flag
function Inc-Number($value,[Switch]$Verbose)
{
if ($Verbose) { Write-Output $value }
$value + 1
}
Inc-Number 1 -Verbose
Exec
Miscellaneous
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:
# On online computer
New-Item c:\tmp\help
Save-Help -DestinationPath c:\tmp\help -Module * -Force
# On offline computer
# ... transfer files to c:\tmp\help
# ... start powershell in admin (Win-X-A)
Update-Help -SourcePath c:\tmp\help -Module * -Force
Find all links recursively
From SO:
dir 'd:\Temp' -recurse -force | ?{$_.LinkType} | select FullName,LinkType,Target
# In case of multi targets for hardlinks, this list them separated by TAB
dir 'd:\Temp' -recurse -force | ?{$_.LinkType} | select FullName,LinkType,@{ Name = "Targets"; Expression={$_.Target -join "`t"} }
Test if a path is a file or a folder
# https://devblogs.microsoft.com/scripting/powertip-using-powershell-to-determine-if-path-is-to-file-or-folder/
# Using object type
(Get-Item C:\fso) -is [System.IO.DirectoryInfo] # True
(Get-Item C:\fso\csidl.txt) -is [System.IO.DirectoryInfo] # False
# Using PSIsContainer attribute
(Get-Item -Path C:\fso).PSIsContainer # True
(Get-Item -Path C:\fso\csidl.txt).PSIsContainer # False
Read / Write / Modify file line by line
- Reading a file is done through
Get-Content
. - Writing to a file is done through
Set-Content
.
- DO NOT USE
Out-File
, because it does SLICE the long lines, hence modifying output, and also output non-matching (ie. empty) lines.
- DO NOT USE
# This is slow on big file
Set-Content .\newfile.txt -Value (Get-content .\file.txt | Select-String -Pattern 'H\|159' -NotMatch)
# Another way using pipe and
Get-Content .\file.txt | Where-Object { -not $_.Contains('H|159') } | Set-Content .\newfile.txt
- Use
foreach
to process the file line by line, orForEach-Object
with a pipeline (see this blog).
foreach
is a statement likeif
. It will always load the ENTIRE COLLECTION in an object before starting processing.ForEach-Object
is however pipeline aware, and have a lower memory usage (but is less performant).
# however foreach loads the ENTIRE file in memory first.
foreach($line in Get-Content .\file.txt) {
if($line -match $regex){
# Work here
}
}
# Pipe-aware - Less memory, slower.
Get-Content .\file.txt | ForEach-Object {
if($_ -match $regex){
# Work here
}
}
# Or use pipe and Where-Object
Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
# Work here
}
# ... short syntax ...
gc 'file.txt' | ?{ $_ -match $regex } | %{ # Work here }
- Use
swith -regex -file
to filter a file with regular expression.
'one
two
three' > file
$regex = '^t'
switch -regex -file file {
$regex { "line is $_" }
}
- With .NET library, use
[System.IO.File]
for better performance:
# Low memory and good performance
[System.IO.File]::ReadLines("C:\path\to\file.txt") | ForEach-Object {
$_
}
# This is faster, but still foreach will load the whole file in memory first
foreach($line in [System.IO.File]::ReadLines("C:\yourpathhere\file.txt"))
{
Write-Output $line
}
# ...
[System.IO.StreamReader]$sr = [System.IO.File]::Open($file, [System.IO.FileMode]::Open)
while (-not $sr.EndOfStream){
$line = $sr.ReadLine()
}
$sr.Close()
Get-Content
Get-Content
is aliased:
gc
cat
Get-Content .\File.txt
gc .\File.txt # Shorter
cat .\File.txt # Shorter... unix like
gc .\File.txt -TotalCount 5 # Limit output
# Process
1..100 | ForEach-Object { Add-Content -Path .\LineNumbers.txt -Value "This is line $_." }
Get-Content -Path .\LineNumbers.txt
Regular expressions
Syntax is mostly the same as POSIX.
'book' -match 'oo' # True
'book' -match 'o*' # True
' - ' -match '\s- ' # True - Match whitespace
# Group and capture
'Hello, World!' -match '(Hello).*(World)' # True
$Matches
# Name Value
# ---- -----
2 World
1 Hello
0 Hello, World
$Matches.1 # Hello
$Matches.Item(1) # Hello
$Matches[1] # Hello
# Replace
'John D. Smith' -replace '(\w+) (\w+)\. (\w+)', '$1.$2.$3@contoso.com'
Set-Location in a local scope
try {
Push-Location .\Some\Path
# stuff
}
finally {
Pop-Location
}
Get relative path to another directory
Inspired from SO:
function Get-Relative-Path($fromPath,$toPath)
{
try {
Push-Location $fromPath; Get-Item $toPath | Resolve-Path -Relative
}
finally {
Pop-Location
}
}
Issues
Resolve-Path / Directory.Parent returns wrong path
# This fails in PS 5.1, but is fixed in PS 7.2 at least
mkdir -f foo > $null
mkdir -f backup\foo\bin
echo "bar" > backup\foo\bin\bar.txt
$bar = $(gi backup\foo\bin\bar.txt)
$bar.Directory.Parent | Resolve-Path -Relative # foo -- BAD
gi $bar.Directory.Parent.FullName | Resolve-Path -Relative # backup\foo -- GOOD