如何优化所有这些管道?

时间:2013-04-11 18:57:00

标签: powershell pipe

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脚本,所以我不知道如何用更优雅的代码完成相同的任务。

我打赌如果没有所有的管道,有办法做到这一点。我也无法从第一行代码输出到输出到文本文件而没有一大堆额外的空格和返回。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

如果你有V3,这似乎更快一点:

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

答案 2 :(得分:-1)

使用-verb过滤源位置的cmdlet列表。最佳做法是尽可能多地过滤管道左侧(最接近数据源)

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

一种消除Where-Object以及-CommandType的{​​{1}}参数的方法,但我无法在此处使用它。我希望以下其中一项能够奏效,但两者都没有:

get-command
相关问题