列出唯一文件擴展的代碼
- PS C:\Users\Administrator> Get-childitem | group-object extension | select-object name
- Name
- ----
- .VirtualBox
- .txt
- .ps1
- .pl
- .RND
Get-ChildItem
我把結果輸出到1.txt裏面
- PS C:\Users\Administrator>Get-childitem >> 1.txt
- 目錄: C:\Users\Administrator
- Mode LastWriteTime Length Name
- ---- ------------- ------ ----
- d---- 2012/11/13 15:24 .VirtualBox
- d-r-- 2012/10/18 16:50 Contacts
- d-r-- 2012/11/13 16:07 Desktop
- d-r-- 2012/11/5 10:07 Documents
- d-r-- 2012/11/13 16:48 Downloads
- d-r-- 2012/10/18 16:53 Favorites
- d-r-- 2012/10/18 16:50 Links
- d-r-- 2012/10/18 16:50 Music
- d-r-- 2012/10/30 17:08 Pictures
- d-r-- 2012/10/18 16:50 Saved Games
- d-r-- 2012/10/18 16:50 Searches
- d---- 2012/10/30 13:33 SysinternalsSuite
- d-r-- 2012/10/18 16:50 Videos
- d---- 2012/11/12 16:03 VirtualBox VMs
- d-r-- 2012/3/23 11:37 「開始」菜單
- d---- 2012/10/18 16:27 桌面
- -a--- 2012/11/14 9:14 4438 1.txt
- -a--- 2012/11/6 14:36 177 gespse.ps1
- -a--- 2012/11/5 11:14 909 new2.pl
- -a--- 2012/11/5 11:13 392 new3.pl
- -a--- 2012/11/9 8:51 600 PUTTY.RND
- -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開始被添加到這個數組中。例如:
- function foo
- {
- Write-Host $args[0] $args[1]
- }
- foo "This is parameter 1""This is parameter 2"
- PS C:\Users\Administrator> C:\Users\Administrator\ps.ps1
- This is parameter 1"This is parameter 2
名字參數
PowerShell輸入的參數也可以命名,這就意味着它們可以通過名字傳遞,並且值被放置在相應的變量裏。注意,當這個函數被調用的時候,參數顛倒,但是數值能正確返回。
- function foo
- {
- Param($param1,$param2)
- Write-Host $param1 $param2
- }
- foo -param2 "this is parameter 2" -param1 "this is parameter 1"
結果:
- PS C:\Users\Administrator> C:\Users\Administrator\ps.ps1
- this is parameter 1 this is parameter 2
splatting參數
在PowerShell的參數傳遞中,這個或許是最常用的方法。它包含創建一個數組或哈希表作爲傳遞給函數的參數組。這個讓你可以動態的創建整個腳本的參數,然後當你準備好後即可調用。
- function foo
- {
- Param($param1,$param2)
- Write-Host $param1 $param2
- }
- Create Hash Table
- $Blah=@{"Param1"="this is parameter 1";
- "Param2"="this is parameter 2"}
- #pass hasj table to function
- foo @Blsh
結果出錯了
- PS C:\Users\Administrator> C:\Users\Administrator\ps.ps1
- 無法將“Create”項識別爲 cmdlet、函數、腳本文件或可運行程序的名稱。請檢查名稱的拼寫,如果包括路徑,請確保路徑正確,然後重試。
- 所在位置 C:\Users\Administrator\ps.ps1:7 字符: 9
- + Create <<<< Hash Table
- + CategoryInfo : ObjectNotFound: (Create:String) [], CommandNotFoundException
- + FullyQualifiedErrorId : CommandNotFoundException
PowerShell參數的屬性
Mandatory 這個屬性在powershell參數選項裏是默認的,但是如果你知道你需要的參數類型,你可以使用這個屬性來強制用戶傳遞這種類型的參數。如果它們沒有這樣做,powershell將報錯給它們,並且強迫的它們提供這種類型的值,以便函數能夠正常的運行。
- function foo
- {
- Param(
- [Parameter(Mandatory=$True)]
- $param1
- )
- Write-Host $param1
- }
ParameterSetName 我們常常需要一起傳遞一組參數(通常因爲一些意外所中斷)。例如,你有一個函數要獲得一個活動目錄對象,如果它是一個用戶或是一個計算機,你就需要知道賬戶:
- function Get-ADObject
- {
- Param(
- [Parameter(Mandatory=$True,
- ParameterSetName="User")]
- $User,
- [Parameter(Mandatory=$True,
- ParameterSetName="Computer")]
- $Computer
- )
- $PScmdlet.ParameterSetName
- }
- # Get-ADObject -#this will throw an error because no parameters passed
- Get-ADObject -user "joe" #will return 'user'
- Get-ADObject -Computer "joe" #will return 'computer'
- # Get-ADObject -User "joe" -Computer "joe" #will return an error
ValueFromPipeline 這個屬性告訴函數某個特定的參數值可以通過管道來傳遞參數。
- function Get-ADUserObject
- {
- Param(
- [Parameter(ValueFormPipeline=$true)]
- $User,
- )
- Process
- {
- $user
- }
- }
- $ListofUsers | Get-ADUserObject
這個運行有問題
ValueFromPipeLineByPropertyName 這個屬性不是使用類型,它使用的是傳入對象的屬性名稱。例如,如果你有一個叫做UserName的用戶對象屬性。
- function Get-ADUserObject
- {
- Param(
- [Parameter(ValueFromPipelineByPropertyName=$true)]
- $Username,
- )
- Process
- {
- $UserName
- }
- }
- $ListofUserObjects | Get-ADUserObject
跟前面那個錯誤差不多
- PS C:\Users\Administrator> C:\Users\Administrator\ps.ps1
- “,”後缺少表達式。
- 所在位置 C:\Users\Administrator\ps.ps1:5 字符: 17
- + $Username, <<<<
- + CategoryInfo : ParserError: (,:OperatorToken) [], ParentContainsErrorRecordException
- + FullyQualifiedErrorId : MissingExpressionAfterToken
HelpMessage 這允許你給用戶添加一個幫助信息。如果它們沒有指定mandatory屬性來調用你的函數,這可以給它們解釋需要輸入用戶名:
- function Get-ADComputerObject
- {
- Param(
- [Parameter(Mandatory=$True,HelpMessage= "Enter computer name.")]
- $ComputerName,
- )
- $ComputerName
- }
原文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}
- PS C:\Users\Administrator> get-help write-host
- 名稱
- Write-Host
- 摘要
- 將自定義的輸出內容寫入主機。
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