定义一个函数:function test {notepad.exe c:\test.txt}
Write cmdlet:主要用于输出调试信息,输出错误对象,输出进度条等。
例:输出信息,黑底红字
Write-host -foregroundcolor red -backgroundcolor black “mynameiszgk”
例:输出进度条
for ($i = 0; $i -lt 100; $i++) { Write-Progress -Activity "Learning PowerShell" -Status "Percentage: $i" -PercentComplete $i; Start-Sleep -Milliseconds 50 }
#-activity “Learning PowerShell” 进度条名称
#-status 整个过程中当前的状态
#-PercentComplete $i进度条具体执行过程
# Start-Sleep -Milliseconds 50 50毫秒延迟
。about_alias.help命令
help *-alias:获得所有关于alias的命令
get-alias:获得所有别名与真实命令对应的列表。例get-alias r* 获得以r开头的alias
get-alias | where-object {$_.definition –eq “remove-item”}:获得remove-item cmdlet对应的所
有别名
alias: :代表别名驱动器
set-location alias: :进入别名驱动器,之后可以用get-childitem查看alias:下的内容,可以用get-childitem –path alias: 代替上述操作。Get-childitem –path alias:r*表示获得以r打头的别名
get-alias | get-member:获得alias的属性和方法,例get-alias –name zgk | get-member –membertype property (method)表示获得别名为zgk的属性(或方法)
set-alias:设置或修改别名,例set-alias –name zgk –value get-childitem,该命令可用new-alias代替,即new-alias –name zgk –value get-childitem,注意,如果不写-name和-value参数,也可以新建立alias,不出错,但不能正确执行。
可以为cmdlet,function,script,file,executable file建立文件,但不能为带参数的cmdlet建立alias,例不能为get-eventlog -logname application建立alias,可建立函数来表示它,function viewlog {get-eventlog –logname application}再运行viewlog来查看结果。可通过help about_function来了解function。
set-alias -name zgknote -value “c:\windows\nontpad.exe” 为notepad.exe 建立别名。
help get-alias –detail(detailed) -full -examples :获得get-alias cmdlet的详细帮助,这些参数是通用参数,适用于其它的cmdlet,以后不在赘述。
new-alias -name zgkps1 -value “c:\test.ps1” :为test.ps1建立alias。
。about_arithmetic_operators.help
precedence(优先级) :1(for a negative number);2* / %3+ -(for subtraction)。其中/是除法;%是取模,例8%3,结果是2。
Help about_assignment_operators :获得关于operators的帮助
。about_assignment_operators.help
包括:= += -= *= /= %=
$a=2;$a=”I”,”and””you”:常规赋值方法。
$a=3.257e3:指数赋值;$a=10kb会被自动转换成bytes。
$a+=1相当于$a=($a+1);$a-=1相当于$a=($a-1)
$a=1,2,3则$a[2]-=1相当于最后一个元素减1,$a的值由1,2,3变成1,2,2
$a=6,则$a+=”3”后$a值为9。
$a=”6”,则$a+=3后$a值为”63”
[string]$a=27相当于$a=[string]27
[string[]]$a=”a”,”b”,”c”
[system.datetime]$a=”1/30/2000}
$varA,$varB,$varC=1,2,3则$varA=1, $varB=2, $varC=1,按照1对1原则。
$varD=1,2,3,则$varA,$varB,$varc=$varD,则$varA=1;$varB=2;$varC=3,还是1对1原则。
$varA=$varB=$varc=$varD,则它们的值都是1,2,3
$varA,$varB,$varC=1,2,3,4,5则$varA=1, $varB=2, $varC=3,4,5。注意,如果值比变量个数多,原则还是1对1,多出来的值全部赋值给最后1个变量。
Set-variable -name varA -value 1,2,3:还可以使用set-variable命令为变量赋值。
$a=@{one=1;two=2;three=3}:$a是1个数组,值是1,2,3。并且每个值都对应1个Key,$a.one对应的是1,依次类推,语法是<array>.<key>。
注意:在PowrShell输入十六进制会被自动转换成十进制。
-=和/= assignment operators不能用于“字符串变量”
。about_array.help
数组是一个数据结构,频繁的读写数组会使脚本执行缓慢。
$zgk=1,2,3,4,5,6,7,8,9和$zgk=1..9 是定义数组的2种方法
$zgk或$zgk[2]:读取$zgk的所有元素或读取第3个element。如果数组有5个elements,它的索引长度是4,即$zgk[0]到$zgk[4]。
$zgk[0..8]:按顺序从$zgk[0]到$zgk[8]读取$zgk的值, 分别是1,2..7,8,9
$zgk[-1..-9]: 按降序从$zgk[-1]到$zgk[-9]读取$zgk的值,分别是9,8,7..2,1
$zgk[-9..-1]: 按升序从$zgk[-9]到$zgk[-1]读取$zgk的值,分别是1,2..7,8,9
$zgk[0,2+4..6]:分别显示$z[0], $z[2], $z[4], $z[5], $z[6],分别是1,3,5,6,7
$zgk[0..($zgk.length-1)]:相当于$zgk[0..8]
Foreach ($element in $zgk) {$element}:用foreach显示$zgk中的每1个元素,注意第1个是圆括号( ),第2个是花括号{ }
For ($i=0;$i –le ($zgk.length-1);$i+=2) {$zgk[$i]} :用for读取数组的第1,3,5,7,9个元素。注意别忘了为$i赋初始值。
$i=0;while ($i –le ($zgk.length-1)) {$zgk[$i];$i++}:用while读取数组$zgk的所有元素。
$zgk.gettype()如果不知道数组类型,可通过gettype()方法查看。
[ini32[]]$zgk=100,200,300:创建包含3个整数的32-bit的integar array(整形数组)。
[diagnostics.process[]]$zgk=get-process:创建一个支持.NET Framework的任意类型
Get-member -inputobject $zgk:利用-inputobject获取$zgk的所有属性和方法。
$zgk[0]=100:将$zgk的第1个数组的值由1改为100。
$zgk.setvalue(200,1):利用setvalue() 方法将第1个数组的值由100改为200。
$zgk +=300:在数组末段添加一个新的元素300。则$zgk现在是1,200,3,..7,8,9,300
两个数组合并:$a=1,2;$b=3,4则$c=$a+$b,所有$c的数组成员是1,2,3,4.
删掉1个数组(把数组当作1个变量):remove-item variable:zgk,记住不用写$了。
获得有关array信息命令:help about_associative_array;help about_assignment_operators;help about_operator;help about_for;help about_foreach;help about_while。
2009-2-24补(马涛)
可以把某个命令的值赋给变量,在以数组的方式读取,很有意思:
$test=dir ; $test[4]
。about_associative_array.help
所谓associative array,可以把它理解为key与value对应的数组。
语法:$<array name>=@{<key1>=value1;<key2>=value2;...}。注意associative array是以@为标记的。例$a=@{"zhangsan"="1/2/2007";"lishi"="1/30/2007";"wangwu"="1/25/2007"},key和value尽量用单或双引号隔离。
$a.”zhangsan”相当于$a[“zhangsan”]都是读取key为zhangsan对应的value。
$a.gettype()表示获得$a的类型。
$a.”zhangsan”.gettype()相当于$a[”zhangsan”].gettype()都是获取key为zhangsan的类型。
$a=@{"zhangsan"="1/2/2007";"lishi"=0459;"wangwu"=get-process}当然可以在1个$a下为key赋不同类型的value。
。about_automatic_variables.help
所谓automatic_variables就是系统定义好了的变量,可以直接使用。
$$` Contains the last token of the last line received by the shell.
$? Contains True if last operation succeeded and False otherwise.
$^ Contains the first token of the last line received by the shell.
$_ Contains the current pipeline object, used in script blocks, filters, and the where statement.
$Args Contains an array of the parameters passed to a function.
$DebugPreference Specifies the action to take when data is written using Write-Debug in a script or WriteDebug in a cmdlet or provider.
$Error Contains objects for which an error occurred while being processed in a cmdlet.
$ErrorActionPreference Specifies the action to take when data is written using Write-Error in a script or WriteError in a cmdlet or provider.
$foreach Refers to the enumerator in a foreach loop.
$Home Specifies the user's home directory. Equivalent of %homedrive%%homepath%.
$Input Use in script blocks that are in the middle of a pipeline.
$LASTEXITCODE Contains the exit code of the last Win32 executable execution.
$MaximumAliasCount Contains the maximum number of aliases available to the session.
$MaximumDriveCount Contains the maximum number of drives available, excluding those provided by the underlying operating system.
$MaximumFunctionCount Contains the maximum number of functions available to the session.
$MaximumHistoryCount Specifies the maximum number of entries saved in the command history.
$MaximumVariableCount Contains the maximum number of variables available to the session.
$PsHome The directory where the Windows PowerShell is installed.
$Host Contains information about the current host.
$OFS Output Field Separator, used when converting an array to a string. By default, this is set to the space character. The following example illustrates the default setting and setting OFS to a different value:
$ReportErrorShowExceptionClass When set to TRUE, shows the class names of displayed exceptions.
$ReportErrorShowInnerException When set to TRUE, shows the chain of inner exceptions. The display of each exception is governed by the same options as the root Exception, that is, the options dictated by $ReportErrorShow* will be used to display each exception.
$ReportErrorShowSource When set to TRUE, shows the assembly names of displayed exceptions.
$ReportErrorShowStackTrace When set to TRUE, emits the stack traces of exceptions.
$ShouldProcessPreference Specifies the action to take when ShouldProcess is used in a cmdlet.
$ShouldProcessReturnPreference Value returned by ShouldPolicy
$StackTrace Contains detailed stack trace information about the last error.
$VerbosePreference Specifies the action to take when data is written using Write-Verbose in a script or WriteVerbose in a cmdlet or provider.
$WarningPreference Specifies the action to take when data is written using Write-Warning in a script or WriteWarning in a cmdlet or provider.
。about_break.help
代码段1:
$loveword="i love you yhh"
$num=0
$varB=10,20,30,40
foreach ($vaL in $varB)
{
$num++
if ($vaL -eq 30)
{
break
}
Write-Host "当到$var1=30时,屏幕输出$num 次 $loveword"
}
注意:该代码段中的foreach不能用for代替
代码段2:
for ($i=0;$i –le 9;$i++)
{
Write-host “$i”
Break
}
代码段3:
。about_command_search.help
在PowerShell下执行任何命令都必须指明详细的路径,否则将在当前目录下寻找匹配的alias,fucntion或在默认的环境变量路径下寻找匹配的命令,找不到则提示命令不被识别。
。about_command_syntax.help
单个命令语法:<command_name> [parameter]…
多个命令应用:<command_name>[parameter]… | <command_name> [parameter]…
有一种参数被称做“positional parameter”(位置参数),可omit(省略),例:get-childitem –path c:\test,其中-path就是positional parameter,可改写为get-childitem c:\test。
。about_commonparameters.help
commonparameters(通用参数):所有命令都支持的参数是commonparameters,在一些命令中执行commonparameters可能没有什么效果。
Parameter Description
Verbose Boolean. Generates detailed information about the operation, much like tracing or a transaction log. This parameter is effective only in cmdlets that generate verbose data.
Debug Boolean. Generates programmer-level detail about the operation. This parameter is effective only in cmdlets that generate debug data.
ErrorAction Enum. Determines how the cmdlet responds when an error occurs. Values are: Continue [default], Stop, SilentlyContinue, Inquire.
ErrorVariable String. Specifies a variable that stores errors from the command during processing. This variable is populated in addition to $error.
OutVariable String. Specifies a variable that stores output from the command during processing.
OutBuffer Int32. Determines the number of objects to buffer before calling the next cmdlet in the pipeline.
WhatIf Boolean. Explains what will happen if the command is executed, without actually executing the command.
Confirm Boolean. Prompts the user for permission before performing any action that modifies the system.
其中,WhatIf非常有用,它的目的是预览命令的执行效果而不是命令真正执行。
。about_comparison_operators.help
Operator Description Example t/f
-eq equals 10 -eq 10 true
-ne not equal 10 -ne 10 false
-gt greater than 10 -gt 10 false
-ge greater than or equal to 10 -ge 10 true
-lt less than 10 -lt 10 false
-le less than or equal to 10 -le 10 true
-like wildcard comparison "one" -like "o*" true
-notlike wildcard comparison "one" -notlike "o*" false
-match regular expression comparison "book" -match "[iou]" true
-notmatch regular expression comparison "book" -notmatch "[iou]" false
例:if ($varA -gt $varB)
{
Write-Host "Condition evaluates to true."
}
else
{
Write-Host "Condition evaluates to false."
}
还包括RANGE OPERATOR(范围操作符号),用 .. 表示
例:foreach($varA in 1..$varB)
{
Write-Host $varA
}
还包括REPLACE OPERATOR(替代操作符)
Operator Case Example Results
-replace case insensitive "book" -replace "B", "C" Cook
-ireplace case insensitive "book" -ireplace "B", "C" Cook
-creplace case sensitive "book" -creplace "B", "C" book
还包括bitwise operators(逐位操作符)---没读懂????
Operator Description Example Results
-band bitwise and 10 -band 3 2
-bor bitwise or 10 -bor 3 11
还包括type operators(类型操作符)
Operator Description Example Results
-is Is of a specified type $true -is [bool] true
-is Is of a specified type 32 -is [int] true
-is Is of a specified type 32 -is [double] false
-isnot Is not of a specified type $true -isnot [bool] false
还有 I 和 c 在操作符中的使用。
例:”a” –eq “A” 不区分大小写,结果是:true 。
例:”a” –ieq “A” 注意加了字母i,还是不区分大小写,结果是:true 。
例:”a” –ceq “A” 注意加了字母c,此时是区分大小写,结果是:false 。
除了i和c外,其它的字母就不能用了。还有,请参考replace operators表中i和c加强理解。记住,它们都是对大写字母操作,如表中例子改成 ”book” –creplace “b”,”c”,就执行替换,结果为: cook,将”b”,”c”换成”B”,”C”,就不执行替换了。
。about_continue.help
Continue:它的作用就是返回到顶部。
例:while ($num –lt 10)
{
$num +=1
if ($num -eq 5) {continue}
write-host $num
}
执行结果:从1到10只有5没有输出其它数字均输出。
切记:在for循环语句中,不要将continue写在循环语句的首行。如果for 循环中的参数检测到在for语句中有值发生改变,将导致infinite loop(死循环或无限循环)。
。about_core_commands.help
所有的powershell core_command(内核命令)都与数据存储有联系。
以下是core_commands list
ChildItem CMDLETS
• Get-ChildItem