PowerShell.
使用 PowerShell,您可以选择在 PowerShell 脚本或二进制 PowerShell cmdlet 中创建可重用命令。 PowerShell 是专门为支持输出重定向以及轻松启动 EXE 和捕获其输出的命令行接口而设计的。 PowerShell IMO 最好的部分之一是它为您标准化和处理参数解析。您所要做的就是为您的命令声明参数,PowerShell 为您提供参数解析代码,包括对类型、可选、命名、位置、强制、管道绑定等的支持。例如,以下函数声明显示了这一点:
function foo($Path = $(throw 'Path is required'), $Regex, [switch]$Recurse)
{
}
# Mandatory
foo
Path is required
# Positional
foo c:\temp '.*' -recurse
# Named - note fullname isn't required - just enough to disambiguate
foo -reg '.*' -p c:\temp -rec
PowerShell 2.0 高级功能提供了更多功能,例如参数别名-CN alias for -ComputerName、参数验证[ValidateNotNull()] 以及用于使用和帮助的文档集,例如:
<#
.SYNOPSIS
Some synopsis here.
.DESCRIPTION
Some description here.
.PARAMETER Path
The path to the ...
.PARAMETER LiteralPath
Specifies a path to one or more locations. Unlike Path, the value of
LiteralPath is used exactly as it is typed. No characters are interpreted
as wildcards. If the path includes escape characters, enclose it in single
quotation marks. Single quotation marks tell Windows PowerShell not to
interpret any characters as escape sequences.
.EXAMPLE
C:\PS> dir | AdvFuncToProcessPaths
Description of the example
.NOTES
Author: Keith Hill
Date: June 28, 2010
#>
function AdvFuncToProcessPaths
{
[CmdletBinding(DefaultParameterSetName="Path")]
param(
[Parameter(Mandatory=$true, Position=0, ParameterSetName="Path",
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
HelpMessage="Path to bitmap file")]
[ValidateNotNullOrEmpty()]
[string[]]
$Path,
[Alias("PSPath")]
[Parameter(Mandatory=$true, Position=0, ParameterSetName="LiteralPath",
ValueFromPipelineByPropertyName=$true,
HelpMessage="Path to bitmap file")]
[ValidateNotNullOrEmpty()]
[string[]]
$LiteralPath
)
...
}
了解属性如何让您更精细地控制 PowerShell 的参数解析引擎。另请注意可用于用法和帮助的 doc cmets,如下所示:
AdvFuncToProcessPaths -?
man AdvFuncToProcessPaths -full
这真的非常强大,也是我停止编写自己的小 C# 实用程序 exe 的主要原因之一。参数解析占代码的 80%。