powershell命令教程

  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("&nbsp","")
955     $title
956     $sapi.Speak($title+"")
957     $content
958     $sapi.Speak($content+"。。")
959 }

 

posted @ 2019-02-27 20:12  Vicen  阅读(1780)  评论(0编辑  收藏  举报