[玩转系统] 发现提供商特定的命令
作者:精品下载站 日期:2024-12-14 07:59:24 浏览:16 分类:玩电脑
发现提供商特定的命令
最近,我在准备下一个 Pluralsight 课程时一直在深入研究 PowerShell 帮助。我发现的一件令人悲伤的事情是失去了提供者的帮助。您可能知道,某些命令具有仅在使用特定 PSDrive 时才存在的参数。例如,Get-ChildItem 的 -File 参数仅适用于文件系统。如果更改为 CERT: PSDrive,则该参数不可用。但您确实获得了一个新参数,例如 -CodeSigningCert。过去,您可以使用帮助来发现这些差异。 Get-Help 有一个 -Path 参数来帮助您。
遗憾的是,至少对于我作为一名 PowerShell 教师来说,这不再有效,特别是如果您最近在 Windows PowerShell 中更新了帮助的话。 Microsoft 正在对如何提供帮助进行一些更新,但目前我们可能需要替代方案。
获取命令
一种选择是使用 Get-Command 及其 -Syntax 参数。
顺便说一句,这是在 Windows PowerShell 中。正如您所看到的,我在 CERT 中可以使用不同的参数:PSDrive。
不幸的是,这并不是一件容易发现的事情。因此,我使用 PSScriptTools 模块中的 Copy-Command 函数创建了 Get-Command 的副本。我的版本本质上是相同的命令,但添加了路径参数。该参数的工作方式与获取帮助中的工作方式相同。它根据您指定的路径向您显示结果。
路径参数对每个 PSProvider 中的第一个 PSDrive 使用自动完成程序。这是该函数,并附有复制的帮助。
#requires -version 5.1
<#
This is a copy of:
CommandType Name Version Source
----------- ---- ------- ------
Cmdlet Get-Command 3.0.0.0 Microsoft.PowerShell.Core
Created: 20 July 2020
Author : Jeff
#>
Function Get-Command2 {
<#
.SYNOPSIS
Gets all commands.
.DESCRIPTION
The Get-Command2 cmdlet gets all commands that are installed on the computer, including cmdlets, aliases, functions, filters, scripts, and applications. Get-Command gets the commands from PowerShell modules and commands that were imported from other sessions. To get only commands that have been imported into the current session, use the ListImported parameter.
Without parameters, Get-Command2 gets all of the cmdlets, functions, and aliases installed on the computer. ` *` gets all types of commands, including all of the non-PowerShell files in the Path environment variable (`$env:Path`), which it lists in the Application command type.
Get-Command2 that uses the exact name of the command, without wildcard characters, automatically imports the module that contains the command so that you can use the command immediately. To enable, disable, and configure automatic importing of modules, use the `$PSModuleAutoLoadingPreference` preference variable. For more information, see about_Preference_Variables (About/about_Preference_Variables.md).
Get-Command2 gets its data directly from the command code, unlike `Get-Help`, which gets its information from help topics.
Starting in Windows PowerShell 5.0, results of the Get-Command2 cmdlet display a Version column by default. A new Version property has been added to the CommandInfo class.
.PARAMETER Path
Display the command using an alternate path to discover provider-aware parameters or syntax.
.PARAMETER All
Indicates that this cmdlet gets all commands, including commands of the same type that have the same name. By default, Get-Command gets only the commands that run when you type the command name.
For more information about the method that PowerShell uses to select the command to run when multiple commands have the same name, see about_Command_Precedence (About/about_Command_Precedence.md). For information about module-qualified command names and running commands that do not run by default because of a name conflict, see about_Modules (About/about_Modules.md).
This parameter was introduced in Windows PowerShell 3.0.
In Windows PowerShell 2.0, Get-Command gets all commands by default.
.PARAMETER ArgumentList
Specifies an array of arguments. This cmdlet gets information about a cmdlet or function when it is used with the specified parameters ("arguments"). The alias for ArgumentList is Args .
To detect dynamic parameters that are available only when certain other parameters are used, set the value of ArgumentList to the parameters that trigger the dynamic parameters.
To detect the dynamic parameters that a provider adds to a cmdlet, set the value of the ArgumentList parameter to a path in the provider drive, such as WSMan:, HKLM:, or Cert:. When the command is a PowerShell provider cmdlet, enter only one path in each command. The provider cmdlets return only the dynamic parameters for the first path the value of ArgumentList . For information about the provider cmdlets, see about_Providers (About/about_Providers.md).
.PARAMETER CommandType
Specifies the types of commands that this cmdlet gets. Enter one or more command types. Use CommandType or its alias, Type . By default, Get-Command gets all cmdlets, functions, and aliases.
The acceptable values for this parameter are:
- Alias. Gets the aliases of all PowerShell commands. For more information, see about_Aliases (About/about_Aliases.md). - All. Gets all command types. This parameter value is the equivalent of ` *`.
- Application. Gets non-PowerShell files in paths listed in the Path environment variable ($env:path), including .txt, .exe, and .dll files. For more information about the Path environment variable, see about_Environment_Variables. - Cmdlet. Gets all cmdlets.
- ExternalScript. Gets all .ps1 files in the paths listed in the Path environment variable ($env:path). - Filter and Function. Gets all PowerShell advanced and simple functions and filters.
- Script. Gets all script blocks. To get PowerShell scripts (.ps1 files), use the ExternalScript
value. - Workflow. Gets all workflows. For more information about workflows, see Introducing Windows PowerShell Workflow.
.PARAMETER FullyQualifiedModule
Specifies modules with names that are specified in the form of ModuleSpecification objects, described in the Remarks section of ModuleSpecification Constructor (Hashtable) (/dotnet/api/microsoft.powershell.commands.modulespecification.-ctor?view=powershellsdk-1.1.0#Microsoft_PowerShell_Commands_ModuleSpecification__ctor_System_Collections_Hashtable_). For example, the FullyQualifiedModule parameter accepts a module name that is specified in one of the following formats:
- `@{ModuleName = "modulename"; ModuleVersion = "version_number"}`
- `@{ModuleName = "modulename"; ModuleVersion = "version_number"; Guid = "GUID"}` ModuleName and ModuleVersion are required, but Guid is optional.
You cannot specify the FullyQualifiedModule parameter in the same command as a Module parameter. The two parameters are mutually exclusive.
.PARAMETER ListImported
Indicates that this cmdlet gets only commands in the current session.
Starting in PowerShell 3.0, by default, Get-Command gets all installed commands, including, but not limited to, the commands in the current session. In PowerShell 2.0, it gets only commands in the current session.
This parameter was introduced in Windows PowerShell 3.0.
.PARAMETER Module
Specifies an array of modules. This cmdlet gets the commands that came from the specified modules or snap-ins. Enter the names of modules or snap-ins.
This parameter takes string values, but the value of this parameter can also be a PSModuleInfo or PSSnapinInfo object, such as the objects that the `Get-Module`, `Get-PSSnapin`, and `Import-PSSession` cmdlets return.
You can refer to this parameter by its name, Module , or by its alias, PSSnapin . The parameter name that you choose has no effect on the command output.
.PARAMETER Name
Specifies an array of names. This cmdlet gets only commands that have the specified name. Enter a name or name pattern. Wildcard characters are permitted.
To get commands that have the same name, use the All parameter. When two commands have the same name, by default, Get-Command gets the command that runs when you type the command name.
.PARAMETER Noun
Specifies an array of command nouns. This cmdlet gets commands, which include cmdlets, functions, and aliases, that have names that include the specified noun. Enter one or more nouns or noun patterns. Wildcard characters are permitted.
.PARAMETER ParameterName
Specifies an array of parameter names. This cmdlet gets commands in the session that have the specified parameters. Enter parameter names or parameter aliases. Wildcard characters are supported.
The ParameterName and ParameterType parameters search only commands in the current session.
This parameter was introduced in Windows PowerShell 3.0.
.PARAMETER ParameterType
Specifies an array of parameter names. This cmdlet gets commands in the session that have parameters of the specified type. Enter the full name or partial name of a parameter type. Wildcard characters are supported.
The ParameterName and ParameterType parameters search only commands in the current session.
This parameter was introduced in Windows PowerShell 3.0.
.PARAMETER ShowCommandInfo
Indicates that this cmdlet displays command information.
This parameter was introduced in Windows PowerShell 5.0.
.PARAMETER Syntax
Indicates that this cmdlet gets only the following specified data about the command:
- Aliases. Gets the standard name.
- Cmdlets. Gets the syntax.
- Functions and filters. Gets the function definition.
- Scripts and applications or files. Gets the path and filename.
.PARAMETER TotalCount
Specifies the number of commands to get. You can use this parameter to limit the output of a command.
.PARAMETER Verb
Specifies an array of command verbs. This cmdlet gets commands, which include cmdlets, functions, and aliases, that have names that include the specified verb. Enter one or more verbs or verb patterns. Wildcard characters are permitted.
.EXAMPLE
Get-Command2
.EXAMPLE
Get-Command2-ListImported
.EXAMPLE
Get-Command2 -Type Cmdlet | Sort-Object -Property Noun | Format-Table -GroupBy Noun
.EXAMPLE
Get-Command2 -Module Microsoft.PowerShell.Security, Microsoft.PowerShell.Utility
.EXAMPLE
Get-Command2 Get-AppLockerPolicy
When a module is imported automatically, the effect is the same as using the Import-Module cmdlet. The module can add commands, types and formatting files, and run scripts in the session. To enable, disable, and configuration automatic importing of modules, use the `$PSModuleAutoLoadingPreference` preference variable. For more information, see about_Preference_Variables (../Microsoft.PowerShell.Core/About/about_Preference_Variables.md).
.EXAMPLE
Get-Childitem -Args Cert: -Syntax
When you compare the syntax displayed in the output with the syntax that is displayed when you omit the Args ( ArgumentList ) parameter, you'll see that the Certificate provider adds a dynamic parameter, CodeSigningCert , to the `Get-ChildItem` cmdlet.
For more information about the Certificate provider, see about_Certificate_Provider (../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md).
.EXAMPLE
function Get-DynamicParameters
{
param ($Cmdlet, $PSDrive)
( $Cmdlet -ArgumentList $PSDrive).ParameterSets | ForEach-Object {$_.Parameters} | Where-Object { $_.IsDynamic } | Select-Object -Property Name -Unique
}
Get-DynamicParameters -Cmdlet Get-ChildItem -PSDrive Cert:
Name
----
CodeSigningCert
The `Get-DynamicParameters` function in this example gets the dynamic parameters of a cmdlet. This is an alternative to the method used in the previous example. Dynamic parameter can be added to a cmdlet by another cmdlet or a provider.
.EXAMPLE
Get-Command2 *
It returns an ApplicationInfo object (System.Management.Automation.ApplicationInfo) for each file, not a FileInfo object (System.IO.FileInfo).
.EXAMPLE
Get-Command2 -ParameterName *Auth* -ParameterType AuthenticationMechanism
You can use a command like this one to find cmdlets that let you specify the method that is used to authenticate the user.
The ParameterType parameter distinguishes parameters that take an AuthenticationMechanism value from those that take an AuthenticationLevel parameter, even when they have similar names.
.EXAMPLE
dir
CommandType Name ModuleName
----------- ---- ----------
Alias dir -> Get-ChildItem
Although it is typically used on cmdlets and functions, Get-Command also gets scripts, functions, aliases, and executable files.
The output of the command shows the special view of the Name property value for aliases. The view shows the alias and the full command name.
.EXAMPLE
Notepad -All | Format-Table CommandType, Name, Definition
CommandType Name Definition
----------- ---- ----------
Application notepad.exe C:\WINDOWS\system32\notepad.exe
Application NOTEPAD.EXE C:\WINDOWS\NOTEPAD.EXE
The All parameter is useful when there is more than one command with the same name in the session.
Beginning in Windows PowerShell 3.0, by default, when the session includes multiple commands with the same name, Get-Command gets only the command that runs when you type the command name. With the All parameter, Get-Command gets all commands with the specified name and returns them in execution precedence order. To run a command other than the first one in the list, type the fully qualified path to the command.
For more information about command precedence, see about_Command_Precedence (About/about_Command_Precedence.md).
.EXAMPLE
( Get-Date).ModuleName
Microsoft.PowerShell.Utility
This command format works on commands in PowerShell modules, even if they are not imported into the session.
.EXAMPLE
Get-Command2 -Type Cmdlet | Where-Object OutputType | Format-List -Property Name, OutputType
This command gets the cmdlets and functions that have an output type and the type of objects that they return.
The first part of the command gets all cmdlets. A pipeline operator (|) sends the cmdlets to the `Where-Object` cmdlet, which selects only the ones in which the OutputType property is populated. Another pipeline operator sends the selected cmdlet objects to the `Format-List` cmdlet, which displays the name and output type of each cmdlet in a list.
The OutputType property of a CommandInfo object has a non-null value only when the cmdlet code defines the OutputType attribute for the cmdlet.
.EXAMPLE
Get-Command2 -ParameterType (((Get-NetAdapter)[0]).PSTypeNames)
CommandType Name ModuleName
----------- ---- ----------
Function Disable-NetAdapter NetAdapter
Function Enable-NetAdapter NetAdapter
Function Rename-NetAdapter NetAdapter
Function Restart-NetAdapter NetAdapter
Function Set-NetAdapter NetAdapter
This command finds cmdlets that take net adapter objects as input. You can use this command format to find the cmdlets that accept the type of objects that any command returns.
The command uses the PSTypeNames intrinsic property of all objects, which gets the types that describe the object. To get the PSTypeNames property of a net adapter, and not the PSTypeNames property of a collection of net adapters, the command uses array notation to get the first net adapter that the cmdlet returns. To get the PSTypeNames property of a net adapter, and not the PSTypeNames property of a collection of net adapters, the command uses array notation to get the first net adapter that the cmdlet returns.
.NOTES
* When more than one command that has the same name is available to the session, Get-Command2 returns the command that runs when you type the command name. To get commands that have the same name, listed in run order, use the All parameter. For more information, see about_Command_Precedence (../Microsoft.PowerShell.Core/About/about_Command_Precedence.md). * When a module is imported automatically, the effect is the same as using the `Import-Module` cmdlet. The module can add commands, types and formatting files, and run scripts in the session. To enable, disable, and configuration automatic importing of modules, use the `$PSModuleAutoLoadingPreference` preference variable. For more information, see about_Preference_Variables (../Microsoft.PowerShell.Core/About/about_Preference_Variables.md).
.INPUTS
System.String
.LINK
https://docs.microsoft.com/powershell/module/microsoft.powershell.core/?view=powershell-5.1&WT.mc_id=ps-gethelp
.LINK
Online Version:
.LINK
Export-PSSession
.LINK
Get-Help
.LINK
Get-Member
.LINK
Get-PSDrive
.LINK
Import-PSSession
.LINK
about_Command_Precedence
#>
[CmdletBinding(DefaultParameterSetName = 'CmdletSet')]
[alias("gcm2")]
Param(
[Parameter(ParameterSetName = 'CmdletSet', ValueFromPipelineByPropertyName = $true)]
[string[]]$Noun,
[Parameter(ParameterSetName = 'AllCommandSet', Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[string[]]$Name,
[Parameter(ParameterSetName = 'CmdletSet', ValueFromPipelineByPropertyName = $true)]
[string[]]$Verb,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Alias('PSSnapin')]
[string[]]$Module,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[Microsoft.PowerShell.Commands.ModuleSpecification[]]$FullyQualifiedModule,
[Parameter(ParameterSetName = 'AllCommandSet', ValueFromPipelineByPropertyName = $true)]
[Alias('Type')]
[System.Management.Automation.CommandTypes]$CommandType,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[int]$TotalCount,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[switch]$Syntax,
[switch]$ShowCommandInfo,
[Parameter(Position = 1, ValueFromRemainingArguments = $true)]
[Alias('Args')]
[AllowEmptyCollection()]
[AllowNull()]
[System.Object[]]$ArgumentList,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[switch]$All,
[Parameter(ValueFromPipelineByPropertyName = $true)]
[switch]$ListImported,
[ValidateNotNullOrEmpty()]
[string[]]$ParameterName,
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSTypeName[]]$ParameterType,
[Parameter(HelpMessage = "Display the command using an alternate path to discover provider-aware parameters or syntax.")]
[ArgumentCompleter( {(Get-PSProvider).foreach( {"$($_.drives[0].name):\"})})]
[ValidateScript( {Test-Path $_})]
[string]$Path
)
Begin {
Write-Verbose "[BEGIN ] Starting $($MyInvocation.Mycommand)"
Write-Verbose "[BEGIN ] Using parameter set $($PSCmdlet.ParameterSetName)"
if ($PSBoundParameters.ContainsKey("Path")) {
Write-Verbose "[BEGIN ] Getting command using path $Path"
[void]$PSBoundParameters.Remove("Path")
$locationChange = $True
Push-Location
Set-Location -Path $Path
}
} #begin
Process {
Write-Verbose "[PROCESS] Invoking 'Microsoft.PowerShell.Core\Get-Command'"
if ($locationChange) {
Write-Verbose "[PROCESS] Current location is $(Get-Location)"
}
Write-Verbose ($PSBoundParameters | Out-String)
Microsoft.PowerShell.Core\Get-Command @PSBoundParameters
} #process
End {
#set location back
if ($locationChange) {
Write-Verbose "[END ] Restoring original location"
Pop-Location
}
Write-Verbose "[END ] Ending $($MyInvocation.Mycommand)"
} #end
} #end function
就我的目的而言,新的 Path 参数仅在使用 -Syntax 或 -ShowInfo 时才有意义。
Get-Command 语法
在完成这个功能之后,我意识到我可以走一条不同的路。特别是如果我只关心语法的话。我真正想要的是一种查看所有提供程序的命令并查看语法如何变化的方法。这就是 Get-CommandSyntax 背后的目的,它的别名为 gsyn。该函数设计为从 PowerShell 控制台运行。它无法在 PowerShell ISE 中正常工作。
Function Get-CommandSyntax {
[cmdletbinding()]
[alias("gsyn")]
Param(
[Parameter(Position = 0, Mandatory, HelpMessage = "Enter the name of a PowerShell cmdlet or function")]
[ValidateScript( {Get-Command -Name $_})]
[string]$Name
)
foreach ($provider in (Get-PSProvider)) {
Write-Verbose "Testing in $($provider.name)"
"$([char]0x1b)[1;4;38;5;155m$($provider.name)$([char]0x1b)[0m"
#get first drive
$path = "$($provider.drives[0]):\"
Write-Verbose "Get syntax"
Push-Location
Set-Location $path
$syn = Get-Command -name $Name -Syntax | Out-String
Write-Verbose "Get dynamic parameters"
$get = Get-Command -name $name
$dynamic = ($get.parameters.GetEnumerator() | Where-Object {$_.value.IsDynamic}).key
Pop-Location
if ($dynamic) {
Write-Verbose "Found $($dynamic.count) dynamic parameters"
Write-Verbose ($dynamic -join ",")
foreach ($param in $dynamic) {
$syn = $syn -replace "\b$param\b", "$([char]0x1b)[1;38;5;213m$param$([char]0x1b)[0m"
}
}
$syn
} #foreach Provider
}
要运行该命令,您只需指定 PowerShell cmdlet 或函数的名称即可。该命令将循环遍历每个已安装 PSProvider 的第一个 PSDrive 并获取命令语法。但它更进一步。
特定于提供者的参数应该是动态的。对于每个提供程序,我找到动态参数名称,然后在语法输出中将它们替换为 ANSI 颜色的等效名称。
现在我可以一眼看出 PSProvider 中的命令可能有何不同。正如我所说,这在 Windows PowerShell 和 PowerShell 7 中都适用。检查很重要,因为 Windows PowerShell 和 PowerShell 7 之间的某些命令发生了更改。通常我会告诉人们阅读帮助,但现在可能并不总是有帮助。希望这些命令能够实现。
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag