【问题标题】:How to Display the Last Half of a String in the Results Returned by windows "findstr" command?如何在windows“findstr”命令返回的结果中显示字符串的后半部分?
【发布时间】:2018-02-16 23:15:23
【问题描述】:

我在 AWS 上有一个 Windows 2012 实例,我试图从 CLI 返回实例 ID。我可以使用这个命令成功地将该信息返回到一个变量中:

$instanceId = Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/instance-id

然后我可以回显该变量的内容并过滤掉相关行:

PS C:\Users\Administrator> echo $instanceId | findstr  /b  /c:"Content "
Content           : i-4bee88888bd72g2a

我的问题是我希望只返回冒号后面的字符串,所以输出看起来像:

i-4bee88888bd72g2a

我可以在 findstr 中添加什么开关来过滤掉那个字符串? Microsoft 相当于 sed 是什么?

【问题讨论】:

    标签: powershell


    【解决方案1】:

    PowerShell 输出 objects,而不是 text。运行此命令时:

    Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/instance-id
    

    它输出具有Content 属性的对象的字符串表示形式。要仅选择该属性的值,您可以使用Select-Object -ExpandProperty,如下所示:

    Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/instance-id | Select-Object -ExpandProperty Content
    

    这告诉 PowerShell:“有一个输出对象,我只想要它的 Content 属性的值。”

    您可以将其分配给您的变量:

    $instanceId = Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/instance-id | Select-Object -ExpandProperty Content
    

    你也可以这样写:

    $instanceId = (Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/instance-id).Content
    

    (也就是说,( ) 包含一个表达式,您将获得表达式输出对象的 Content 属性。)

    【讨论】:

    • 谢谢! “Select-Object -ExpandProperty Content”命令效果非常好。
    【解决方案2】:

    我找到了一个更好的解决方案,可以返回准确的结果;它使用“replace”,即“sed”的 MS 版本:

    $instanceId = Invoke-WebRequest -Uri http://169.254.169.254/latest/meta-data/instance-id
    $contentString = $instanceId | findstr /b /c:"Content "
    $desiredresult = $contentString -replace "(Content           :)\s([a-z]+)",'$2'
    $desiredresult
    

    返回确切结果:

    i-4bee88888bd72g2a
    

    【讨论】:

      【解决方案3】:

      我可能用 findstr 命令找错了树。我发现我可以使用命令 select-string 显示确切的字符串:

      $instanceId | select-string -Pattern "i-"
      

      返回结果:

      i-4bee88888bd72g2a
      

      (但它在结果前后包含空白行,我可能不得不丢弃,待定。)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-14
        • 1970-01-01
        • 1970-01-01
        • 2021-07-12
        • 1970-01-01
        相关资源
        最近更新 更多