windows 7 PowerShell 笔记
轉(zhuǎn)自:http://lovephoenix.javaeye.com/blog/661380
對 powershell 做下總結(jié)
?
?
?啟動 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-MemberTypeName: System.StringName 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... ...#統(tǒng)計所有正在運行的進程的句柄數(shù) PS C:/> $handleCount=0 PS C:/> foreach($process in Get-process) { $handleCount +=$process.Handles } PS C:/> $handleCount 23318#直接調(diào)用donet對象,獲取網(wǎng)頁內(nèi)容 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#獲取系統(tǒng)信息 PS C:/> Get-WmiObject Win32_BiosSMBIOSBIOSVersion : 2TKT00AUS Manufacturer : LENOVO Name : Default System BIOS SerialNumber : 1111111 Version : LENOVO - 5000821#導(dǎo)航文件系統(tǒng) 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#導(dǎo)航注冊表 PS C:/> Set-Location HKCU:/Software/Microsoft/Windows/ PS HKCU:/Software/Microsoft/Windows/> Get-ChildItemHive: HKEY_CURRENT_USER/Software/Microsoft/WindowsSKC 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...#導(dǎo)航證書 PS C:/Users/vv> Set-Location cert:/CurrentUser/Root PS cert:/CurrentUser/Root> Get-ChildItem目錄: Microsoft.PowerShell.Security/Certificate::CurrentUser/RootThumbprint 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-ProcessHandles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- -----------527 28 40784 44864 243 18.94 4956 360SE537 29 49144 59340 248 9.09 5276 360SE924 20 17580 2504 132 3768 360tray160 5 16080 7852 41 2036 audiodg318 24 6524 7008 124 188 CCProxy56 5 796 288 33 1232 CNAB4RPK61 4 1568 6916 63 0.19 5064 conhost60 4 1532 3628 63 0.06 5584 conhost645 6 2076 1204 72 380 csrss649 9 8148 11056 185 440 csrss ......#搜索所有包含Get動詞的命令 PS C:/Users/vv> Get-Command -Verb GetCommandType 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#調(diào)用powershell腳本 PowerShell "& 'C:/get-report.ps1' arguments"#循環(huán) PS C:/Users/vv> 1..10 | % {"aaa"} aaa aaa aaa aaa aaa aaa aaa aaa aaa aaa#數(shù)據(jù)加密(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#檢查命令是否執(zhí)行成功 PS C:/Users/vv> $lastExitCode 0 PS C:/Users/vv> $? True#性能測試,計算一個命令執(zhí)行的時間 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 循環(huán) foreach($alias in Get-Alias){$alias }#顯示為表格 PS C:/Users/vv> Get-Process | Format-Table Name,WS -Auto#復(fù)制文件 Copy-Item c:/temp/*.txt c:/temp/backup/ -verbose#列出所有已經(jīng)停止的服務(wù) PS C:/Users/vv> Get-Service | Where-Object { $_.Status -eq "Stopped" } #列出當前位置的所有子目錄 PS C:/Users/vv> Get-ChildItem | Where-Object { $_.PsIsContainer }#循環(huán) 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() }#其它循環(huán)關(guān)鍵字 for foreach do while#從管道中選擇接收值 PS C:/Users/vv> dir | Select Name#釋放變量占用的內(nèi)存空間 $processes = $null#顯示所有變量 PS C:/> dir variable:/PS C:/> dir variable:/s*#顯示文件內(nèi)容 PS C:/> ${c:/autoexec.bat}#變量范圍 $Global:myVariable1 = value1 $Script:myVariable2 = value2 $Local:myVariable3 = value3#靜態(tài)方法 調(diào)用 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 IdleGet-Process Notepad #Get-Process 代替 System.Diagnostics.Process$process.WaitForExit() #暫停直到結(jié)束Get-Date 等同于 [System.DateTime]::Now#創(chuàng)建對象 PS C:/> $generator = New-Object System.Random PS C:/> $generator.NextDouble() 0.121309703738107PS 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.... #創(chuàng)建后保存 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#調(diào)用COM組件 $sapi = New-Object -Com Sapi.SpVoice $sapi.rate=0 $sapi.Speak("一直以為...只要隱著身,就沒有美女認得出我是帥哥!但是...我錯了,像我這樣拉風的男人,就好比那暗夜里的螢火蟲,田地里的金龜子,是那樣的鮮明,那樣的出眾,特別是我那憂郁的眼神,凌亂的頭發(fā),嘴里叼著四塊五的紅金龍,還有我兜里露出來的半包旺旺雪餅,深深地出賣了我。")#獲取對象類型 $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#邏輯運算關(guān)鍵字 -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"} }#循環(huán) #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#字符串 使用單引號表示原生字符串,不支持變量擴展或轉(zhuǎn)義字符 $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不必為后續(xù)的使用而繼續(xù)保留信息了#轉(zhuǎn)義字符 ` (不使用反斜杠) 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)" $myStringReport for today ----------------#格式化輸出 右對齊8個字符,格式為4為數(shù)字,: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.570003 ¥7.00#字符串方法 PS C:/Users/vv> "abc".IndexOf("b") 1PS 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.StringBuilder1..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.5372Measure-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#數(shù)學(xué)計算 $result = [int](3/2) $result 2#截斷 $result=3/2 [Math]::Truncate($result) 1function 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#統(tǒng)計 1..10 | Measure-Object -Average -SumCount : 10 Average : 5.5 Sum : 55 Maximum : Minimum : Property : Get-ChildItem > output.txt Get-COntent output.txt | Measure-Object -Character -Word -LineLines Words Characters Property ----- ----- ---------- -------- 28 117 2638 #從文件列表中取得LastWriteTime的平均值 $times = dir | Foreach-Object { $_.LastWriteTime } $results = $times | Measure-Object Ticks -Average New-Object DateTime $results.Average2009年12月11日 21:27:09#16進制數(shù) $hexNumber = 0x1234 $hexNumber 4660#16進制 轉(zhuǎn) 2進制 [Convert]::ToString(12341,2) 11000000110101#2進制轉(zhuǎn)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()#設(shè)置文件屬性 (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 -autoProperty 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#讀取文件內(nèi)容 $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.txtGet-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#內(nèi)容寫入到文件 $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 腳本 #下載一個文件 (參數(shù)錯誤?) $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 創(chuàng)建一個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#從腳本塊返回數(shù)據(jù) function GetDate {Get-Date } $tomorrow = (GetDate).AddDays(1)#數(shù)組 $myArray = 1,2,"aaa" $myArray 1 2 aaa#數(shù)組 基本操作 $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 $myArrayHandles 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) $myArrayHandles 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#訪問數(shù)組中的每一個元素 $myArray = 1,2,3 $sum = 0 $myArray | Foreach-Object {$sum+=$_} $sum 6#訪問數(shù)組中的每一個元素,更腳本化 $myArray = 1,2,3 $sum=0 foreach($element in $myArray){$sum+=$element} $sum 6#數(shù)組列表排序 Get-ChildItem | Sort-Object -Descending Length | Select Name, Length#檢查數(shù)組列表是否包含指定的項 "Hello","World" -contains "Hello"#合并數(shù)組 $array = 1,2 $array += 3,4#數(shù)組查詢 $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 }#參數(shù) 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")#環(huán)境變量#查看 $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 ......#設(shè)置環(huán)境變量(永久) $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+"。。") }
總結(jié)
以上是生活随笔為你收集整理的windows 7 PowerShell 笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PowerShell 调用dll
- 下一篇: 使用 Windows PowerShel