PowerShell:Basic
lastmod 2023-02-24created 2023-02-245 edits
PowerShell basics
Looking up commands
- Get-Command - list commands
- Get-Help - command usage. e.g.
Get-Help dir - Get-Alias - list command aliases
Strings
Expandable string ("")
If a string contains a variable, the variable's value is inserted into the string.
Literal string ('')
Even if a string contains a variable, it is not replaced with the variable's value.
Escaping
PowerShell uses the backtick as its escape character.
Using the escape character keeps a variable name from being replaced with its value in an expandable string.
Replace
$str = 'abc_abc'
$$ = 'xyz'
$1 = '123'
$str -replace 'a(\w)', '$1' # bc_bc - a를 제외한 키워드 출력
$str -replace 'a(\w)', "$1" # 123c_123c - 변수 해석
$str -replace 'a(\w)', '$$$1' # $bc_$bc
$str -replace 'a(\w)', "$$$1" # xyz123c_xyz123c
Conditionals
if - elseif - else
$var = 5
if ( $var -eq 0 )
{
echo "`$var = 0"
}
elseif ($var -eq 1) {
echo "`$var = 1"
}
else {
echo "`$var = $var"
}
# 출력값 : $var = 5
switch (multi-way conditional)
Comparison operators
| Operator | Meaning | Symbol |
| | Equals | = |
| | Does not equal | != |
| | Greather than | > |
| | Less than | < |
| | Greater than or equal to | >= |
| | Less than or equal to | <= |
Wildcardcomparison
-
-like: matches. -
-notlike: does not match.
Regularexpression comparison
-
-match: regular expression match -
-notmatch: negated regular expression match
Loops
while
For
Foreach
A loop that iterates once for every item in an array or collection. (Unlike For, it handles the counting internally)
Or:
$_ refers to each element of the array or collection passed through the pipeline.
Arrays
Creating an empty array
Adding values
Using commas
Using the range operator
Delimited strings
Getting the array size
Reading array values
Or
Functions
Definition
function add_func {
Param ([int]$parm1 , [int]$parm2)
return $parm1+$parm2
}
$result = add_func -parm1 10 -parm2 5
Or
Function arguments and script file arguments are stored in the $args variable.