Powershell: Difference between revisions
Jump to navigation
Jump to search
(→Syntax) |
|||
Line 289: | Line 289: | ||
# ExternalScript test.ps1 C:\tmp\test.ps1 |
# ExternalScript test.ps1 C:\tmp\test.ps1 |
||
$MyInvocation.MyCommand.Definition # C:\tmp\test.ps1 |
$MyInvocation.MyCommand.Definition # C:\tmp\test.ps1 |
||
# Namespaces |
|||
ls "HKLM:\Software\Microsoft\PowerShell\1\ShellIds" # HKLM for registry |
|||
"$env:PATH" # Env variables |
|||
</source> |
</source> |
||
</div> |
</div> |
Revision as of 16:11, 22 February 2022
Links
- Learn powershell in Y minutes — A MUST-READ to learn rapidly.
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
- Primitive types / operators
- 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
- IO
- Functions
- 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:
<source lang="powershell">
- 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 </source