转自:http://lovephoenix.javaeye.com/blog/661380 对 powershell 做下总结 启动 powershell #字符串操作 对象操作 "hello".Length #进程操作 PS C:/> notepad PS C:/> $process=get-process notepad PS C:/> $process.Kill() #默认对象操作 PS C:/> 40GB/650MB 63.0153846153846 #时间操作 PS C:/> [DateTime]"2009-12-5" - [DateTime]::Now Days : -58 Hours : -14 Minutes : -53 Seconds : -58 Milliseconds : -510 Ticks : -50648385105314 TotalDays : -58.6208160941134 TotalHours : -1406.89958625872 TotalMinutes : -84413.9751755233 TotalSeconds : -5064838.5105314 TotalMilliseconds : -5064838510.5314 #时间对象操作 PS C:/> $result = [DateTime]"2009-12-5" - [DateTime]::Now PS C:/> $result.TotalDays -58.6213450248299 #查询今天星期几 PS C:/Users/vv> $date=Get-Date PS C:/Users/vv> $date.DayOfWeek Monday #查找powershell命令中包含单词process的命令 PS C:/> Get-Command *process* CommandType Name Definition ----------- ---- ---------- Application api-ms-win-core-processenvir... C:/Windows/system32/api-ms-w... Application api-ms-win-core-processthrea... C:/Windows/system32/api-ms-w... Cmdlet Debug-Process Debug-Process [-Name] <Strin... Cmdlet Get-Process Get-Process [[-Name] <String... Application microsoft-windows-kernel-pro... C:/Windows/system32/microsof... Application qprocess.exe C:/Windows/system32/qprocess... Cmdlet Start-Process Start-Process [-FilePath] <S... Cmdlet Stop-Process Stop-Process [-Id] <Int32[]>... Cmdlet Wait-Process Wait-Process [-Name] <String... #检索donet中对象的属性和方法 PS C:/> "aaa" | Get-Member TypeName: System.String Name MemberType Definition ---- ---------- ---------- Clone Method System.Object Clone() CompareTo Method int CompareTo(System.Object value), i... Contains Method bool Contains(string value) CopyTo Method System.Void CopyTo(int sourceIndex, c... EndsWith Method bool EndsWith(string value), bool End... Equals Method bool Equals(System.Object obj), bool ... GetEnumerator Method System.CharEnumerator GetEnumerator() GetHashCode Method int GetHashCode() GetType Method type GetType() GetTypeCode Method System.TypeCode GetTypeCode() IndexOf Method int IndexOf(char value), int IndexOf(... IndexOfAny Method int IndexOfAny(char[] anyOf), int Ind... Insert Method string Insert(int startIndex, string ... IsNormalized Method bool IsNormalized(), bool IsNormalize... LastIndexOf Method int LastIndexOf(char value), int Last... LastIndexOfAny Method int LastIndexOfAny(char[] anyOf), int... ... #统计所有正在运行的进程的句柄数 PS C:/> $handleCount=0 PS C:/> foreach($process in Get-process) { $handleCount +=$process.Handles } PS C:/> $handleCount 23318 #直接调用donet对象,获取网页内容 PS C:/> $webClient = New-Object System.Net.WebClient PS C:/> $content = $webClient.DownloadString("http://www.baidu.com") PS C:/> $content.Substring(0,1000) <html><head><meta http-equiv=Content-Type content="text/html;charset=gb2312"><t itle>百度一下,你就知道 </title><style>body{margin:4px 0}p{margin:0;paddin g:0}img{border:0}td,p,#u{font-size:12px}#b,#u,#l td,a{font-family:arial}#kw{fon t:16px Verdana;height:1.78em;padding-top:2px}#b{height:30px;padding-top:4px}#b, #b a{color:#77c}#u{padding-right:10px;line-height:19px;text-align:right;margin: 0 0 3px !important;margin:0 0 10px}#sb{height:2em;width:5.6em}#km{height:50px}# l{margin:0 0 5px 38px}#l td{padding-left:107px}p,table{width:650px;border:0}#l td,#sb,#km{font-size:14px}#l a,#l b{margin-right:1.14em}a{color:#00c}a:active{c olor:#f60}#hp{position:absolute;margin-left:6px}#lg{margin:-26px 0 -44px}#lk{wi dth:auto;line-height:18px;vertical-align:top}form{position:relative;z-index:9}< /style></head> <body><div id=u><a href=http://passport.baidu.com/?login&tpl=mn>登录</a></div>< center><img src=http://www.baidu.com/img/baidu_logo.gif width=270 height=129 us emap="#mp" id=lg><br><br><br><br><table cellpadd #获取系统信息 PS C:/> Get-WmiObject Win32_Bios SMBIOSBIOSVersion : 2TKT00AUS Manufacturer : LENOVO Name : Default System BIOS SerialNumber : 1111111 Version : LENOVO - 5000821 #导航文件系统 PS C:/> Set-Location c:/ PS C:/> Get-ChildItem 目录: C:/ Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 2010/1/7 14:20 bea d---- 2010/1/7 14:20 BEA WebLogic E-Business Platform d---- 2009/12/7 13:02 dzh d---- 2010/1/2 15:48 his d---- 2009/7/14 10:37 PerfLogs d-r-- 2010/1/25 12:58 Program Files d-r-- 2009/12/31 19:11 Users d---- 2009/11/7 9:52 usr d---- 2010/1/28 3:16 Windows -a--- 2009/6/11 5:42 24 autoexec.bat -a--- 2009/6/11 5:42 10 config.sys -a--- 2009/10/28 13:37 454656 putty.exe #导航注册表 PS C:/> Set-Location HKCU:/Software/Microsoft/Windows/ PS HKCU:/Software/Microsoft/Windows/> Get-ChildItem Hive: HKEY_CURRENT_USER/Software/Microsoft/Windows SKC VC Name Property --- -- ---- -------- 33 0 CurrentVersion {} 0 11 DWM {Composition, CompositionPolicy, Colo... 3 0 Shell {} 1 0 ShellNoRoam {} 2 0 TabletPC {} 3 12 Windows Error Reporting {ConfigureArchive, DisableArchive, Di... #导航证书 PS C:/Users/vv> Set-Location cert:/CurrentUser/Root PS cert:/CurrentUser/Root> Get-ChildItem 目录: Microsoft.PowerShell.Security/Certificate::CurrentUser/Root Thumbprint Subject ---------- ------- CDD4EEAE6000AC7F40C3802C171E30148030C072 CN=Microsoft Root Certificate Auth... BE36A4562FB2EE05DBB3D32323ADF445084ED656 CN=Thawte Timestamping CA, OU=Thaw... A7217F919843199C958C128449DD52D2723B0A8A CN=Alibaba.com Corporation Root CA... A43489159A520F0D93D032CCAF37E7FE20A8B419 CN=Microsoft Root Authority, OU=Mi... 7F88CD7223F3C813818C994614A89C99FA3B5247 CN=Microsoft Authenticode(tm) Root... 742C3192E607E424EB4549542BE1BBC53E6174E2 OU=Class 3 Public Primary Certific... 654E9FADD2032AE1B87D6263AF04FD7FEE38D57C CN=iTruschina CN Root CA-3, OU=Chi... 46F168AF009C28C18F452EB85F5E8747892B3C8B CN=iTruschina CN Root CA-2, OU=Chi... 245C97DF7514E7CF2DF8BE72AE957B9E04741E85 OU=Copyright (c) 1997 Microsoft Co... 240A61A2577970625B9F0B81283C4AA4037217B1 CN=iTruschina CN Root CA-1, OU=Chi... 18F7C1FCC3090203FD5BAA2F861A754976C8DD25 OU="NO LIABILITY ACCEPTED, (c)97 V... #显示所有进程 PS C:/Users/vv> Get-Process Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 527 28 40784 44864 243 18.94 4956 360SE 537 29 49144 59340 248 9.09 5276 360SE 924 20 17580 2504 132 3768 360tray 160 5 16080 7852 41 2036 audiodg 318 24 6524 7008 124 188 CCProxy 56 5 796 288 33 1232 CNAB4RPK 61 4 1568 6916 63 0.19 5064 conhost 60 4 1532 3628 63 0.06 5584 conhost 645 6 2076 1204 72 380 csrss 649 9 8148 11056 185 440 csrss ...... #搜索所有包含Get动词的命令 PS C:/Users/vv> Get-Command -Verb Get CommandType Name Definition ----------- ---- ---------- Cmdlet Get-Acl Get-Acl [[-Path] <String[]>]... Cmdlet Get-Alias Get-Alias [[-Name] <String[]... Cmdlet Get-AuthenticodeSignature Get-AuthenticodeSignature [-... Cmdlet Get-ChildItem Get-ChildItem [[-Path] <Stri... Cmdlet Get-Command Get-Command [[-ArgumentList]... Cmdlet Get-ComputerRestorePoint Get-ComputerRestorePoint [[-... ...... #帮助 PS C:/Users/vv> Get-Help Get-Verb -Full/-Detailed/-Examples #调用powershell脚本 PowerShell "& 'C:/get-report.ps1' arguments" #循环 PS C:/Users/vv> 1..10 | % {"aaa"} aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa #数据加密(Base64) PS C:/Users/vv> $bytes=[System.Text.Encoding]::Unicode.GetBytes("aaa") PS C:/Users/vv> $encodedString=[Convert]::ToBase64String($bytes) PS C:/Users/vv> $encodedString YQBhAGEA #检查命令是否执行成功 PS C:/Users/vv> $lastExitCode 0 PS C:/Users/vv> $? True #性能测试,计算一个命令执行的时间 PS C:/Users/vv> Measure-Command { Start-Sleep -Milliseconds 337 } Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 340 Ticks : 3404713 TotalDays : 3.9406400462963E-06 TotalHours : 9.45753611111111E-05 TotalMinutes : 0.00567452166666667 TotalSeconds : 0.3404713 TotalMilliseconds : 340.4713 #foreach 循环 foreach($alias in Get-Alias){ $alias } #显示为表格 PS C:/Users/vv> Get-Process | Format-Table Name,WS -Auto #复制文件 Copy-Item c:/temp/*.txt c:/temp/backup/ -verbose #列出所有已经停止的服务 PS C:/Users/vv> Get-Service | Where-Object { $_.Status -eq "Stopped" } #列出当前位置的所有子目录 PS C:/Users/vv> Get-ChildItem | Where-Object { $_.PsIsContainer } #循环 PS C:/Users/vv> 1..10 | Foreach-Object { $_ * 2 } #获取正在运行的记事本程序的进程列表,然后等待他们退出 PS C:/Users/vv> $notepadProcesses = Get-Process notepad PS C:/Users/vv> $notepadProcesses | Foreach-Object { $_.WaitForExit() } #其它循环关键字 for foreach do while #从管道中选择接收值 PS C:/Users/vv> dir | Select Name #释放变量占用的内存空间 $processes = $null #显示所有变量 PS C:/> dir variable:/ PS C:/> dir variable:/s* #显示文件内容 PS C:/> ${c:/autoexec.bat} #变量范围 $Global:myVariable1 = value1 $Script:myVariable2 = value2 $Local:myVariable3 = value3 #静态方法 调用 donet PS C:/> [System.Diagnostics.Process]::GetProcessById(0) Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 0 0 0 24 0 0 Idle Get-Process Notepad #Get-Process 代替 System.Diagnostics.Process $process.WaitForExit() #暂停直到结束 Get-Date 等同于 [System.DateTime]::Now #创建对象 PS C:/> $generator = New-Object System.Random PS C:/> $generator.NextDouble() 0.121309703738107 PS C:/> (New-Object Net.WebClient).DownloadString("http://www.baidu.com") #先加载库文件 PS C:/> [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") GAC Version Location --- ------- -------- True v2.0.50727 C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.... #创建后保存 PS C:/> $image = New-Object System.Drawing.Bitmap source.gif PS C:/> $image.Save("source_1.jpg","JPEG") PS C:/> [Reflection.Assembly]::LoadWithPartialName("System.Web") GAC Version Location --- ------- -------- True v2.0.50727 C:/Windows/assembly/GAC_32/System.Web/2.0.0.0__b03f5f7... PS C:/> [Web.HttpUtility]::UrlEncode("http://search.msn.com") http%3a%2f%2fsearch.msn.com #缩短类名 PS C:/> $math=[System.Math] PS C:/> $math::Min(1,10) 1 #调用COM组件 $sapi = New-Object -Com Sapi.SpVoice $sapi.rate=0 $sapi.Speak("一直以为...只要隐着身,就没有美女认得出我是帅哥!但是...我错了,像我这样拉风的男人,就好比那暗夜里的萤火虫,田地里的金龟子,是那样的鲜明,那样的出众,特别是我那忧郁的眼神,凌乱的头发,嘴里叼着四块五的红金龙,还有我兜里露出来的半包旺旺雪饼,深深地出卖了我。") #获取对象类型 $date = Get-Date $date.GetType().ToString() #正则表达式匹配 PS C:/Users/vv> "Hello World" -match "Hello" True #条件运算符 PS C:/Users/vv> $data = "Hello World" ($data -like "*llo w*") -and ($data.Length -gt 10) True #逻辑运算关键字 -eq -ne -ge -lt -le -like -notlike -match -notmatch -contains -notcontains -is isnot #条件语句 if elseif else $a=20 switch($a) { {$_ -lt 32} {"aaaa";break} 32 {"bbb";break} default {"ccc"} } #循环 #for foreach while do foreach-object foreach($file in dir){ "File length:"+$file.Length } #暂停或延迟 Read-Host "Press ENTER" Start-Sleep 2 Start-Sleep -Milliseconds 300 #字符串 使用单引号表示原生字符串,不支持变量扩展或转义字符 $myString = 'Hello World' #多行字符串 $myString = @" This is the first line, This is the second line. "@ #多行注释 ##This is a regular comment $null=@" function MyTest{ "aaaaaaaaaaaa" } "@ #变量$null告诉PowerShell不必为后续的使用而继续保留信息了 #转义字符 ` (不使用反斜杠) PS C:/Users/vv> $myString = "Report for today `n---------" $myString Report for today --------- #字符串变量 PS C:/Users/vv> $header = "Report for today" $myString = "$header `n$('-'*$header.Length)" $myString Report for today ---------------- #格式化输出 右对齐8个字符,格式为4为数字,:C表示货币形式 -f String.Format() PS C:/Users/vv> $formatString = "{0,8:D4} {1:C}`n" $report = "Quantity Price`n" $report += "--------------`n" $report += $formatString -f 50,2.5677 $report += $formatString -f 3,7 $report Quantity Price -------------- 0050 ¥2.57 0003 ¥7.00 #字符串方法 PS C:/Users/vv> "abc".IndexOf("b") 1 PS C:/Users/vv> "abc".Contains("b") True #$helpContent 得到的是一个对像,而不是字符串 $helpContent = Get-Help Get-ChildItem $helpContent -match "location" False $helpContent.Name Get-ChildItem #得到字符串使用下面的方式 $helpContent = Get-Help Get-ChildItem | Out-String $helpContent -match "location" True "Hello World".Replace("World","PowerShell") Hello PowerShell #replace 高级用法 "Hello World" -replace '(.*) (.*)','$2 $1' World Hello "Hello World".ToUpper() HELLO WORLD "Hello World".ToLower() hello world #首字符大写 $text = "hello" $newText = $text.Substring(0,1).ToUpper()+$text.Substring(1) "Hello World".Trim() #从字符串尾部取出字符 "Hello World".TrimEnd('w','d',' '); #格式化日期 $date = [DateTime]::now $date.ToString("dd-MM-yyyy") #日期比较 $dueDate = [DateTime] "01/01/2008" if([DateTime]::Now -gt $dueDate) { "Account is now due" } #字符串合并用 append Measure-Command{ $output = New-Object Text.StringBuilder 1..10000 | Foreach-Object { $output.Append("Hello World") } } Days : 0 Hours : 0 Minutes : 0 Seconds : 1 Milliseconds : 696 Ticks : 16965372 TotalDays : 1.96358472222222E-05 TotalHours : 0.000471260333333333 TotalMinutes : 0.02827562 TotalSeconds : 1.6965372 TotalMilliseconds : 1696.5372 Measure-Command{ $output ="" 1..10000 | Foreach-Object { $output+="Hello World" } } Days : 0 Hours : 0 Minutes : 0 Seconds : 5 Milliseconds : 453 Ticks : 54531118 TotalDays : 6.31147199074074E-05 TotalHours : 0.00151475327777778 TotalMinutes : 0.0908851966666667 TotalSeconds : 5.4531118 TotalMilliseconds : 5453.1118 #数学计算 $result = [int](3/2) $result 2 #截断 $result=3/2 [Math]::Truncate($result) 1 function trunc($number){ [Math]::Truncate($number) } $result=3/2 trunc $result 1 [Math]::Abs(-10.6) [Math]::Pow(123,2) [Math]::Sqrt(100) [Math]::Sin([Math]::PI /2) [Math]::ASin(1) #立方根 function root($number,$root){ [Math]::Exp($([Math]::Log($number)/$root))} root 64 3 4 #统计 1..10 | Measure-Object -Average -Sum Count : 10 Average : 5.5 Sum : 55 Maximum : Minimum : Property : Get-ChildItem > output.txt Get-COntent output.txt | Measure-Object -Character -Word -Line Lines Words Characters Property ----- ----- ---------- -------- 28 117 2638 #从文件列表中取得LastWriteTime的平均值 $times = dir | Foreach-Object { $_.LastWriteTime } $results = $times | Measure-Object Ticks -Average New-Object DateTime $results.Average 2009年12月11日 21:27:09 #16进制数 $hexNumber = 0x1234 $hexNumber 4660 #16进制 转 2进制 [Convert]::ToString(12341,2) 11000000110101 #2进制转10进制 [Convert]::ToInt32("11000000110101",2) 12341 #修改文件属性,并查询 $archive = [System.IO.FileAttributes] "Archive" attrib +a test.txt Get-ChildItem | Where { $_.Attributes -band $archive } | Select Name #文件加密 (Get-Item output.txt).Encrypt() #文件解密 (Get-Item output.txt).Decrypt() #设置文件属性 (Get-Item output.txt).IsReadOnly True (Get-Item output.txt).IsReadOnly = $false (Get-Item output.txt).IsReadOnly False #枚举文件可能的属性 [Enum]::GetNames([System.IO.FileAttributes]) ReadOnly Hidden System Directory Archive Device Normal Temporary SparseFile ReparsePoint Compressed Offline NotContentIndexed Encrypted [int] (Get-Item output.txt).Attributes 32 #文件属性的表示形式 $attributes = [Enum]::GetValues([System.IO.FileAttributes]) $attributes | Select-Object ` @{"Name"="Property";"Expression"={ $_ }}, @{"Name"="Integer";"Expression"={ [int]$_ }}, @{"Name"="Hexadecimal";"Expression"={ [Convert]::ToString([int] $_,16)}}, @{"Name"="Binary";"Expression"={ [Convert]::ToString([int] $_,2)}} | Format-Table -auto Property Integer Hexadecimal Binary -------- ------- ----------- ------ ReadOnly 1 1 1 Hidden 2 2 10 System 4 4 100 Directory 16 10 10000 Archive 32 20 100000 Device 64 40 1000000 Normal 128 80 10000000 Temporary 256 100 100000000 SparseFile 512 200 1000000000 ReparsePoint 1024 400 10000000000 Compressed 2048 800 100000000000 Offline 4096 1000 1000000000000 NotContentIndexed 8192 2000 10000000000000 Encrypted 16384 4000 100000000000000 #判断文件属性 $encrypted=16384 $attributes = (Get-Item output.txt -force).Attributes ($attributes -band $encrypted) -eq $encrypted False #读取文件内容 $content = Get-Content c:/file.txt $content = ${c:/file.txt} $content = [System.IO.File]::ReadAllText("c:/file.txt") #搜索文件文本 Select-String -Simple "aaa" file.txt Select-String "/(.../) ...-..." phone.txt Get-ChildItem -Filter *.txt -Recurse | Select-String pattern #获取被补丁修改的文件列表 cd $env:WINDIR $parseExpression = "(.*): Destination:(.*) /((.*)/)" $files = dir kb*.log -Exclude *uninst.log $logContent = $files | Get-Content | Select-String $parseExpression $logContent #移动文件,删除文件 $filename = [System.IO.Path]::GetTempFileName() $newname = [System.IO.Path]::ChangeExtension($filename,".cs") Move-Item $filename $newname Remove-Item $newname #内容写入到文件 $filename = "output.txt" $content = Get-Content $filename $content = "hellohello" $content | Set-Content $filename #xml文件 $xml = [xml] (Get-Content powershell_blog.xml) $xml.rss ($xml.rss.channel.item).Count ($xml.rss.channel.item)[0].title $xml.rss.channel.item | Sort-Object title | Select-Object title #XPath查询 #查询所有少于20个字符的标题 $xml = [xml] (Get-Content powershell_blog.xml) $query = "/rss/chanel/item[string-length(title) < 20]/title" $xml.SelectNodes($query) #修改xml $filename = (Get-Item phone.xml).FullName Get-Content $fileName $phoneBook = [xml](Get-Content $fileName) $person = $phoneBook.AddressBook.Person[0] $person.Phone[0]."#text" = "555-1214" $person.Phone[0].type="mobile" $newNumber = [xml]'<Phone type="home">555-1215</Phone>' $newNode = $phoneBook.ImportNode($newNumber.Phone,$true) [void] $person.AppendChild($newNode) $phoneBook.save($filename) Get-Content $filename #Internet 脚本 #下载一个文件 (参数错误?) $source = "http://img3.cn.msn.com/images/0809/logo1.png" $destination = "c:/logo1.png" $wc = New-Object System.Net.WebClient $wc.DownloadFile($source,$destination) #下载一个Web页面 $source = "http://blogs.msdn.com/powershell/rss.xml" $wc = New-Object System.Net.WebClient $content = $wc.DownloadString($source) #输出格式为Html 创建一个PowerShell命令的概要 $filename = "c:/PowerShell.html" $commands = Get-Command | Where { $_.CommandType -ne "Alias" } $summary = $commands | Get-Help | Select Name,Synopsis $summary | ConvertTo-Html | Set-Content $filename #脚本块 function MultiplyInpuByTwo { process { $_ * 2 } } 1,2,3 | MultiplyInpuByTwo 2 4 6 #从脚本块返回数据 function GetDate { Get-Date } $tomorrow = (GetDate).AddDays(1) #数组 $myArray = 1,2,"aaa" $myArray 1 2 aaa #数组 基本操作 $collection = New-Object System.Collections.ArrayList $collection.Add("Hello") [void]$collection.Add("Hello") [void]$collection.AddRange{("a","b")} $collection.RemoveAt(1) $myArray = New-Object string[] 10 $myArray[5]="bbb" $myArray = Get-Process $myArray Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 851 38 69204 101888 338 137.36 5012 360SE 532 30 42192 42316 271 54.19 5864 360SE 965 19 17784 2192 132 3768 360tray 134 5 15516 12864 41 3612 audiodg 314 21 6796 5228 127 188 CCProxy 56 5 796 304 33 1232 CNAB4RPK 61 4 1532 1312 63 0.09 5436 conhost ...... $myArray = @(Get-Process Explorer) $myArray Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 1085 42 52080 98140 300 164.77 2256 explorer $a = @( (1,2,3,4), (5,6,7,8) ) $a[0][1] 2 $myArray = 1,2,3 $myArray[1..3 + 0] 2 3 1 #访问数组中的每一个元素 $myArray = 1,2,3 $sum = 0 $myArray | Foreach-Object {$sum+=$_} $sum 6 #访问数组中的每一个元素,更脚本化 $myArray = 1,2,3 $sum=0 foreach($element in $myArray){$sum+=$element} $sum 6 #数组列表排序 Get-ChildItem | Sort-Object -Descending Length | Select Name, Length #检查数组列表是否包含指定的项 "Hello","World" -contains "Hello" #合并数组 $array = 1,2 $array += 3,4 #数组查询 $array = "Item1","Item2","Item3","Item4","Item15" $array -eq "Item1" #Item1 $array -like "*2*" #Item2 $array -match "Item.." #Item15 $array -ne "Item1" #Item2 Item3 Item4 Item15 $array -notlike "*1*" #Item2 Item3 Item4 $array -notmatch "Item.." #Item1 Item2 Item3 Item4 #哈希表 ,哈希表不保存顺序,可用 Sort 排序 $myHashtable = @{} $myHashtable = @{key1="value1";key2=1,2,3} $myHashtable["NewItem"]=5 foreach($item in $myHashtable.GetEnumerator() | Sort Name) { $item.value } #参数 function Reverse { $srgsEnd = $args.Length - 1 $args[$srgsEnd..0] } Reverse 1,2,3,4 #用户交互 #读取用户输入一行 $directory = Read-Host "Enter a directory name:" $directory #读取用户输入的键 $key = [Console]::ReadKey($true) $key $key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") #环境变量 #查看 $env:username #完整方式 Get-Content Env:/Username #查看所有变量 dir env: Name Value ---- ----- ALLUSERSPROFILE C:/ProgramData ANT_HOME D:/J2EE/apache-ant-1.7.0 APPDATA C:/Users/vv/AppData/Roaming CLASSPATH ./;D:/Design/J2EE/jdk1.6.0_10/lib/tools.jar CommonProgramFiles C:/Program Files/Common Files COMPUTERNAME VV-PC ComSpec C:/Windows/system32/cmd.exe FP_NO_HOST_CHECK NO HOMEDRIVE C: HOMEPATH /Users/vv JAVA_HOME D:/Design/J2EE/jdk1.6.0_10 ...... #设置环境变量(永久) $oldPersonalPath = ";d:/tools" [Environment]::SetEnvironmentVariable("Path",$oldPersonalPath,"User") [Environment]::GetEnvironmentVariable("Path","User") #;d:/tools #阅读 rss $sapi = New-Object -Com Sapi.SpVoice $WebClient = New-Object System.Net.WebClient $WebClient.Encoding=[System.Text.Encoding]::UTF8 $rss = [XML]($WebClient.DownloadString("http://weather.qq.com/zixun/rss_fyzx.xml")) foreach($item in $rss.rss.channel.Item){ $title = $item.title #$title = $item.title.InnerText $content = $item.description #$content = $item.description.InnerText #$content = $item.description.InnerText.Replace(" ","") $title $sapi.Speak($title+"。") $content $sapi.Speak($content+"。。") }