rgu*_*wan 4 powershell command-line
如果你要制作一个工具:
你会制作这个工具:
我听说PowerShell在sys-admin中很重要,但我不知道与CLI工具相比有多大.
Kei*_*ill 11
使用PowerShell,您可以选择在PowerShell脚本中创建可重用命令,也可以选择在二进制PowerShell cmdlet中创建可重用命令.PowerShell的是专门为条命令行接口,可支持输出重定向以及容易启动的exe和捕捉它们的输出设计.PowerShell IMO的最佳部分之一是它为您标准化和处理参数解析.您所要做的就是声明命令的参数,PowerShell为您提供参数解析代码,包括对typed,optional,named,position,mandatory,pipeline bound等的支持.例如,以下函数声明显示了这一点:
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
Run Code Online (Sandbox Code Playgroud)
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
)
...
}
Run Code Online (Sandbox Code Playgroud)
了解这些属性如何为PowerShell的参数解析引擎提供更精细的控制.另请注意可以用于使用和帮助的文档注释,如下所示:
AdvFuncToProcessPaths -?
man AdvFuncToProcessPaths -full
Run Code Online (Sandbox Code Playgroud)
这真的非常强大,也是我停止编写自己的小C#实用程序exes的主要原因之一.参数解析最多只占代码的80%.
| 归档时间: |
|
| 查看次数: |
1181 次 |
| 最近记录: |