命令行界面还是PowerShell?

rgu*_*wan 4 powershell command-line

如果你要制作一个工具:

  1. sys-admins会使用(例如系统监控或备份/恢复工具)
  2. 必须在Windows上可编写脚本

你会制作这个工具:

  1. 命令行界面工具?
  2. PowerShell cmdlet?
  3. 使用公共API的GUI工具?

我听说PowerShell在sys-admin中很重要,但我不知道与CLI工具相比有多大.

Kei*_*ill 11

PowerShell.

使用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%.

  • 如果Windows是目标,我真的不认为有比PowerShell更好的选择.就个人而言,我认为它最大的优势在于它是如何轻松实现远程操作的.我讨厌远程操作,因为根据我的经验,在你启动它之前总是有一个你必须执行的过程,这需要花费时间.现在使用PowerShell所有你需要做的就是`Enable-PSRemoting`,你很高兴. (2认同)