2013-04-11 43 views
0
get-command | where-object { $_.commandtype -eq "cmdlet" } | sort-object -property name | select-object -property name | where-object { $_.name -match "^get" } | out-file "getcommands.txt" 

$content = get-content "getcommands.txt" 

$content | Foreach-Object { $_.TrimEnd() } | where { $_ -match "\w" } | Out-File "getcommands.txt" -encoding Ascii 

compare-object -referenceobject $(Get-Content "oldcommands.txt") -differenceobject $(Get-Content "getcommands.txt") -includeequal 

該代碼檢索所有以「get」開頭的cmdlet,並將它們與文本文件中的列表進行比較。它也消除了超額回報和空白,所以比較實際的作品。如何優化所有這些管道?

一切正常,但很難閱讀。我剛學習如何編寫PowerShell腳本,因此我不確定如何用更優雅的代碼完成相同的任務。

我敢打賭,有一種方法可以做到這一點,沒有所有的管道。我也無法從第一行代碼輸出到一個文本文件沒有一大堆額外的空間和返回。

回答

1

我覺得這做同樣的:

get-command -CommandType "cmdlet" -name get* | SELECT -expand name | 
out-file "getcommands.txt" -encoding Ascii 

compare-object -referenceobject (Get-Content "oldcommands.txt") -differenceobject (Get-Content "getcommands.txt") -includeequal 
+0

我有一個優化添加:)使用名詞參數: - 獲取 – 2013-04-11 19:16:53

+0

@ShayLevy是'-verb get';)但我認爲這也返回函數和動詞的別名得到 – 2013-04-11 19:27:45

+0

不應該是'-Verb Get'? – alroc 2013-04-11 19:31:04

-1

篩選的cmdlet在與-verb源列表。最好的做法是儘可能多的,你可以(最靠近數據源)過濾器在管道上的左側

get-command -verb get |where-object{$_.CommandType -eq "Cmdlet"}|select-object -expandpropertyproperty name|out-file getcommands.txt -encoding ascii 
compare-object -referenceobject $(Get-Content "oldcommands.txt") -differenceobject $(Get-Content "getcommands.txt") -includeequal 

應該是與-CommandType參數消除Where-Object還有一種方式爲get-command,但我不能在這裏工作。我希望下面的工作之一,但同樣沒有:

get-command -verb get -CommandType Cmdlet 
get-command -verb get -CommandType [system.management.automation.commandtypes]::Cmdlet 
+0

-1在我的答案中,消除了「Where-Object」來過濾-CommandType的方法,遵循了你所告訴的最佳做法。 – 2013-04-11 19:42:31

+0

顯然'-commandtype'和'-verb'不能一起使用。儘管我沒有在文檔中看到這一點。 – alroc 2013-04-11 19:46:11

+0

他們在不同的parameterSet名稱,這就是爲什麼我用'-name get *'過濾 – 2013-04-11 19:48:39

0

如果你有V3,這似乎只是有點快:

(get-command -CommandType "cmdlet" -name get*).name | 
set-content getcommands.txt