1 啓動 powershell 2 3 #字符串操做 4 對象操做 "hello".Length 5 6 7 #進程操做 8 PS C:\> notepad 9 PS C:\> $process=get-process notepad 10 PS C:\> $process.Kill() 11 12 13 #默認對象操做 14 PS C:\> 40GB/650MB 15 63.0153846153846 16 17 #時間操做 18 PS C:\> [DateTime]"2009-12-5" - [DateTime]::Now 19 Days : -58 20 Hours : -14 21 Minutes : -53 22 Seconds : -58 23 Milliseconds : -510 24 Ticks : -50648385105314 25 TotalDays : -58.6208160941134 26 TotalHours : -1406.89958625872 27 TotalMinutes : -84413.9751755233 28 TotalSeconds : -5064838.5105314 29 TotalMilliseconds : -5064838510.5314 30 31 #時間對象操做 32 PS C:\> $result = [DateTime]"2009-12-5" - [DateTime]::Now 33 PS C:\> $result.TotalDays 34 -58.6213450248299 35 36 37 #查詢今天星期幾 38 PS C:\Users\vv> $date=Get-Date 39 PS C:\Users\vv> $date.DayOfWeek 40 Monday 41 42 43 #查找powershell命令中包含單詞process的命令 44 PS C:\> Get-Command *process* 45 CommandType Name Definition 46 ----------- ---- ---------- 47 Application api-ms-win-core-processenvir... C:\Windows\system32\api-ms-w... 48 Application api-ms-win-core-processthrea... C:\Windows\system32\api-ms-w... 49 Cmdlet Debug-Process Debug-Process [-Name] <Strin... 50 Cmdlet Get-Process Get-Process [[-Name] <String... 51 Application microsoft-windows-kernel-pro... C:\Windows\system32\microsof... 52 Application qprocess.exe C:\Windows\system32\qprocess... 53 Cmdlet Start-Process Start-Process [-FilePath] <S... 54 Cmdlet Stop-Process Stop-Process [-Id] <Int32[]>... 55 Cmdlet Wait-Process Wait-Process [-Name] <String... 56 57 58 #檢索donet中對象的屬性和方法 59 PS C:\> "aaa" | Get-Member 60 61 TypeName: System.String 62 63 Name MemberType Definition 64 ---- ---------- ---------- 65 Clone Method System.Object Clone() 66 CompareTo Method int CompareTo(System.Object value), i... 67 Contains Method bool Contains(string value) 68 CopyTo Method System.Void CopyTo(int sourceIndex, c... 69 EndsWith Method bool EndsWith(string value), bool End... 70 Equals Method bool Equals(System.Object obj), bool ... 71 GetEnumerator Method System.CharEnumerator GetEnumerator() 72 GetHashCode Method int GetHashCode() 73 GetType Method type GetType() 74 GetTypeCode Method System.TypeCode GetTypeCode() 75 IndexOf Method int IndexOf(char value), int IndexOf(... 76 IndexOfAny Method int IndexOfAny(char[] anyOf), int Ind... 77 Insert Method string Insert(int startIndex, string ... 78 IsNormalized Method bool IsNormalized(), bool IsNormalize... 79 LastIndexOf Method int LastIndexOf(char value), int Last... 80 LastIndexOfAny Method int LastIndexOfAny(char[] anyOf), int... 81 ... 82 83 84 #統計全部正在運行的進程的句柄數 85 PS C:\> $handleCount=0 86 PS C:\> foreach($process in Get-process) { $handleCount +=$process.Handles } 87 PS C:\> $handleCount 88 23318 89 90 #直接調用donet對象,獲取網頁內容 91 PS C:\> $webClient = New-Object System.Net.WebClient 92 PS C:\> $content = $webClient.DownloadString("http://www.baidu.com") 93 PS C:\> $content.Substring(0,1000) 94 <html><head><meta http-equiv=Content-Type content="text/html;charset=gb2312"><t 95 itle>百度一下,你就知道 </title><style>body{margin:4px 0}p{margin:0;paddin 96 g:0}img{border:0}td,p,#u{font-size:12px}#b,#u,#l td,a{font-family:arial}#kw{fon 97 t:16px Verdana;height:1.78em;padding-top:2px}#b{height:30px;padding-top:4px}#b, 98 #b a{color:#77c}#u{padding-right:10px;line-height:19px;text-align:right;margin: 99 0 0 3px !important;margin:0 0 10px}#sb{height:2em;width:5.6em}#km{height:50px}# 100 l{margin:0 0 5px 38px}#l td{padding-left:107px}p,table{width:650px;border:0}#l 101 td,#sb,#km{font-size:14px}#l a,#l b{margin-right:1.14em}a{color:#00c}a:active{c 102 olor:#f60}#hp{position:absolute;margin-left:6px}#lg{margin:-26px 0 -44px}#lk{wi 103 dth:auto;line-height:18px;vertical-align:top}form{position:relative;z-index:9}< 104 /style></head> 105 <body><div id=u><a href=http://passport.baidu.com/?login&tpl=mn>登陸</a></div>< 106 center><img src=http://www.baidu.com/img/baidu_logo.gif width=270 height=129 us 107 emap="#mp" id=lg><br><br><br><br><table cellpadd 108 109 110 #獲取系統信息 111 PS C:\> Get-WmiObject Win32_Bios 112 113 SMBIOSBIOSVersion : 2TKT00AUS 114 Manufacturer : LENOVO 115 Name : Default System BIOS 116 SerialNumber : 1111111 117 Version : LENOVO - 5000821 118 119 120 #導航文件系統 121 PS C:\> Set-Location c:\ 122 PS C:\> Get-ChildItem 123 124 125 目錄: C:\ 126 127 128 Mode LastWriteTime Length Name 129 ---- ------------- ------ ---- 130 d---- 2010/1/7 14:20 bea 131 d---- 2010/1/7 14:20 BEA WebLogic E-Business Platform 132 d---- 2009/12/7 13:02 dzh 133 d---- 2010/1/2 15:48 his 134 d---- 2009/7/14 10:37 PerfLogs 135 d-r-- 2010/1/25 12:58 Program Files 136 d-r-- 2009/12/31 19:11 Users 137 d---- 2009/11/7 9:52 usr 138 d---- 2010/1/28 3:16 Windows 139 -a--- 2009/6/11 5:42 24 autoexec.bat 140 -a--- 2009/6/11 5:42 10 config.sys 141 -a--- 2009/10/28 13:37 454656 putty.exe 142 143 144 #導航註冊表 145 PS C:\> Set-Location HKCU:\Software\Microsoft\Windows\ 146 PS HKCU:\Software\Microsoft\Windows\> Get-ChildItem 147 148 149 Hive: HKEY_CURRENT_USER\Software\Microsoft\Windows 150 151 152 SKC VC Name Property 153 --- -- ---- -------- 154 33 0 CurrentVersion {} 155 0 11 DWM {Composition, CompositionPolicy, Colo... 156 3 0 Shell {} 157 1 0 ShellNoRoam {} 158 2 0 TabletPC {} 159 3 12 Windows Error Reporting {ConfigureArchive, DisableArchive, Di... 160 161 162 #導航證書 163 PS C:\Users\vv> Set-Location cert:\CurrentUser\Root 164 PS cert:\CurrentUser\Root> Get-ChildItem 165 166 167 目錄: Microsoft.PowerShell.Security\Certificate::CurrentUser\Root 168 169 170 Thumbprint Subject 171 ---------- ------- 172 CDD4EEAE6000AC7F40C3802C171E30148030C072 CN=Microsoft Root Certificate Auth... 173 BE36A4562FB2EE05DBB3D32323ADF445084ED656 CN=Thawte Timestamping CA, OU=Thaw... 174 A7217F919843199C958C128449DD52D2723B0A8A CN=Alibaba.com Corporation Root CA... 175 A43489159A520F0D93D032CCAF37E7FE20A8B419 CN=Microsoft Root Authority, OU=Mi... 176 7F88CD7223F3C813818C994614A89C99FA3B5247 CN=Microsoft Authenticode(tm) Root... 177 742C3192E607E424EB4549542BE1BBC53E6174E2 OU=Class 3 Public Primary Certific... 178 654E9FADD2032AE1B87D6263AF04FD7FEE38D57C CN=iTruschina CN Root CA-3, OU=Chi... 179 46F168AF009C28C18F452EB85F5E8747892B3C8B CN=iTruschina CN Root CA-2, OU=Chi... 180 245C97DF7514E7CF2DF8BE72AE957B9E04741E85 OU=Copyright (c) 1997 Microsoft Co... 181 240A61A2577970625B9F0B81283C4AA4037217B1 CN=iTruschina CN Root CA-1, OU=Chi... 182 18F7C1FCC3090203FD5BAA2F861A754976C8DD25 OU="NO LIABILITY ACCEPTED, (c)97 V... 183 184 185 #顯示全部進程 186 PS C:\Users\vv> Get-Process 187 188 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName 189 ------- ------ ----- ----- ----- ------ -- ----------- 190 527 28 40784 44864 243 18.94 4956 360SE 191 537 29 49144 59340 248 9.09 5276 360SE 192 924 20 17580 2504 132 3768 360tray 193 160 5 16080 7852 41 2036 audiodg 194 318 24 6524 7008 124 188 CCProxy 195 56 5 796 288 33 1232 CNAB4RPK 196 61 4 1568 6916 63 0.19 5064 conhost 197 60 4 1532 3628 63 0.06 5584 conhost 198 645 6 2076 1204 72 380 csrss 199 649 9 8148 11056 185 440 csrss 200 ...... 201 202 203 #搜索全部包含Get動詞的命令 204 PS C:\Users\vv> Get-Command -Verb Get 205 206 CommandType Name Definition 207 ----------- ---- ---------- 208 Cmdlet Get-Acl Get-Acl [[-Path] <String[]>]... 209 Cmdlet Get-Alias Get-Alias [[-Name] <String[]... 210 Cmdlet Get-AuthenticodeSignature Get-AuthenticodeSignature [-... 211 Cmdlet Get-ChildItem Get-ChildItem [[-Path] <Stri... 212 Cmdlet Get-Command Get-Command [[-ArgumentList]... 213 Cmdlet Get-ComputerRestorePoint Get-ComputerRestorePoint [[-... 214 ...... 215 216 217 #幫助 218 PS C:\Users\vv> Get-Help Get-Verb -Full/-Detailed/-Examples 219 220 221 #調用powershell腳本 222 PowerShell "& 'C:\get-report.ps1' arguments" 223 224 225 #循環 226 PS C:\Users\vv> 1..10 | % {"aaa"} 227 aaa 228 aaa 229 aaa 230 aaa 231 aaa 232 aaa 233 aaa 234 aaa 235 aaa 236 aaa 237 238 239 #數據加密(Base64) 240 PS C:\Users\vv> $bytes=[System.Text.Encoding]::Unicode.GetBytes("aaa") 241 PS C:\Users\vv> $encodedString=[Convert]::ToBase64String($bytes) 242 PS C:\Users\vv> $encodedString 243 YQBhAGEA 244 245 246 #檢查命令是否執行成功 247 PS C:\Users\vv> $lastExitCode 248 0 249 PS C:\Users\vv> $? 250 True 251 252 253 #性能測試,計算一個命令執行的時間 254 PS C:\Users\vv> Measure-Command { Start-Sleep -Milliseconds 337 } 255 Days : 0 256 Hours : 0 257 Minutes : 0 258 Seconds : 0 259 Milliseconds : 340 260 Ticks : 3404713 261 TotalDays : 3.9406400462963E-06 262 TotalHours : 9.45753611111111E-05 263 TotalMinutes : 0.00567452166666667 264 TotalSeconds : 0.3404713 265 TotalMilliseconds : 340.4713 266 267 268 #foreach 循環 269 foreach($alias in Get-Alias){ 270 $alias 271 } 272 273 274 #顯示爲表格 275 PS C:\Users\vv> Get-Process | Format-Table Name,WS -Auto 276 277 278 #複製文件 279 Copy-Item c:\temp\*.txt c:\temp\backup\ -verbose 280 281 282 #列出全部已經中止的服務 283 PS C:\Users\vv> Get-Service | Where-Object { $_.Status -eq "Stopped" } 284 #列出當前位置的全部子目錄 285 PS C:\Users\vv> Get-ChildItem | Where-Object { $_.PsIsContainer } 286 287 288 #循環 289 PS C:\Users\vv> 1..10 | Foreach-Object { $_ * 2 } 290 291 292 #獲取正在運行的記事本程序的進程列表,而後等待他們退出 293 PS C:\Users\vv> $notepadProcesses = Get-Process notepad 294 PS C:\Users\vv> $notepadProcesses | Foreach-Object { $_.WaitForExit() } 295 296 #其它循環關鍵字 297 for foreach do while 298 299 300 #從管道中選擇接收值 301 PS C:\Users\vv> dir | Select Name 302 303 304 #釋放變量佔用的內存空間 305 $processes = $null 306 307 308 #顯示全部變量 309 PS C:\> dir variable:\ 310 311 PS C:\> dir variable:\s* 312 313 #顯示文件內容 314 PS C:\> ${c:\autoexec.bat} 315 316 #變量範圍 317 $Global:myVariable1 = value1 318 $Script:myVariable2 = value2 319 $Local:myVariable3 = value3 320 321 322 #靜態方法 調用 donet 323 PS C:\> [System.Diagnostics.Process]::GetProcessById(0) 324 325 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName 326 ------- ------ ----- ----- ----- ------ -- ----------- 327 0 0 0 24 0 0 Idle 328 329 330 Get-Process Notepad 331 #Get-Process 代替 System.Diagnostics.Process 332 333 $process.WaitForExit() #暫停直到結束 334 335 Get-Date 等同於 [System.DateTime]::Now 336 337 #建立對象 338 PS C:\> $generator = New-Object System.Random 339 PS C:\> $generator.NextDouble() 340 0.121309703738107 341 342 PS C:\> (New-Object Net.WebClient).DownloadString("http://www.baidu.com") 343 344 #先加載庫文件 345 PS C:\> [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 346 GAC Version Location 347 --- ------- -------- 348 True v2.0.50727 C:\Windows\assembly\GAC_MSIL\System.Windows.Forms\2.0.... 349 #建立後保存 350 PS C:\> $image = New-Object System.Drawing.Bitmap source.gif 351 PS C:\> $image.Save("source_1.jpg","JPEG") 352 353 354 PS C:\> [Reflection.Assembly]::LoadWithPartialName("System.Web") 355 GAC Version Location 356 --- ------- -------- 357 True v2.0.50727 C:\Windows\assembly\GAC_32\System.Web\2.0.0.0__b03f5f7... 358 359 PS C:\> [Web.HttpUtility]::UrlEncode("http://search.msn.com") 360 http%3a%2f%2fsearch.msn.com 361 362 363 #縮短類名 364 PS C:\> $math=[System.Math] 365 PS C:\> $math::Min(1,10) 366 1 367 368 #調用COM組件 369 $sapi = New-Object -Com Sapi.SpVoice 370 $sapi.rate=0 371 $sapi.Speak("一直覺得...只要隱着身,就沒有美女認得出我是帥哥!可是...我錯了,像我這樣拉風的男人,就比如那暗夜裏的螢火蟲,田地裏的金龜子,是那樣的鮮明,那樣的出衆,特別是我那憂鬱的眼神,凌亂的頭髮,嘴裏叼着四塊五的紅金龍,還有我兜裏露出來的半包旺旺雪餅,深深地出賣了我。") 372 373 374 #獲取對象類型 375 $date = Get-Date 376 $date.GetType().ToString() 377 378 379 #正則表達式匹配 380 PS C:\Users\vv> "Hello World" -match "Hello" 381 True 382 383 #條件運算符 384 PS C:\Users\vv> $data = "Hello World" 385 ($data -like "*llo w*") -and ($data.Length -gt 10) 386 True 387 388 #邏輯運算關鍵字 389 -eq -ne -ge -lt -le -like -notlike -match -notmatch -contains -notcontains -is isnot 390 391 392 #條件語句 393 if elseif else 394 395 $a=20 396 switch($a) 397 { 398 {$_ -lt 32} {"aaaa";break} 399 32 {"bbb";break} 400 default {"ccc"} 401 } 402 403 #循環 404 #for foreach while do foreach-object 405 foreach($file in dir){ 406 "File length:"+$file.Length 407 } 408 409 #暫停或延遲 410 Read-Host "Press ENTER" 411 Start-Sleep 2 412 Start-Sleep -Milliseconds 300 413 414 415 #字符串 使用單引號表示原生字符串,不支持變量擴展或轉義字符 416 $myString = 'Hello World' 417 418 #多行字符串 419 $myString = @" 420 This is the first line, 421 This is the second line. 422 "@ 423 424 #多行註釋 425 ##This is a regular comment 426 $null=@" 427 function MyTest{ 428 "aaaaaaaaaaaa" 429 } 430 "@ 431 #變量$null告訴PowerShell沒必要爲後續的使用而繼續保留信息了 432 433 #轉義字符 ` (不使用反斜槓) 434 PS C:\Users\vv> $myString = "Report for today `n---------" 435 $myString 436 Report for today 437 --------- 438 439 #字符串變量 440 PS C:\Users\vv> $header = "Report for today" 441 $myString = "$header `n$('-'*$header.Length)" 442 $myString 443 444 Report for today 445 ---------------- 446 447 #格式化輸出 右對齊8個字符,格式爲4爲數字,:C表示貨幣形式 -f String.Format() 448 PS C:\Users\vv> $formatString = "{0,8:D4} {1:C}`n" 449 $report = "Quantity Price`n" 450 $report += "--------------`n" 451 $report += $formatString -f 50,2.5677 452 $report += $formatString -f 3,7 453 $report 454 Quantity Price 455 -------------- 456 0050 ¥2.57 457 0003 ¥7.00 458 459 #字符串方法 460 PS C:\Users\vv> "abc".IndexOf("b") 461 1 462 463 PS C:\Users\vv> "abc".Contains("b") 464 True 465 466 #$helpContent 獲得的是一個對像,而不是字符串 467 $helpContent = Get-Help Get-ChildItem 468 $helpContent -match "location" 469 False 470 471 $helpContent.Name 472 Get-ChildItem 473 474 #獲得字符串使用下面的方式 475 $helpContent = Get-Help Get-ChildItem | Out-String 476 $helpContent -match "location" 477 True 478 479 "Hello World".Replace("World","PowerShell") 480 Hello PowerShell 481 482 #replace 高級用法 483 "Hello World" -replace '(.*) (.*)','$2 $1' 484 World Hello 485 486 "Hello World".ToUpper() 487 HELLO WORLD 488 "Hello World".ToLower() 489 hello world 490 491 #首字符大寫 492 $text = "hello" 493 $newText = $text.Substring(0,1).ToUpper()+$text.Substring(1) 494 495 "Hello World".Trim() 496 497 #從字符串尾部取出字符 498 "Hello World".TrimEnd('w','d',' '); 499 500 #格式化日期 501 $date = [DateTime]::now 502 $date.ToString("dd-MM-yyyy") 503 504 #日期比較 505 $dueDate = [DateTime] "01/01/2008" 506 if([DateTime]::Now -gt $dueDate) 507 { 508 "Account is now due" 509 } 510 511 512 #字符串合併用 append 513 Measure-Command{ 514 $output = New-Object Text.StringBuilder 515 1..10000 | 516 Foreach-Object { $output.Append("Hello World") } 517 } 518 Days : 0 519 Hours : 0 520 Minutes : 0 521 Seconds : 1 522 Milliseconds : 696 523 Ticks : 16965372 524 TotalDays : 1.96358472222222E-05 525 TotalHours : 0.000471260333333333 526 TotalMinutes : 0.02827562 527 TotalSeconds : 1.6965372 528 TotalMilliseconds : 1696.5372 529 530 Measure-Command{ 531 $output ="" 532 1..10000 | 533 Foreach-Object { $output+="Hello World" } 534 } 535 Days : 0 536 Hours : 0 537 Minutes : 0 538 Seconds : 5 539 Milliseconds : 453 540 Ticks : 54531118 541 TotalDays : 6.31147199074074E-05 542 TotalHours : 0.00151475327777778 543 TotalMinutes : 0.0908851966666667 544 TotalSeconds : 5.4531118 545 TotalMilliseconds : 5453.1118 546 547 548 #數學計算 549 $result = [int](3/2) 550 $result 551 2 552 553 #截斷 554 $result=3/2 555 [Math]::Truncate($result) 556 1 557 558 function trunc($number){ 559 [Math]::Truncate($number) 560 } 561 $result=3/2 562 trunc $result 563 1 564 565 [Math]::Abs(-10.6) 566 [Math]::Pow(123,2) 567 [Math]::Sqrt(100) 568 [Math]::Sin([Math]::PI /2) 569 [Math]::ASin(1) 570 571 #立方根 572 function root($number,$root){ [Math]::Exp($([Math]::Log($number)/$root))} 573 root 64 3 574 4 575 576 #統計 577 1..10 | Measure-Object -Average -Sum 578 579 Count : 10 580 Average : 5.5 581 Sum : 55 582 Maximum : 583 Minimum : 584 Property : 585 586 Get-ChildItem > output.txt 587 Get-COntent output.txt | Measure-Object -Character -Word -Line 588 589 Lines Words Characters Property 590 ----- ----- ---------- -------- 591 28 117 2638 592 593 #從文件列表中取得LastWriteTime的平均值 594 $times = dir | Foreach-Object { $_.LastWriteTime } 595 $results = $times | Measure-Object Ticks -Average 596 New-Object DateTime $results.Average 597 598 2009年12月11日 21:27:09 599 600 601 #16進制數 602 $hexNumber = 0x1234 603 $hexNumber 604 4660 605 606 #16進制 轉 2進制 607 [Convert]::ToString(12341,2) 608 11000000110101 609 610 #2進制轉10進制 611 [Convert]::ToInt32("11000000110101",2) 612 12341 613 614 #修改文件屬性,並查詢 615 $archive = [System.IO.FileAttributes] "Archive" 616 attrib +a test.txt 617 Get-ChildItem | Where { $_.Attributes -band $archive } | Select Name 618 619 620 #文件加密 621 (Get-Item output.txt).Encrypt() 622 #文件解密 623 (Get-Item output.txt).Decrypt() 624 625 #設置文件屬性 626 (Get-Item output.txt).IsReadOnly 627 True 628 (Get-Item output.txt).IsReadOnly = $false 629 (Get-Item output.txt).IsReadOnly 630 False 631 632 633 #枚舉文件可能的屬性 634 [Enum]::GetNames([System.IO.FileAttributes]) 635 ReadOnly 636 Hidden 637 System 638 Directory 639 Archive 640 Device 641 Normal 642 Temporary 643 SparseFile 644 ReparsePoint 645 Compressed 646 Offline 647 NotContentIndexed 648 Encrypted 649 650 651 [int] (Get-Item output.txt).Attributes 652 32 653 654 #文件屬性的表示形式 655 $attributes = [Enum]::GetValues([System.IO.FileAttributes]) 656 $attributes | Select-Object ` 657 @{"Name"="Property";"Expression"={ $_ }}, 658 @{"Name"="Integer";"Expression"={ [int]$_ }}, 659 @{"Name"="Hexadecimal";"Expression"={ [Convert]::ToString([int] $_,16)}}, 660 @{"Name"="Binary";"Expression"={ [Convert]::ToString([int] $_,2)}} | 661 Format-Table -auto 662 663 Property Integer Hexadecimal Binary 664 -------- ------- ----------- ------ 665 ReadOnly 1 1 1 666 Hidden 2 2 10 667 System 4 4 100 668 Directory 16 10 10000 669 Archive 32 20 100000 670 Device 64 40 1000000 671 Normal 128 80 10000000 672 Temporary 256 100 100000000 673 SparseFile 512 200 1000000000 674 ReparsePoint 1024 400 10000000000 675 Compressed 2048 800 100000000000 676 Offline 4096 1000 1000000000000 677 NotContentIndexed 8192 2000 10000000000000 678 Encrypted 16384 4000 100000000000000 679 680 681 #判斷文件屬性 682 $encrypted=16384 683 $attributes = (Get-Item output.txt -force).Attributes 684 ($attributes -band $encrypted) -eq $encrypted 685 False 686 687 688 #讀取文件內容 689 $content = Get-Content c:\file.txt 690 $content = ${c:\file.txt} 691 $content = [System.IO.File]::ReadAllText("c:\file.txt") 692 693 #搜索文件文本 694 Select-String -Simple "aaa" file.txt 695 Select-String "\(...\) ...-..." phone.txt 696 697 Get-ChildItem -Filter *.txt -Recurse | Select-String pattern 698 699 700 #獲取被補丁修改的文件列表 701 cd $env:WINDIR 702 $parseExpression = "(.*): Destination:(.*) \((.*)\)" 703 $files = dir kb*.log -Exclude *uninst.log 704 $logContent = $files | Get-Content | Select-String $parseExpression 705 $logContent 706 707 #移動文件,刪除文件 708 $filename = [System.IO.Path]::GetTempFileName() 709 $newname = [System.IO.Path]::ChangeExtension($filename,".cs") 710 Move-Item $filename $newname 711 Remove-Item $newname 712 713 714 #內容寫入到文件 715 $filename = "output.txt" 716 $content = Get-Content $filename 717 $content = "hellohello" 718 $content | Set-Content $filename 719 720 721 #xml文件 722 $xml = [xml] (Get-Content powershell_blog.xml) 723 $xml.rss 724 ($xml.rss.channel.item).Count 725 ($xml.rss.channel.item)[0].title 726 $xml.rss.channel.item | Sort-Object title | Select-Object title 727 728 #XPath查詢 729 #查詢全部少於20個字符的標題 730 $xml = [xml] (Get-Content powershell_blog.xml) 731 $query = "/rss/chanel/item[string-length(title) < 20]/title" 732 $xml.SelectNodes($query) 733 734 #修改xml 735 $filename = (Get-Item phone.xml).FullName 736 Get-Content $fileName 737 $phoneBook = [xml](Get-Content $fileName) 738 $person = $phoneBook.AddressBook.Person[0] 739 $person.Phone[0]."#text" = "555-1214" 740 $person.Phone[0].type="mobile" 741 $newNumber = [xml]'<Phone type="home">555-1215</Phone>' 742 $newNode = $phoneBook.ImportNode($newNumber.Phone,$true) 743 [void] $person.AppendChild($newNode) 744 $phoneBook.save($filename) 745 Get-Content $filename 746 747 748 749 #Internet 腳本 750 #下載一個文件 (參數錯誤?) 751 $source = "http://img3.cn.msn.com/images/0809/logo1.png" 752 $destination = "c:\logo1.png" 753 $wc = New-Object System.Net.WebClient 754 $wc.DownloadFile($source,$destination) 755 756 #下載一個Web頁面 757 $source = "http://blogs.msdn.com/powershell/rss.xml" 758 $wc = New-Object System.Net.WebClient 759 $content = $wc.DownloadString($source) 760 761 #輸出格式爲Html 建立一個PowerShell命令的概要 762 $filename = "c:\PowerShell.html" 763 $commands = Get-Command | Where { $_.CommandType -ne "Alias" } 764 $summary = $commands | Get-Help | Select Name,Synopsis 765 $summary | ConvertTo-Html | Set-Content $filename 766 767 #腳本塊 768 function MultiplyInpuByTwo 769 { 770 process 771 { 772 $_ * 2 773 } 774 } 775 776 1,2,3 | MultiplyInpuByTwo 777 2 778 4 779 6 780 781 #從腳本塊返回數據 782 function GetDate 783 { 784 Get-Date 785 } 786 $tomorrow = (GetDate).AddDays(1) 787 788 789 790 791 792 #數組 793 $myArray = 1,2,"aaa" 794 $myArray 795 1 796 2 797 aaa 798 799 #數組 基本操做 800 $collection = New-Object System.Collections.ArrayList 801 $collection.Add("Hello") 802 [void]$collection.Add("Hello") 803 [void]$collection.AddRange{("a","b")} 804 $collection.RemoveAt(1) 805 806 $myArray = New-Object string[] 10 807 $myArray[5]="bbb" 808 809 810 $myArray = Get-Process 811 $myArray 812 813 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName 814 ------- ------ ----- ----- ----- ------ -- ----------- 815 851 38 69204 101888 338 137.36 5012 360SE 816 532 30 42192 42316 271 54.19 5864 360SE 817 965 19 17784 2192 132 3768 360tray 818 134 5 15516 12864 41 3612 audiodg 819 314 21 6796 5228 127 188 CCProxy 820 56 5 796 304 33 1232 CNAB4RPK 821 61 4 1532 1312 63 0.09 5436 conhost 822 ...... 823 824 825 $myArray = @(Get-Process Explorer) 826 $myArray 827 828 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName 829 ------- ------ ----- ----- ----- ------ -- ----------- 830 1085 42 52080 98140 300 164.77 2256 explorer 831 832 833 834 $a = @( 835 (1,2,3,4), 836 (5,6,7,8) 837 ) 838 $a[0][1] 839 2 840 841 $myArray = 1,2,3 842 $myArray[1..3 + 0] 843 2 844 3 845 1 846 847 #訪問數組中的每個元素 848 $myArray = 1,2,3 849 $sum = 0 850 $myArray | Foreach-Object {$sum+=$_} 851 $sum 852 6 853 854 #訪問數組中的每個元素,更腳本化 855 $myArray = 1,2,3 856 $sum=0 857 foreach($element in $myArray){$sum+=$element} 858 $sum 859 6 860 861 #數組列表排序 862 Get-ChildItem | Sort-Object -Descending Length | Select Name, Length 863 864 #檢查數組列表是否包含指定的項 865 "Hello","World" -contains "Hello" 866 867 #合併數組 868 $array = 1,2 869 $array += 3,4 870 871 #數組查詢 872 $array = "Item1","Item2","Item3","Item4","Item15" 873 $array -eq "Item1" #Item1 874 $array -like "*2*" #Item2 875 $array -match "Item.." #Item15 876 $array -ne "Item1" #Item2 Item3 Item4 Item15 877 $array -notlike "*1*" #Item2 Item3 Item4 878 $array -notmatch "Item.." #Item1 Item2 Item3 Item4 879 880 881 #哈希表 ,哈希表不保存順序,可用 Sort 排序 882 $myHashtable = @{} 883 $myHashtable = @{key1="value1";key2=1,2,3} 884 $myHashtable["NewItem"]=5 885 foreach($item in $myHashtable.GetEnumerator() | Sort Name) 886 { 887 $item.value 888 } 889 890 891 #參數 892 function Reverse 893 { 894 $srgsEnd = $args.Length - 1 895 $args[$srgsEnd..0] 896 } 897 Reverse 1,2,3,4 898 899 900 #用戶交互 901 #讀取用戶輸入一行 902 $directory = Read-Host "Enter a directory name:" 903 $directory 904 905 #讀取用戶輸入的鍵 906 $key = [Console]::ReadKey($true) 907 $key 908 909 $key = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") 910 911 #環境變量 912 913 #查看 914 $env:username 915 916 #完整方式 917 Get-Content Env:\Username 918 919 920 #查看全部變量 921 dir env: 922 923 Name Value 924 ---- ----- 925 ALLUSERSPROFILE C:\ProgramData 926 ANT_HOME D:\J2EE\apache-ant-1.7.0 927 APPDATA C:\Users\vv\AppData\Roaming 928 CLASSPATH .\;D:\Design\J2EE\jdk1.6.0_10\lib\tools.jar 929 CommonProgramFiles C:\Program Files\Common Files 930 COMPUTERNAME VV-PC 931 ComSpec C:\Windows\system32\cmd.exe 932 FP_NO_HOST_CHECK NO 933 HOMEDRIVE C: 934 HOMEPATH \Users\vv 935 JAVA_HOME D:\Design\J2EE\jdk1.6.0_10 936 ...... 937 938 #設置環境變量(永久) 939 $oldPersonalPath = ";d:\tools" 940 [Environment]::SetEnvironmentVariable("Path",$oldPersonalPath,"User") 941 [Environment]::GetEnvironmentVariable("Path","User") #;d:\tools 942 943 944 #閱讀 rss 945 $sapi = New-Object -Com Sapi.SpVoice 946 $WebClient = New-Object System.Net.WebClient 947 $WebClient.Encoding=[System.Text.Encoding]::UTF8 948 $rss = [XML]($WebClient.DownloadString("http://weather.qq.com/zixun/rss_fyzx.xml")) 949 foreach($item in $rss.rss.channel.Item){ 950 $title = $item.title 951 #$title = $item.title.InnerText 952 $content = $item.description 953 #$content = $item.description.InnerText 954 #$content = $item.description.InnerText.Replace(" ","") 955 $title 956 $sapi.Speak($title+"。") 957 $content 958 $sapi.Speak($content+"。。") 959 }