Powershell 如何优化所有这些管道?

Powershell 如何优化所有这些管道?,powershell,pipe,Powershell,Pipe,此代码检索所有以“get”开头的cmdlet,并将它们与文本文件中的列表进行比较。它还删除了多余的返回和空白,因此比较实际上是有效的 一切都正常,但它很难阅读。我只是在学习如何编写PowerShell脚本,因此我不确定如何使用更优雅的代码完成相同的任务 我打赌有一种方法可以在没有所有管道的情况下做到这一点。我也无法在没有大量额外空格和返回的情况下将第一行代码的输出结果输出到文本文件。我认为这也可以做到: get-command | where-object { $_.commandtype -e

此代码检索所有以“get”开头的cmdlet,并将它们与文本文件中的列表进行比较。它还删除了多余的返回和空白,因此比较实际上是有效的

一切都正常,但它很难阅读。我只是在学习如何编写PowerShell脚本,因此我不确定如何使用更优雅的代码完成相同的任务


我打赌有一种方法可以在没有所有管道的情况下做到这一点。我也无法在没有大量额外空格和返回的情况下将第一行代码的输出结果输出到文本文件。

我认为这也可以做到:

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

使用
-verb
筛选源位置的cmdlet列表。最佳实践是在管道左侧(最靠近数据源)尽可能多地进行过滤

应该有一种方法可以消除
Where对象
以及
get命令
-CommandType
参数,但我无法让它在这里工作。我希望以下其中一项能起作用,但两者都不起作用:

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

如果您使用的是V3,那么这似乎要快一点:

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

我有一个优化添加:)使用名词参数:-名词Get@ShayLevy是
-动词get
;)但我认为这也会返回带有动词Get的函数和别名,这不应该是
-动词Get
?@ShayLevy出于我对你的尊重,我尝试了各种方式运行-Non,直到意识到你的意思是-verb!英雄联盟谢谢大家!我不知道怎么做,但是这种输出命令的方法在文本文件中没有额外的空白。-1我的答案中有一种方法,可以消除过滤-CommandType的
Where对象
,并遵循您所说的最佳实践。显然
-CommandType
-verb
不能一起使用。但是我在文档中没有看到这一点。它们位于不同的参数集名称中,这就是为什么我使用
-name get*
get-command -verb get -CommandType Cmdlet
get-command -verb get -CommandType [system.management.automation.commandtypes]::Cmdlet
(get-command -CommandType "cmdlet" -name get*).name |
set-content getcommands.txt