[PowerShell] PowerShell學習腳印

來源:互聯網
上載者:User
#別名ac = Add-Contentasnp = Add-PSSnapinclc = Clear-Contentcli = Clear-Itemclp = Clear-ItemPropertyclv = Clear-Variablecpi = Copy-Itemcpp = Copy-ItemPropertycvpa = Convert-Pathdiff = Compare-Objectepal = Export-Aliasepcsv = Export-Csvfc = Format-Customfl = Format-Listforeach = ForEach-Object% = ForEach-Objectft = Format-Tablefw = Format-Widegal = Get-Aliasgc = Get-Contentgci = Get-ChildItemgcm = Get-Commandgdr = Get-PSDriveghy = Get-Historygi = Get-Itemgl = Get-Locationgm = Get-Membergp = Get-ItemPropertygps = Get-Processgroup = Group-Objectgsv = Get-Servicegsnp = Get-PSSnapingu = Get-Uniquegv = Get-Variablegwmi = Get-WmiObjectiex = Invoke-Expressionihy = Invoke-Historyii = Invoke-Itemipal = Import-Aliasipcsv = Import-Csvmi = Move-Itemmp = Move-ItemPropertynal = New-Aliasndr = New-PSDriveni = New-Itemnv = New-Variableoh = Out-Hostrdr = Remove-PSDriveri = Remove-Itemrni = Rename-Itemrnp = Rename-ItemPropertyrp = Remove-ItemPropertyrsnp = Remove-PSSnapinrv = Remove-Variablervpa = Resolve-Pathsal = Set-Aliassasv = Start-Servicesc = Set-Contentselect = Select-Objectsi = Set-Itemsl = Set-Locationsleep = Start-Sleepsort = Sort-Objectsp = Set-ItemPropertyspps = Stop-Processspsv = Stop-Servicesv = Set-Variabletee = Tee-Objectwhere = Where-Object? = Where-Objectwrite = Write-Outputcat = Get-Contentcd = Set-Locationclear = Clear-Hostcp = Copy-Itemh = Get-Historyhistory = Get-Historykill = Stop-Processlp = Out-Printerls = Get-ChildItemmount = New-PSDrivemv = Move-Itempopd = Pop-Locationps = Get-Processpushd = Push-Locationpwd = Get-Locationr = Invoke-Historyrm = Remove-Itemrmdir = Remove-Itemecho = Write-Outputcls = Clear-Hostchdir = Set-Locationcopy = Copy-Itemdel = Remove-Itemdir = Get-ChildItemerase = Remove-Itemmove = Move-Itemrd = Remove-Itemren = Rename-Itemset = Set-Variabletype = Get-Content#PSDrivealiascertenvfunctionhkcuhklmvariable#擷取協助help get*help *processhelp dirhelp dir -fullhelp dir -detailedhelp dir -exampledir -?#逸出序列   `0      //空值   `a      //Beep   `b      //退格   `f      //換頁   `n      //新行   `r      //斷行符號   `t      //定位字元   `v      //垂直引號   ``      // "`"#數字常量   1kb     // 1024   1mb   1gb   1e3     // 1000   0xFFFF  // 65535#編輯指令碼,推薦使用PrimalScript的最新版本,非常強大#設定指令碼安全性原則set-executionpolicy Restricted#預設set-executionpolicy AllSigned#部署set-executionpolicy RemoteSigned#開發set-executionpolicy Unrestricted#不推薦#執行指令碼必須帶路徑./myScript.ps1#擷取基於使用者名稱和密碼的憑據對象$cert = get-credential#對指令碼簽名$cert = Get-PfxCertificate C:\Test\Mysign.pfxSet-AuthenticodeSignature myScript.ps1 -cert $cert#作業系統gwmi win32_operatingsystem#自動變數$Args #傳遞進函數的參數$_ #通過管道傳入的對象$input  #通過管道傳入的對象集合$$      #前一命令列的最後一個標記$?      #上一命令的布爾狀態$^      #前一命令列的第一個標記$Matches #使用 –match 運算子找到的匹配項的雜湊表$Error[0] #前一次錯誤$Home   #使用者的主目錄$Host   #引用宿主 POWERSHELL 語言的應用程式$LastExitCode #上一程式或指令碼的結束代碼$PSHome #Windows PowerShell 的安裝位置$profile #標準設定檔(可能不存在)$StackTrace #Windows PowerShell 捕獲的上一異常#類型   空類型       [void]    數實值型別       [byte]        typeof(byte)        [decimal]     typeof(decimal)        [double]      typeof(double)        [float]       typeof(float)        [int]         typeof(int)        [long]        typeof(long)        [single]      typeof(float)    字元類型       [char]        typeof(char)        [string]      typeof(string)    布爾類型       [bool]        typeof(bool)    集合類型       [array]       typeof(System.Array)                      typeof(System.Object[])        [hashtable]   typeof(System.Collections.Hashtable)    其它       [psobject]    typeof(System.Management.Automation.PSObject)        [ref]         typeof(System.Management.Automation.PSReference)        [regex]       typeof(System.Text.RegularExpressions.Regex)        [scriptblock] typeof(System.Management.Automation.ScriptBlock)        [switch]      typeof(System.Management.Automation.SwitchParameter)        [type]        typeof(System.Type)        [wmi]         typeof(System.Management.ManagementObject)        [wmiclass]    typeof(System.Management.ManagementClass)        [wmisearcher] typeof(System.Management.ManagementObjectSearcher)        [xml]         typeof(System.Xml.XmlDocument)example:#[void][void] $var#可以阻止$var輸出#[xml]$var = [xml] "onetwo3"$var.top$var.top.a$var.top.a = "13"#自訂函數function writeln([string] $str) { echo $str }function writeln([string] $str) { Begin {echo "Begin"} Process {echo $str} End {echo "End"} }function writeln { param ([string] $str = $(throw "missing parameter")); echo $str }${function:writeln} = { param ([string] $str = $(throw "missing parameter")); echo $str }#文字檔讀寫${C:\test.txt} = "Hello`r`n"${C:\test.txt} += "-----------------"$Line1 = ${C:\test.txt}[0]# $null$var = $null#刪除$vardir > $null$null = dir#Invoke$method = "ToUpper""abc".$method.Invoke()#布爾值$true$false#where, select等的用法cd c:\dir | where {$_.Name -eq "WINDOWS"} | select Length,Namedir | ? {$_.Name -eq "WINDOWS"}# 列出字串對象"str"的所有屬性與方法"str" | gm#強制類型變數[Boolean] $condition = 0[string] $str = "hello"#數組$array = 1,2,3,4,5,6,7,8$array = @(1,2,3,4,5,6,7,8)$array[-1]#最後一個元素$array[0..4]$array[-1..-8]#倒序#雜湊表$hash = @{"Name"="Icebird"; "Job"="Engineer"}#如何取得文本的行數(type C:\test.txt | measure-object).Count#從控制台讀取一行輸入$var = Read-Host#擷取環境變數$path = $env:Path#讀取註冊表$a = (gp "hklm:\\Software\Microsoft\Windows\CurrentVersion").ProductId#比較和運算-like"file.doc" -like "file.*"-notlike-contains1,2,3 -contains 1-notcontains-----------------------------------eq= (忽略大小寫)-ieq= (忽略大小寫)-ceq= (不忽略大小寫)-ne!=-gt>-lt<-ge>=-le<=以上操作符也可用於對數組操作:1,2,3,5,3,2 -lt 3-----------------------------------and-or-not!等價於-not-xor%模運算*可用於字串重複: "-" * 80#位操作-band-bor-bnot-bxor#特殊操作$a = "Hat"$a -replace "a","o"$a -is [string]$a = 1 -as [string]$b = @(1..5)"{0:d}" -f (get-date)"{0:yyyy-MM-dd}" -f (get-date)#格式化$a = 123456789.456789$a.ToString("F4")"{0:F4}" -f $a"{0,-20:F4}{1}" -f $a,0"{0,20:F4}" -f $a"{0:x}" -f 100000"{0:X}" -f 100000#Regex$regex = [regex]"He"$str = "Hello, Hello"$isMatch = $str -match $regex$isMatch = $regex.ismatch($str)$matches = $regex.matches($str)#雙引號與單引號$a = 1;"$a"會輸出1'$a'會輸出$a# & 與 ..{$var = 1}#看作include&{$var = 1}#看作call&"dir"#意味著函數名之類的可以當作參數傳入#foreachforeach ($file in dir) { $file.Name }dir | % { $_.Name }#forfor ($i = 1; $i -lt 5; $i++) {echo $i}#while$i = 0while ($i -lt 4) { $i++; $i }#do...while$i = 10do {$i--; $i} while ($i -lt 5)#do...until$i = 10do {$i--; $i} until ($i -lt 5)#if...else[if]$obj = "Hello"if ($obj -is [string]) { "ISSTRING" }if ($obj -is [string]) { "ISSTRING" } else { "ISNOTSTRING" }if ($obj -is [string]) { "ISSTRING" } elseif ($obj -is [int]) { "ISINTEGER" }#switchswitch (1,2,3) { 1 {"a"} 2 {"b"} 3 {"c"} default {"?"} }switch (1) { "a" {"China"} "b" {"Japan"} "c" {"c"} default {"???"} }#switch -regex$var = "abcdefg"switch -regex($var) {"^\w+$" {echo $_" is a word"}"^\d+$" {echo $_" is a number"}"^\s+$" {echo $_" is a space"}default {echo "?"}}#switch -casesensitive#switch -wildcard#switch -extract?怎麼用#switch -file?怎麼用#拋出錯誤&捕獲異常throw "Error"raised "Exception"trap{  write-host "Error: " $_.Exception.Message#$_.TargetObject#$_.CategoryInfo#$_.FullyQualifiedErrorID#$_.ErrorDetails#$_.InvocationInfo  continue#break#return}#輸出格式化Format-ListFormat-TableFormat-WideFormat-Customdir | format-table -groupby Modedir | sort Name -descdir | sort Name -desc | select Name,Length,Mode | export-csv C:\dir.csvdir | sort Name -desc | select Name,Length,Mode | export-clixml C:\dir.csvdir | convertto-html#使用.NET的對象$webclient = New-Object System.Net.WebClient$webclient.Encoding = [System.Text.Encoding]::UTF8$url = "http://www.cnblogs.com/rss"$data = [string]$webclient.downloadstring($url)#使用COM對象$spVoice = new-object -com "SAPI.spvoice"$spVoice.Speak("Hello, I am Icebird.")

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.