PowerShell實用教程

 

列出唯一文件擴展的代碼

 

  1. PS C:\Users\Administrator> Get-childitem | group-object extension | select-object name 
  2. Name                                                                                                                                                                                                           
  3. ----                                                                                                                                                                                                           
  4. .VirtualBox                                                                                                                                                                                                                   
  5. .txt                                                                                                                                                                                                           
  6. .ps1                                                                                                                                                                                                           
  7. .pl                                                                                                                                                                                                            
  8. .RND    

Get-ChildItem

我把結果輸出到1.txt裏面

  1.   PS C:\Users\Administrator>Get-childitem >> 1.txt
  2.    目錄: C:\Users\Administrator  
  3. Mode                LastWriteTime     Length Name                                                                       
  4. ----                -------------     ------ ----                                                                       
  5. d----        2012/11/13     15:24            .VirtualBox                                                                
  6. d-r--        2012/10/18     16:50            Contacts                                                                   
  7. d-r--        2012/11/13     16:07            Desktop                                                                    
  8. d-r--         2012/11/5     10:07            Documents                                                                  
  9. d-r--        2012/11/13     16:48            Downloads                                                                  
  10. d-r--        2012/10/18     16:53            Favorites                                                                  
  11. d-r--        2012/10/18     16:50            Links                                                                      
  12. d-r--        2012/10/18     16:50            Music                                                                      
  13. d-r--        2012/10/30     17:08            Pictures                                                                   
  14. d-r--        2012/10/18     16:50            Saved Games                                                                
  15. d-r--        2012/10/18     16:50            Searches                                                                   
  16. d----        2012/10/30     13:33            SysinternalsSuite                                                          
  17. d-r--        2012/10/18     16:50            Videos                                                                     
  18. d----        2012/11/12     16:03            VirtualBox VMs                                                             
  19. d-r--         2012/3/23     11:37            「開始」菜單                                                                     
  20. d----        2012/10/18     16:27            桌面                                                                         
  21. -a---        2012/11/14      9:14       4438 1.txt                                                                      
  22. -a---         2012/11/6     14:36        177 gespse.ps1                                                                 
  23. -a---         2012/11/5     11:14        909 new2.pl                                                                    
  24. -a---         2012/11/5     11:13        392 new3.pl                                                                    
  25. -a---         2012/11/9      8:51        600 PUTTY.RND                                                                  
  26. -a---         2012/11/2     10:47          0 rocks.txt.txt    

Get-ChildItem是一個內置的cmdlet,列出給定路徑裏的文件和文件夾。

Group-Object這個命令可以收集對象,並通過特性進行分類,

可以用Get-Help Group-Object查看詳細解釋,用Get-Help Group-Object -examples查看詳細的例子。

Select-Object這個命令允許你調出你想保存的對象。

PowerShell的函數參數

PowerShell中最大的特點之一是函數的可擴展性強。

位置參數

    PowerShell可以創建一個數值數組傳遞給函數的$args變量。傳遞給函數的每一個值從0開始被添加到這個數組中。例如:

  1. function foo 
  2.     Write-Host $args[0] $args[1] 
  3. foo "This is parameter 1""This is parameter 2" 
 
  1. PS C:\Users\Administrator> C:\Users\Administrator\ps.ps1 
  2. This is parameter 1"This is parameter 2 

名字參數

    PowerShell輸入的參數也可以命名,這就意味着它們可以通過名字傳遞,並且值被放置在相應的變量裏。注意,當這個函數被調用的時候,參數顛倒,但是數值能正確返回。

  1. function foo 
  2.   Param($param1,$param2) 
  3.   Write-Host $param1 $param2 
  4.  } 
  5.  foo -param2 "this is parameter 2" -param1 "this is parameter 1" 

結果:

  1. PS C:\Users\Administrator> C:\Users\Administrator\ps.ps1 
  2. this is parameter 1 this is parameter 2 

splatting參數

    在PowerShell的參數傳遞中,這個或許是最常用的方法。它包含創建一個數組或哈希表作爲傳遞給函數的參數組。這個讓你可以動態的創建整個腳本的參數,然後當你準備好後即可調用。

  1. function foo 
  2.  { 
  3.   Param($param1,$param2) 
  4.   Write-Host $param1 $param2 
  5.   } 
  6.    
  7.   Create Hash Table 
  8.   $Blah=@{"Param1"="this is parameter 1"; 
  9.   "Param2"="this is parameter 2"} 
  10.    
  11.   #pass hasj table to function  
  12.   foo @Blsh 

結果出錯了

  1. PS C:\Users\Administrator> C:\Users\Administrator\ps.ps1 
  2. 無法將“Create”項識別爲 cmdlet、函數、腳本文件或可運行程序的名稱。請檢查名稱的拼寫,如果包括路徑,請確保路徑正確,然後重試。 
  3. 所在位置 C:\Users\Administrator\ps.ps1:7 字符: 9 
  4. +   Create <<<<  Hash Table 
  5.     + CategoryInfo          : ObjectNotFound: (Create:String) [], CommandNotFoundException 
  6.     + FullyQualifiedErrorId : CommandNotFoundException 

PowerShell參數的屬性

    Mandatory 這個屬性在powershell參數選項裏是默認的,但是如果你知道你需要的參數類型,你可以使用這個屬性來強制用戶傳遞這種類型的參數。如果它們沒有這樣做,powershell將報錯給它們,並且強迫的它們提供這種類型的值,以便函數能夠正常的運行。

  1. function foo 
  2.   Param( 
  3.         [Parameter(Mandatory=$True)] 
  4.         $param1 
  5.        ) 
  6.      Write-Host $param1 
  7.  } 

ParameterSetName   我們常常需要一起傳遞一組參數(通常因爲一些意外所中斷)。例如,你有一個函數要獲得一個活動目錄對象,如果它是一個用戶或是一個計算機,你就需要知道賬戶:

  1. function Get-ADObject 
  2.    Param( 
  3.       [Parameter(Mandatory=$True, 
  4.       ParameterSetName="User")] 
  5.       $User, 
  6.        
  7.       [Parameter(Mandatory=$True, 
  8.       ParameterSetName="Computer")] 
  9.       $Computer 
  10.       ) 
  11.       $PScmdlet.ParameterSetName 
  12.       } 
  13.        
  14.    #   Get-ADObject -#this will throw an error because no parameters passed 
  15.       Get-ADObject -user "joe" #will return 'user' 
  16.       Get-ADObject -Computer "joe" #will return 'computer' 
  17.    #   Get-ADObject -User "joe" -Computer "joe" #will return an error 

ValueFromPipeline  這個屬性告訴函數某個特定的參數值可以通過管道來傳遞參數。

  1. function Get-ADUserObject 
  2.    Param( 
  3.       [Parameter(ValueFormPipeline=$true)] 
  4.       $User, 
  5.         ) 
  6.       Process 
  7.        { 
  8.         $user 
  9.         } 
  10.        } 
  11.         
  12.       $ListofUsers | Get-ADUserObject 

這個運行有問題

ValueFromPipeLineByPropertyName  這個屬性不是使用類型,它使用的是傳入對象的屬性名稱。例如,如果你有一個叫做UserName的用戶對象屬性。

  1. function Get-ADUserObject 
  2.    Param( 
  3.       [Parameter(ValueFromPipelineByPropertyName=$true)] 
  4.       $Username, 
  5.       ) 
  6.       Process 
  7.       { 
  8.          $UserName 
  9.        } 
  10.      } 
  11.      $ListofUserObjects | Get-ADUserObject 

跟前面那個錯誤差不多

  1. PS C:\Users\Administrator> C:\Users\Administrator\ps.ps1 
  2. “,”後缺少表達式。 
  3. 所在位置 C:\Users\Administrator\ps.ps1:5 字符: 17 
  4. +       $Username, <<<<  
  5.     + CategoryInfo          : ParserError: (,:OperatorToken) [], ParentContainsErrorRecordException 
  6.     + FullyQualifiedErrorId : MissingExpressionAfterToken 

HelpMessage  這允許你給用戶添加一個幫助信息。如果它們沒有指定mandatory屬性來調用你的函數,這可以給它們解釋需要輸入用戶名:

  1. function Get-ADComputerObject 
  2.    Param( 
  3.       [Parameter(Mandatory=$True,HelpMessage"Enter computer name.")] 
  4.       $ComputerName, 
  5.       ) 
  6.       $ComputerName 
  7.     } 

原文http://searchsv.techtarget.com.cn/showcontent_39722.htm?lg=t

Windows PowerShell五大Cmdlet命令

Function--- 與cmdlet非常類似,除了他們是使用關鍵工作“功能”產生的意外。

例如function foo {"I'm Foo"}

Parameter---  cmdlet或function的值。

Object ---從cmdlet或function返回的條目。對象擁有的屬性和行爲,。。。

Propertie---描述對象用到的屬性。

Method---對象執行的動作。

Variable---用於存儲數據的對象。

Pipeline---這個指從一個命令傳輸對象到另一個概念,通過管道操作符來完成。

Aliase---給用戶提供縮寫cmdlet的能力。

ScriptBlock---包含在"{"and"}"裏的一塊代碼。

例如:{Write-Host "This is a ScriptBlock"}

現在我們來分解重要的cmdlet。括號裏面的字符表示每個cmdlet的縮寫。

 Get-Help(help:)---有三個參數,控制返回數據的數量:Detail,Full,Example

語句:Get-Help

例子:Get-Help Get-Member

Get-Member(gm:)---它允許你發現給定對象擁有的屬性和行爲。畢竟,如果不知道屬性在哪,你不能準確適用。

 語句:<object> | get-member

 例子: Get-Childitem | Get-Member

Get-Command(gcm:)---Get-Command僅僅提供命令。這些命令可以是cmdlet,funciton,aliase,application。

語句:Get-Command -commandtype <type>

例子:Get-Command -commandtype cmdlet

Foreach-Object(%:)---這個條目用於處理管道里的條目。對於管道里的每個對象,這個命令將處理腳本

語句:<object(s)> | foreach-object <scriptblock>

例子:Get-ChildItem | foreach-object {Write-Host "Found: "$-.fullname}

  1. PS C:\Users\Administrator> get-help write-host 
  2. 名稱 
  3.     Write-Host 
  4. 摘要 
  5.     將自定義的輸出內容寫入主機。 

 Where-Object(?:)---這個類似於Foreach-Object,但它不是簡單處理腳本塊,而是將腳本塊作爲某種過濾器使用。如果腳本塊的結果是$true,對象可以傳輸。如果結果是$false,當前腳本將被丟棄。

語句:<object(s)> | where-object <scriptblock>

例子:Get-ChildItem | where-object {$_.Length -gt 10mb} 

管理員常用的25個powershell命令

入門級別

1、像文件系統那樣操作Windows Registry---cd hkcu:

2、在文件裏遞歸的搜索某個字符串---dir -r | select string "searchforthis"

3、使用內存找到五個進程---ps | sort -p ws | select -last 5

4、循環(停止,然後重啓)一個服務,如DHCP---Restart-Service DHCP

5、在文件夾裏列出所有條目---Get-ChildItem -Force

6、遞歸-系列的目錄或文件夾---Get-ChildItem -Force c:\directory -Recurse

7、在目錄裏移除所有文件而不需要單個移除---Remove-Item c:\tobedeleted -Recurse

8、重啓當前計算機---(Get-WinObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(2)

收集信息

9、獲取計算機組成或模型信息---Get-WmiObject -Class Win32_ComputerSystem

10、獲取當前計算機BIOS信息---Get-WmiObject -Class Win32_BIOS -ComputerName.

11、列出所安裝的修復程序(如QFE或Windows Update文件)---Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName.

12、獲取當前登錄計算機的用戶的用戶名---Get-WmiObject -Class Win32_ComputerSystem -Property UserName -ComputerName.

13、獲取當前計算機所安裝的應用程序的名字---Get-WmiObject -Class Win32_Product -ComputerName . | Format-Wide -Column 1

14、獲取分配給當前計算機的IP地址---Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnable=TRUE -ComputerName . | Format-Table -Property IPAddress

15、獲取當前計算機詳細的IP配置報道---Get-WmiObject -Class Win32_NetworkadapterConfiguration -Filter IPEnable=TRUE -ComputerName . | Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*

16、找到當前計算機上使用DHCP啓用的網卡---Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "DHCPEnabled=true" -ComputerName .

17、在當前計算機上所有的網卡上啓用DHCP---Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName. | ForEach-Object -Process {$_.EnableDHCE()}

 軟件管理

18、在遠程計算機上安裝MSI包---(Get-WMIObject -ComputerName TARGETMACHINE -list | Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).Install(\\MACHINEWHEREMSIRESIDES\path\package.msi)

19、使用基於MSI的應用程序升級包升級所安裝的應用程序---(Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='name_of_app_to_be_updated'").Upgrade(\\MACHINEWHEREMSIRESIDES\path\upgrade_package.msi)

20、從當前計算機移除MSI包---(Get-WmiObject -Class Win32_Product -Filter "Name='product_to_remove'" -ComputerName.).Unistall()

機器管理

21、一分鐘後遠程關閉另一臺計算機---Start-Sleep 60;Restart-Computer -Force -ComputerName TARGETMACHINE

22、添加打印機---(New-Object -ComObject WScript.Network.AddWindowsPrinterConnection(\\printerserver\hpaser3)

25、移除打印機---(New-Object -ComObject WScript.Network).RemovePrintConnection("\\printerserver\hplaser3")

24、進入powershell回話---invoke-command -computername machine1,machine2 -filepath c:\script\script.ps1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章