Powershell: Difference between revisions
m Added navbox |
|||
| (13 intermediate revisions by the same user not shown) | |||
| Line 3: | Line 3: | ||
==== Comments ==== | ==== Comments ==== | ||
{{highlight|lang=powershell|code= | {{highlight|lang=powershell|code= | ||
# Single Line Comments | |||
<# | <# | ||
multi-line comments | multi-line comments | ||
| Line 14: | Line 16: | ||
-param1 value ` | -param1 value ` | ||
-param2 value | -param2 value | ||
}} | |||
==== Boolean Values ==== | |||
Use {{code|$TRUE}} or {{code|$FALSE}}. | |||
==== Strings ==== | |||
Strings can be: | |||
* Concatenated using {{code|+}} | |||
* Split using {{code|.Split("delimiter")}} (ie. PHP's {{code|explode()}}) | |||
* Joined (list of strings) using {{code|[string]::join("delimiter", $array)}} (ie. PHP's {{code|implode()}}) | |||
* Search/Replaced using {{code|-replace}}. Search patterns can be regex. | |||
{{highlight|lang=powershell|code= | |||
"hello.cs.cpsc.ucalgary.ca" -replace "cs.cpsc","cpsc" | |||
# Returns 'hello.cpsc.ucalgary.ca' | |||
}} | |||
* Searched using {{code|-match}}. Search patterns can be regex. | |||
{{highlight|lang=powershell|code= | |||
"hello.cs.cpsc.ucalgary.ca" -match "^hello.*ca$" | |||
# Returns True | |||
}} | }} | ||
| Line 25: | Line 46: | ||
}} | }} | ||
Arrays | Arrays (aka. Lists) | ||
{{highlight|lang=powershell|code= | {{highlight|lang=powershell|code= | ||
$a = @() | $a = @() | ||
$a += "Item" | $a += "Item" | ||
$a.Count # 1 | |||
$a.Remove("Item") # Can also remove by index range and number of items: $a.RemoveRange(0,1) | |||
$a.Clear() | |||
# Other things you may want to know: | |||
[array]::Reverse($a) # reverses array in place. | |||
}} | }} | ||
Hash Tables (aka. a Dictionary) | Hash Tables (aka. a Dictionary) | ||
{{highlight|lang=powershell|code= | {{highlight|lang=powershell|code= | ||
$a = @{} | # Basic Operation | ||
$a.Add("Key", "Value") | $a = @{} # or with initialized values: $a = @{"Key1" = "Value1" ; "Key2" = "Value2"} | ||
$a.Add("Key", "Value") | |||
$a["Key"] = "New Value" | |||
$a.Remove("Key") | |||
# To iterate over the hash table | |||
$a.GetEnumerator() | ForEach-Object { ... } | |||
}} | }} | ||
==== Parameters ==== | ==== Parameters ==== | ||
For functions, parameters can be given as part of the function definition. Eg: | |||
{{highlight|lang=powershell|code= | |||
function Get-HostsFromServer([string]$IpAddress) { | |||
# ... | |||
} | |||
}} | |||
Alternatively: | |||
{{highlight|lang=powershell|code= | {{highlight|lang=powershell|code= | ||
param ( | function Get-HostsFromServer { | ||
param( [string]$IpAddress ) | |||
# ... | |||
} | |||
}} | }} | ||
You can have strict parameter checking with Advanced Functions (ie. script cmdlets which contain the 3 methods {{code|begin}}, {{code|process}}, {{code|end}}). | |||
=== Common Tasks === | === Common Tasks === | ||
| Line 57: | Line 102: | ||
{{highlight|lang=powershell|code= | {{highlight|lang=powershell|code= | ||
Where-Object {$_.RecordData.IPv4Address -like "172.20.1.*" } | Where-Object {$_.RecordData.IPv4Address -like "172.20.1.*" } | ||
}} | |||
==== Limiting ==== | |||
Pipe to {{code|Select}} with the desired option. This is similar to {{code|head}} and {{code|tail}} in UNIX shells. | |||
{{highlight|lang=powershell|code= | |||
# First (Analogous to `head -n 1`) | |||
Select -last 1 | |||
# Last (Analogous to `tail -n 1`) | |||
Select -last 1 | |||
}} | }} | ||
| Line 80: | Line 136: | ||
== Other Stuff == | == Other Stuff == | ||
=== Get machine | === Get machine UUID === | ||
To get the UUID of the computer (analogous to {{code|dmidecode{{!}}grep -i uuid}}), run: | |||
{{highlight|lang=powershell|code= | |||
get-wmiobject Win32_ComputerSystemProduct | Select-Object -ExpandProperty UUID | |||
}} | |||
== Troubleshooting == | == Troubleshooting == | ||
{{highlight|lang=terminal|code= | |||
Error: "File cannot be loaded because the execution of scripts is disabled on this system" | |||
}} | |||
To allow untrusted script execution, open a powershell instance (same arch as what you're trying to run the script as. ie: 64bit/32bit) as Administrator and run: | To allow untrusted script execution, open a powershell instance (same arch as what you're trying to run the script as. ie: 64bit/32bit) as Administrator and run: | ||
{{highlight|lang=terminal|code= | |||
PS> set-executionpolicy unrestricted | |||
}} | |||
You should now be able to see: | You should now be able to see: | ||
{{highlight|lang=terminal|code= | |||
PS> get-executionpolicy | PS> get-executionpolicy | ||
Unrestricted | Unrestricted | ||
}} | |||
{{Navbox Windows}} | |||
[[Category:Windows]] | [[Category:Windows]] | ||
Latest revision as of 01:45, 30 December 2021
Quick Overview
Syntax
Comments
# Single Line Comments
<#
multi-line comments
#>
Multi-Line Commands
Similar to the \ in bash, use the backtick to continue the command on the next line.
Do-Something `
-param1 value `
-param2 value
Boolean Values
Use $TRUE or $FALSE.
Strings
Strings can be:
- Concatenated using
+ - Split using
.Split("delimiter")(ie. PHP'sexplode()) - Joined (list of strings) using
[string]::join("delimiter", $array)(ie. PHP'simplode()) - Search/Replaced using
-replace. Search patterns can be regex.
"hello.cs.cpsc.ucalgary.ca" -replace "cs.cpsc","cpsc"
# Returns 'hello.cpsc.ucalgary.ca'
- Searched using
-match. Search patterns can be regex.
"hello.cs.cpsc.ucalgary.ca" -match "^hello.*ca$"
# Returns True
Data Containers
These are things in powershell that can contain data values or other objects.
Objects
$a = New-Object –TypeNamePSObject
$a
Arrays (aka. Lists)
$a = @()
$a += "Item"
$a.Count # 1
$a.Remove("Item") # Can also remove by index range and number of items: $a.RemoveRange(0,1)
$a.Clear()
# Other things you may want to know:
[array]::Reverse($a) # reverses array in place.
Hash Tables (aka. a Dictionary)
# Basic Operation
$a = @{} # or with initialized values: $a = @{"Key1" = "Value1" ; "Key2" = "Value2"}
$a.Add("Key", "Value")
$a["Key"] = "New Value"
$a.Remove("Key")
# To iterate over the hash table
$a.GetEnumerator()
Parameters
For functions, parameters can be given as part of the function definition. Eg:
function Get-HostsFromServer([string]$IpAddress) {
# ...
}
Alternatively:
function Get-HostsFromServer {
param( [string]$IpAddress )
# ...
}
You can have strict parameter checking with Advanced Functions (ie. script cmdlets which contain the 3 methods begin, process, end).
Common Tasks
Writing Output
Use Write-Host to write logging information to the console. It runs [console]::WriteLine() in the background.
Use Write-Output to write to the pipeline.
In either case, wrap the output text in brackets so that concatenation works as expected. Eg: Write-Output ("Hello" + $World).
Filtering
Pipe to Where-Object and provide the matching condition.
Where-Object {$_.RecordData.IPv4Address -like "172.20.1.*" }
Limiting
Pipe to Select with the desired option. This is similar to head and tail in UNIX shells.
# First (Analogous to `head -n 1`)
Select -last 1
# Last (Analogous to `tail -n 1`)
Select -last 1
Iterating
Use the ForEach statement:
foreach($item in $items) {
# do things on $item
}
Or if you're dealing with a list of objects, pipe to the ForEach-Object. Pass in any of:
-process- Runs for each incoming object-begin- Runs before any object is processed-end- Runs after objects are processed
Eg:
ForEach-Object -process { $_.doSomething() }
Other Stuff
Get machine UUID
To get the UUID of the computer (analogous to dmidecode|grep -i uuid), run:
get-wmiobject Win32_ComputerSystemProduct
Troubleshooting
Error: "File cannot be loaded because the execution of scripts is disabled on this system"
To allow untrusted script execution, open a powershell instance (same arch as what you're trying to run the script as. ie: 64bit/32bit) as Administrator and run:
PS> set-executionpolicy unrestricted
You should now be able to see:
PS> get-executionpolicy
Unrestricted