Get-Command:一个命令 - 两个使用场景 - 意外地两个非常不同的结果

时间:2015-10-20 15:36:04

标签: powershell powershell-v5.0

根据使用方法的不同,使用相同的命令会得到两个不同的结果。我正在使用PowerShell第5版。

按照预期在控制台中输入以下内容,我会得到PSReadline模块中可用命令的简短列表。

gcm -module psreadline

然而,当我使用下面的脚本尝试相同时,我会得到一个很长的TMI列表。

该脚本只列出所有已加载的模块,然后应用与上面相同的命令,但这次是通过指定模块名称的用户输入应用的。

任何人都可以使下面的脚本只输出上面命令的简短命令列表吗?

用于测试此模块的模块可以是另一个模块 - 不必是psreadline。

提前致谢。

# List loaded modules & get commands for a module specified by the user via user input:

cls
write-host "`n`n`n"
write-host " Loaded Modules: " -f darkblue -b white
write-host "`n`n"
get-module
write-host "`n`n"
$strString = " Get commands for a module  "
write-host $strString -f darkblue -b white
write-host "`n`n`n"
$input=Read-Host " Enter module name:   " ;
gcm -module $input

1 个答案:

答案 0 :(得分:3)

当对象写入控制台时,PowerShell首先尝试应用基于类型的格式化 - 您可以使用Get-Help about_Format.ps1xml阅读有关此主题的更多信息。

写入多个对象时,格式化仅适用于一种类型 - 通常是第一种非基本类型 - 另一种类型的任何其他对象将通过Format-List传送,这就是为什么你看到比预期更多的输出。

考虑以下示例:

PS C:\> @(Get-Service)[0],@(Get-Process)[0]
Status   Name               DisplayName
------   ----               -----------
Stopped  AService           A Service

Id      : 2816
Handles : 264
CPU     : 1.078125
Name    : ApplicationFrameHost

自动格式应用于Get-Service的输出,但不是Get-Process

但是,如果我们重新订购它们:

PS C:\> @(Get-Process)[0],@(Get-Service)[0]

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    264      22    17548      20988 ...25     1.08   2816 ApplicationFrameHost

Status      : Stopped
Name        : AService
DisplayName : A Service

Get-Process现在“首先出门”,格式化应用于该输出类型,但不是其他不同类型的后续对象

由于您已在Get-Module之前调出Get-Command,因此上述情况适用于您的情况。

您可以通过管道连接到Format-* cmdlet:

来自行控制输出格式
Get-Module | Format-Table Name,Version
Get-Command -Module PSReadLine | Format-Table Name,CommandType