Windows PowerShell Language Quick Reference
2009-05-07 09:21
316 查看
Windows PowerShell Language Quick Reference
Native Support for Different Type Systems | ||||||||||||||||||||||||||||||||
Windows PowerShell adapts WMI, XML, ASDI, ADO, and COM objects to provide a common syntax to access their properties and methods. Example $g = Get-WmiObject Win32_Process $g[0].Name # instead of $g[0].Properties[“Name”] | ||||||||||||||||||||||||||||||||
Arithmetic Binary Operators | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
Array Operations | ||||||||||||||||||||||||||||||||
Does this array have a 3 in it 1,2,3,5,3,2 –contains 3 Return all elements equal to 3: 1,2,3,5,3,2 –eq 3 Return all elements less than 3: 1,2,3,5,3,2 –lt 3 Test if 2 exists in collection: if (1, 3, 5 –contains 2) … Other operators: -gt, -le, -ge, -ne | ||||||||||||||||||||||||||||||||
Arrays | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
Assignment Operators | ||||||||||||||||||||||||||||||||
=, +=, -=, *=, /=, %= | ||||||||||||||||||||||||||||||||
Associative Arrays (Hashtables) | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
Boolean Values and Operators | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
Break (Scripting) | ||||||||||||||||||||||||||||||||
The break commands exits a loop. It can take an optional LABEL to break to Example: while (1) { $a = something if ($a –eq 1) break; } | ||||||||||||||||||||||||||||||||
Command Expansion Operators | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
Comments | ||||||||||||||||||||||||||||||||
# This is a comment because # is the first char of a token $a = “#This is not a comment…” $a = “something” # …but this is. Write-Host Hello#world | ||||||||||||||||||||||||||||||||
Comparison Operators | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
Continue (Scripting) | ||||||||||||||||||||||||||||||||
The continue statement continues the next iteration of a loop without breaking out of it. Example: while (1) { $a = something if ($a –eq 1) (continue) # This line is not reached unless $a == 1 } # This line is never reached. | ||||||||||||||||||||||||||||||||
Dot Sourcing | ||||||||||||||||||||||||||||||||
Dot sourcing allows running functions, script blocks, and scripts in the current scope rather than a local one. Example: . MyFunction If MyFunction sets a variable, it is set in the current scope rather than the function’s local scope. $a = {$x = Get-Process | Select –First 2} . $a #Evaluates the script block in the current scope | ||||||||||||||||||||||||||||||||
Escape Sequences | ||||||||||||||||||||||||||||||||
The Windows PowerShell escape character is the backwards apostrophe, or `. To make a character literal, precede it with `. To specify a ` use ``.
| ||||||||||||||||||||||||||||||||
Execution Order | ||||||||||||||||||||||||||||||||
Windows PowerShell attempts to resolve commands in the following order: aliases, functions, cmdlets, scripts, executables, and normal files. | ||||||||||||||||||||||||||||||||
For (Scripting) | ||||||||||||||||||||||||||||||||
[:label] for ([initializer]; [condition]; [iterator]) {} Example: for ($i = 0; $i –lt 5; $i++) {Write-Object $i} | ||||||||||||||||||||||||||||||||
Foreach (Scripting) | ||||||||||||||||||||||||||||||||
[:label] foreach (identifier in collection) {} Expression | foreach {} Expression | foreach {BEGIN{} PROCESS{} END{}} Examples: $i = 1,2,3 foreach ($z in $i) {Write-Object $z} Get-Process |foreach {BEGIN{$x=1} PROCESS{$X++} END{“$X Processes”}} | ||||||||||||||||||||||||||||||||
Functions (Scripting) | ||||||||||||||||||||||||||||||||
function MyFunction { write-object $args[0] } function test ([string]$label=”default label”,[int]$start=0) { BEGIN {$x=$start} PROCESS {“$label: $_”’; $x++} END{“$x total”} } | ||||||||||||||||||||||||||||||||
Filters (Scripting) | ||||||||||||||||||||||||||||||||
Filters are a shorthand way of writing a function with a PROCESS script block. filter MyFilter { $_.name } | ||||||||||||||||||||||||||||||||
If/elseif/else (Scripting) | ||||||||||||||||||||||||||||||||
if (condition) {…} elseif (condition) {…} else {…} On the command line, the closing brace must be on the same line as elseif and else. This restriction does not apply to scripts | ||||||||||||||||||||||||||||||||
Invoke Operator | ||||||||||||||||||||||||||||||||
The & operator can be used to invoke a script block or the name of a command or function. Example: $a = “Get-Process” &$a $a = { Get-Process | Select -First 2 } &$a | ||||||||||||||||||||||||||||||||
Logical Operators | ||||||||||||||||||||||||||||||||
!, -not, -and, -or | ||||||||||||||||||||||||||||||||
Method Calls | ||||||||||||||||||||||||||||||||
Methods can be called on objects. Examples: $a = “This is a string” $a.ToUpper() $a.SubString(0,3) $a.SubString(0,($a.length/2)) $a.Substring(($a.length/2), ($a.length/3)) Static Methods are callable with the “::” operator [DateTime]::IsLeapYear(2005) | ||||||||||||||||||||||||||||||||
Windows PowerShell Automatic Variables (Not Exhaustive) | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
Object Properties | ||||||||||||||||||||||||||||||||
An object’s properties can be referenced directly with the “.” operator. $a = Get-Date $a.Date $a.TimeOfDay.Hours Static properties can be referenced with the “::” operator [DateTime]::Now | ||||||||||||||||||||||||||||||||
Operator Precedence | ||||||||||||||||||||||||||||||||
In Windows PowerShell, operators are evaluated in the following precedence: () {}, @ $, !, [ ], ., &, ++ --, Unary + -, * / %, Binary + -, Comparison Operators, -and –or, |, > >>, = | ||||||||||||||||||||||||||||||||
Other Operators | ||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||
Return (Scripting) | ||||||||||||||||||||||||||||||||
The return command exits the current script or function and returns a value. Example: function foo { return 1 } | ||||||||||||||||||||||||||||||||
Scopes (Scripting) | ||||||||||||||||||||||||||||||||
Variables and other data elements may be instantiated in different scopes: · Variables in the global scope are visible in all scopes. · Variables in the script scope are visible to all scopes within that script file. · Variables in the local scope are visible only in the current scope and its children. · Private scope variables are visible only to that current scope. A scope is created in the body of a shell function (see function creation) Example: $global:a = 4 $script:a = 5 $local:a = 3 $private:a = 6 | ||||||||||||||||||||||||||||||||
Script Blocks | ||||||||||||||||||||||||||||||||
Commands and expressions can be stored in a script block object and executed later. Example: $block = {Get-Process; $a=1} &$block | ||||||||||||||||||||||||||||||||
Scripts | ||||||||||||||||||||||||||||||||
Windows PowerShell commands can be stored in and executed from script files. The file extension for Windows PowerShell scripts is “.ps1”. Parameters can be passed to a script and a script can return a value. Example: $sum = MyAdder.ps1 1 2 3 | ||||||||||||||||||||||||||||||||
Strings | ||||||||||||||||||||||||||||||||
String constants: “this is a string, this $variable is expanded as is $(2+2)” ‘this is a string, this $variable is not expanded’ @” This is a “here string” which can contain anything including carriage returns and quotes. Exressions $(2+2) are evaluated ”@ @’ “here string” with single quotes do not evaluate expressions. ‘@
| ||||||||||||||||||||||||||||||||
Switch (Scripting) | ||||||||||||||||||||||||||||||||
The variable $_ is available in the script. $_ represents the current value being evaluated. If an array is used in switch, each element of the array is tested. Example: $var = "word1","word2","word3" switch -regex ($var) { "word1" {"Multi-match Exact " + $_ } "word2" {"Multi-match Exact " + $_ } "w.*2" {"Pattern match Exact " + $_ } default {"Multi-match Default " + $_ } } Output: Multi-match Exact word1 Multi-match Exact word2 Pattern match Exact word2 Multi-match Default word3 | ||||||||||||||||||||||||||||||||
Throw | ||||||||||||||||||||||||||||||||
Throw provides the same functionality for scripts as the ThrowTerminatingError API does for cmdlets. throw "Danger, Danger" Danger, Danger At line:1 char:6 + throw <<<< "Danger, Danger" Throw takes a string, exception, or ErrorRecord as an argument. | ||||||||||||||||||||||||||||||||
Traps | ||||||||||||||||||||||||||||||||
Trap [ExceptionType] { if (…) { continue # continue at the script statement after the one that cased the # trap; $? is updated but no error record is generated } else (…) { Break # rethrow the exception } # Doing nothing will do what is specified in the # $ErrorActionPreference setting } | ||||||||||||||||||||||||||||||||
Type Operations (Scripting) | ||||||||||||||||||||||||||||||||
-is IS type (e.g. $a -is [int] ) -as convert to type (e.g. 1 -as [string] treats 1 as a string ) | ||||||||||||||||||||||||||||||||
Until (Scripting) | ||||||||||||||||||||||||||||||||
do { … } until (condition) | ||||||||||||||||||||||||||||||||
Variables | ||||||||||||||||||||||||||||||||
Format: $[scope:]name or ${anyname} or ${any path} Examples: $a = 1 ${!@#$%^&*()}=3 $global:a = 1 # Visible everywhere $local:a = 1 # defined in this scope and visible to children $private:a=1 # same as local but invisible to child scopes $script:a=1 # visible to everything in this script $env:path = “d:\windows” ${C:\TEMP\testfile.txt}=”This writes to a file” Get-Variable –scope 1 a #Gets value from the parent scope Get-Variable –scope 2 a # grandparent | ||||||||||||||||||||||||||||||||
While (Scripting) | ||||||||||||||||||||||||||||||||
[:label] while (condition) { … } do { … } while (condition) | ||||||||||||||||||||||||||||||||
Parsing | ||||||||||||||||||||||||||||||||
Windows PowerShell parses in two modes—command mode and expression mode. In expression mode, Windows PowerShell parses as most high-level languages parse: numbers are numbers; strings need to be quoted, and so on. Expressions are things such as: 2+2 4 "Hello" + " world" Hello world $a = "hi" $a.length * 13 26 When parsing in command mode, strings do not need to be quoted and everything is treated like a string except variables and things in parentheses. For example: copy users.txt accounts.txt users.txt and accounts.txt are treated as strings write-host 2+2 2+2 is treated as string, not an expression to evaluate copy $src $dest $src and $dest are variables. Not needing to use quotation marks when working in a command shell can be very beneficial in the long run because it greatly reduces the amount of typing required. The parsing mode is determined by the first token encountered. If the token is a number, variable, or quoted string, then the shell parses in expression mode. If the line starts with a letter, an & (ampersand), or a . (dot) followed by a space or a letter, the parsing is done in command mode.
Write-Host (2+2) 2+2 is treated as an expression to evaluate and is passed to the Write-Host command. (Get-Date).day + 2 Get-Date is treated as a command, and the result of executing it becomes the left value in the expression. You can nest commands and expressions without restrictions. Write-Host ((Get-Date).day + 2) Get-Date is a command. ((Get-Date).day+2) is an expression, and Write-Host ((Get-Date).day + 2) is a command again. Write-Host ((Get-Date) - (Get-Date).date) The Get-Date command is used twice to determine how much time has passed since midnight (condition). |
相关文章推荐
- Windows Vista in a Nutshell: A Desktop Quick Reference
- Windows PowerShell Pocket Reference: Pocket Reference
- LotusScript Language Quick-reference
- Windows Vista For Dummies Quick Reference
- Windows上Python安装及Powershell使用
- XPath Functions Quick Reference
- Microsoft Windows Forms QuickStarts Tutorial - Building Applications
- PowerShell 2.0之使用WMI管理Windows(三)对WMI对象的语言支持
- PowerShell 2.0之使用WMI管理Windows(三)获取软硬件信息
- PowerShell 2.0之使用WMI管理Windows(五)生成WMI代码
- Language Reference >> Predefined Interfaces and Classes >> Generator
- [Reference] Windows Installer XML (WiX) 3.0 Snippets
- PowerShell2.0之Windows排错(一)启动故障排错
- volcanol_Windows_Powershell_汇总贴
- Powershell 5.1 脚本化配置 Windows 2016 & SQL Server 2016 无域 AlwaysOn AG
- PowerShell2.0之Windows排错(五)查看硬件问题
- PowerShell 查找删除Windows补丁文件
- Windows任务计划创建计划,定时执行PowerShell命令
- 通过PowerShell获取Windows系统密码Hash 推荐
- What Can I Do With Windows PowerShell?