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

powershell命令教程的更多相关文章

  1. PowerShell 在线教程 4

    PowerShell 在线教程 4   认识Powershell 介绍和安装 自定义控制台 快速编辑模式和标准模式 快捷键 管道和重定向 Powershell交互式 数学运算 执行外部命令 命令集 别 ...

  2. PowerShell使用教程

    一.说明 1.1 背景说明 个人对PowerShell也不是很熟悉,开始的时候就突然看到开始菜单中多了个叫PowerShell的文件夹,后来一点就看到某个教程视频说PowerShell很厉害但也没怎么 ...

  3. powershell入门教程-v0.3版

    powershell入门教程-v0.3版 来源 https://www.itsvse.com/thread-3650-1-1.html 参考 http://www.cnblogs.com/piapia ...

  4. SharePoint 2013 PowerShell命令备份还原报错

    错误截图: 文字描述: Restore-SPSite : <nativehr>0x80070003</nativehr><nativestack></nati ...

  5. 解决PowerShell命令行窗口中不显示光标的问题

    不知道什么原因,在有些系统上打开PowerShell命令行窗口后,光标无法显示.这种情况在Windows Server 2008/2012.Windows 8/9/10上都出现过,估计是由于某些系统软 ...

  6. 【转】PowerShell入门(五):Cmd命令与PowerShell命令的交互

    转至:http://www.cnblogs.com/ceachy/archive/2013/02/18/Call_Between_Cmd_And_PowerShell.html 单独使用一种脚本来完成 ...

  7. powershell命令大全

    Name Category Synopsis ---- -------- -------- ac Alias Add-Content asnp Alias Add-PSSnapin clc Alias ...

  8. Make 命令教程 -- 阮一峰

    摘自http://www.ruanyifeng.com/blog/2015/02/make.html Make 命令教程 作者: 阮一峰 日期: 2015年2月20日 代码变成可执行文件,叫做编译(c ...

  9. linux版powershell安装教程(.net core版)

    powershell 传教士 原创文章 始于2016-12-20,2017-03-15改.文章版本目前博客园为最新版. 允许转载,但必须保留名字和出处,否则追究法律责任 问:powershell二进制 ...

随机推荐

  1. v-cloak 的用法

    https://blog.csdn.net/knqiufan/article/details/81002957

  2. 12 Windows编程——子窗口和系统内置窗口类“BUTTON”

    创建子窗口类,使得子窗口有自己的处理过程. 子窗口类型WS_CHILD不能和WS_POPUP一起使用!为什么子窗口要有自己的处理过程?如果使用主窗口类来创建子窗口,那么子窗口和主窗口将公用窗口处理过程 ...

  3. php中unserialize 返回false的解决方法

    serialize 序列化 unserialize 反序列化 $content = 'a:5:{s:4:"img1";s:5:"35568";s:4:" ...

  4. 【python】使用plotly生成图表数据

    安装 在 ubuntu 环境下,安装 plotly 很简单 python 版本2.7+ pip install plotly 绘图 在 plotly 网站注册后,可以直接将生成的图片保存到网站上,便于 ...

  5. Python sleep()函数用法:线程睡眠

    如果需要让当前正在执行的线程暂停一段时间,并进入阻塞状态,则可以通过调用 time 模块的 sleep(secs) 函数来实现.该函数可指定一个 secs 参数,用于指定线程阻塞多少秒. 当前线程调用 ...

  6. c++代码中“引用”的使用

    这些上机实验在Qt5.9上完成的,具体步骤 结构体引用 #include <iostream> #include<stdlib.h> using namespace std; ...

  7. Java8-Lambda-No.01

    import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util ...

  8. 04_mysql安装

    # 安装 [root@localhost ~]# yum install mysql mysql-server -y 报错 [root@ossec-server ~]# yum install mys ...

  9. Razor传值到js

    1.Asp.net MVC 3 中Session与ViewBag传值到Js中 http://www.cnblogs.com/wintersun/archive/2012/06/04/2534975.h ...

  10. vue中setInterval的清除

    两种清除setInterval的方式: 方案一: data() { return { timer: null // 定时器名称 } }, mouted() { this.timer = (() =&g ...