【问题标题】:Adding user input to a Select-String command将用户输入添加到 Select-String 命令
【发布时间】:2018-05-14 18:11:05
【问题描述】:

我目前正在尝试创建一个选择字符串命令来确定我公司中的用户是否仍显示在某些目录中。我当前的命令如下:

Select-String -path "C:\filepath\*.csv" -Pattern "<string>" |
    Format-Table -Property LineNumber,Line,Path -Wrap |
    Out-File "C:\outfile.txt"

当前命令意味着我需要在每次运行脚本之前更改 Pattern 参数的内容。我想做的是在我运行脚本时请求我输入字符串。是否可以在此命令中添加一个 while 循环来请求用户输入?

谢谢

【问题讨论】:

    标签: powershell while-loop select-string


    【解决方案1】:

    将此添加到脚本的头部:

    Param(
        [Parameter(Mandatory = $True)]
        [System.String]
        $Pattern
    )
    
    Select-String -Path C:\filepath\*.csv -Pattern $Pattern |
        Tee-Object -FilePath C:\outfile.txt |
        Format-Table -Property LineNumber, Line, Path -Wrap
    

    当您调用脚本时,该属性会确保您向-Pattern 提供参数。如果您希望它不为空 ([ValidateNotNullOrEmpty()]) 等,您可以添加更多属性。

    顺便说一句,永远不要从格式化程序中管道。

    【讨论】:

    • 出于好奇,我为什么不应该在 Format-Table 之后使用管道?
    • @m_lloyd 因为格式化程序仅用于显示到控制台。它们由Format.Format* 数据类型组成,您实际上无法对其进行任何操作。 Get-Process | Format-Table,现在您无法再访问流程详细信息了。
    猜你喜欢
    • 1970-01-01
    • 2020-03-31
    • 2021-04-16
    • 2016-01-31
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 2018-06-15
    相关资源
    最近更新 更多