转并学习:powershell 命令五味(别名列表,文件操作……)

来源:互联网 发布:淘宝 商品 模板 编辑:程序博客网 时间:2024/05/05 14:42

转自:http://www.cnblogs.com/Icebird/archive/2008/02/11/powershellstudy.html

#别名ac = Add-Contentasnp = Add-PSSnapinclc = Clear-Contentcli = Clear-Itemclp = Clear-ItemPropertyclv = Clear-Variablecpi = Copy-Itemcpp = Copy-ItemPropertycvpa = Convert-Pathdiff = Compare-Objectepal = Export-Aliasepcsv = Export-Csvfc = Format-Customfl = Format-Listforeach = ForEach-Object% = ForEach-Objectft = Format-Tablefw = Format-Widegal = Get-Aliasgc = Get-Contentgci = Get-ChildItemgcm = Get-Commandgdr = Get-PSDriveghy = Get-Historygi = Get-Itemgl = Get-Locationgm = Get-Membergp = Get-ItemPropertygps = Get-Processgroup = Group-Objectgsv = Get-Servicegsnp = Get-PSSnapingu = Get-Uniquegv = Get-Variablegwmi = Get-WmiObjectiex = Invoke-Expressionihy = Invoke-Historyii = Invoke-Itemipal = Import-Aliasipcsv = Import-Csvmi = Move-Itemmp = Move-ItemPropertynal = New-Aliasndr = New-PSDriveni = New-Itemnv = New-Variableoh = Out-Hostrdr = Remove-PSDriveri = Remove-Itemrni = Rename-Itemrnp = Rename-ItemPropertyrp = Remove-ItemPropertyrsnp = Remove-PSSnapinrv = Remove-Variablervpa = Resolve-Pathsal = Set-Aliassasv = Start-Servicesc = Set-Contentselect = Select-Objectsi = Set-Itemsl = Set-Locationsleep = Start-Sleepsort = Sort-Objectsp = Set-ItemPropertyspps = Stop-Processspsv = Stop-Servicesv = Set-Variabletee = Tee-Objectwhere = Where-Object? = Where-Objectwrite = Write-Outputcat = Get-Contentcd = Set-Locationclear = Clear-Hostcp = Copy-Itemh = Get-Historyhistory = Get-Historykill = Stop-Processlp = Out-Printerls = Get-ChildItemmount = New-PSDrivemv = Move-Itempopd = Pop-Locationps = Get-Processpushd = Push-Locationpwd = Get-Locationr = Invoke-Historyrm = Remove-Itemrmdir = Remove-Itemecho = Write-Outputcls = Clear-Hostchdir = Set-Locationcopy = Copy-Itemdel = Remove-Itemdir = Get-ChildItemerase = Remove-Itemmove = Move-Itemrd = Remove-Itemren = Rename-Itemset = Set-Variabletype = Get-Content#PSDrivealiascertenvfunctionhkcuhklmvariable#获取帮助help get*help *processhelp dirhelp dir -fullhelp dir -detailedhelp dir -exampledir -?#转义序列   `0      //空值   `a      //Beep   `b      //退格   `f      //换页   `n      //新行   `r      //回车   `t      //制表符   `v      //垂直引号   ``      // "`"#数字常量   1kb     // 1024   1mb   1gb   1e3     // 1000   0xFFFF  // 65535#编辑脚本,推荐使用PrimalScript的最新版本,非常强大#设置脚本安全策略set-executionpolicy Restricted#默认set-executionpolicy AllSigned#部署set-executionpolicy RemoteSigned#开发set-executionpolicy Unrestricted#不推荐#执行脚本必须带路径./myScript.ps1#获取基于用户名和密码的凭据对象$cert = get-credential#对脚本签名$cert = Get-PfxCertificate C:/Test/Mysign.pfxSet-AuthenticodeSignature myScript.ps1 -cert $cert#操作系统gwmi win32_operatingsystem#自动变量$Args #传递进函数的参数$_ #通过管道传入的对象$input  #通过管道传入的对象集合$$      #前一命令行的最后一个标记$?      #上一命令的布尔状态$^      #前一命令行的第一个标记$Matches #使用 –match 运算符找到的匹配项的哈希表$Error[0] #前一次错误$Home   #用户的主目录$Host   #引用宿主 POWERSHELL 语言的应用程序$LastExitCode #上一程序或脚本的退出代码$PSHome #Windows PowerShell 的安装位置$profile #标准配置文件(可能不存在)$StackTrace #Windows PowerShell 捕获的上一异常#类型   空类型       [void]    数值类型       [byte]        typeof(byte)        [decimal]     typeof(decimal)        [double]      typeof(double)        [float]       typeof(float)        [int]         typeof(int)        [long]        typeof(long)        [single]      typeof(float)    字符类型       [char]        typeof(char)        [string]      typeof(string)    布尔类型       [bool]        typeof(bool)    集合类型       [array]       typeof(System.Array)                      typeof(System.Object[])        [hashtable]   typeof(System.Collections.Hashtable)    其它       [psobject]    typeof(System.Management.Automation.PSObject)        [ref]         typeof(System.Management.Automation.PSReference)        [regex]       typeof(System.Text.RegularExpressions.Regex)        [scriptblock] typeof(System.Management.Automation.ScriptBlock)        [switch]      typeof(System.Management.Automation.SwitchParameter)        [type]        typeof(System.Type)        [wmi]         typeof(System.Management.ManagementObject)        [wmiclass]    typeof(System.Management.ManagementClass)        [wmisearcher] typeof(System.Management.ManagementObjectSearcher)        [xml]         typeof(System.Xml.XmlDocument)example:#[void][void] $var#可以阻止$var输出#[xml]$var = [xml] "onetwo3"$var.top$var.top.a$var.top.a = "13"#自定义函数function writeln([string] $str) { echo $str }function writeln([string] $str) { Begin {echo "Begin"} Process {echo $str} End {echo "End"} }function writeln { param ([string] $str = $(throw "missing parameter")); echo $str }${function:writeln} = { param ([string] $str = $(throw "missing parameter")); echo $str }#文本文件读写${C:/test.txt} = "Hello`r`n"${C:/test.txt} += "-----------------"$Line1 = ${C:/test.txt}[0]# $null$var = $null#删除$vardir > $null$null = dir#Invoke$method = "ToUpper""abc".$method.Invoke()#布尔值$true$false#where, select等的用法cd c:/dir | where {$_.Name -eq "WINDOWS"} | select Length,Namedir | ? {$_.Name -eq "WINDOWS"}# 列出字符串对象"str"的所有属性与方法"str" | gm#强制类型变量[Boolean] $condition = 0[string] $str = "hello"#数组$array = 1,2,3,4,5,6,7,8$array = @(1,2,3,4,5,6,7,8)$array[-1]#最后一个元素$array[0..4]$array[-1..-8]#倒序#哈希表$hash = @{"Name"="Icebird"; "Job"="Engineer"}#如何取得文本的行数(type C:/test.txt | measure-object).Count#从控制台读取一行输入$var = Read-Host#获取环境变量$path = $env:Path#读取注册表$a = (gp "hklm://Software/Microsoft/Windows/CurrentVersion").ProductId#比较和运算-like"file.doc" -like "file.*"-notlike-contains1,2,3 -contains 1-notcontains-----------------------------------eq= (忽略大小写)-ieq= (忽略大小写)-ceq= (不忽略大小写)-ne!=-gt>-lt<-ge>=-le<=以上操作符也可用于对数组操作:1,2,3,5,3,2 -lt 3-----------------------------------and-or-not!等价于-not-xor%模运算*可用于字符串重复: "-" * 80#位操作-band-bor-bnot-bxor#特殊操作$a = "Hat"$a -replace "a","o"$a -is [string]$a = 1 -as [string]$b = @(1..5)"{0:d}" -f (get-date)"{0:yyyy-MM-dd}" -f (get-date)#格式化$a = 123456789.456789$a.ToString("F4")"{0:F4}" -f $a"{0,-20:F4}{1}" -f $a,0"{0,20:F4}" -f $a"{0:x}" -f 100000"{0:X}" -f 100000#正则表达式$regex = [regex]"He"$str = "Hello, Hello"$isMatch = $str -match $regex$isMatch = $regex.ismatch($str)$matches = $regex.matches($str)#双引号与单引号$a = 1;"$a"会输出1'$a'会输出$a# & 与 ..{$var = 1}#看作include&{$var = 1}#看作call&"dir"#意味着函数名之类的可以当作参数传入#foreachforeach ($file in dir) { $file.Name }dir | % { $_.Name }#forfor ($i = 1; $i -lt 5; $i++) {echo $i}#while$i = 0while ($i -lt 4) { $i++; $i }#do...while$i = 10do {$i--; $i} while ($i -lt 5)#do...until$i = 10do {$i--; $i} until ($i -lt 5)#if...else[if]$obj = "Hello"if ($obj -is [string]) { "ISSTRING" }if ($obj -is [string]) { "ISSTRING" } else { "ISNOTSTRING" }if ($obj -is [string]) { "ISSTRING" } elseif ($obj -is [int]) { "ISINTEGER" }#switchswitch (1,2,3) { 1 {"a"} 2 {"b"} 3 {"c"} default {"?"} }switch (1) { "a" {"China"} "b" {"Japan"} "c" {"c"} default {"???"} }#switch -regex$var = "abcdefg"switch -regex($var) {"^/w+$" {echo $_" is a word"}"^/d+$" {echo $_" is a number"}"^/s+$" {echo $_" is a space"}default {echo "?"}}#switch -casesensitive#switch -wildcard#switch -extract?怎么用#switch -file?怎么用#抛出错误&捕获异常throw "Error"raised "Exception"trap{  write-host "Error: " $_.Exception.Message#$_.TargetObject#$_.CategoryInfo#$_.FullyQualifiedErrorID#$_.ErrorDetails#$_.InvocationInfo  continue#break#return}#输出格式化Format-ListFormat-TableFormat-WideFormat-Customdir | format-table -groupby Modedir | sort Name -descdir | sort Name -desc | select Name,Length,Mode | export-csv C:/dir.csvdir | sort Name -desc | select Name,Length,Mode | export-clixml C:/dir.csvdir | convertto-html#使用.NET的对象$webclient = New-Object System.Net.WebClient$webclient.Encoding = [System.Text.Encoding]::UTF8$url = "http://www.cnblogs.com/rss"$data = [string]$webclient.downloadstring($url)#使用COM对象$spVoice = new-object -com "SAPI.spvoice"$spVoice.Speak("Hello, I am Icebird.")