【问题标题】:Pipe select-string variable into select-string管道选择字符串变量到选择字符串
【发布时间】:2015-03-05 03:33:54
【问题描述】:

我为用户提供 2 个下拉列表(1.“区域”和 2.“站点”),第二个列表依赖/动态取决于第一个列表选择。 When a "Region" item is selected, I'm doing a select-string to lookup a file which has all region/site information to return all lines which match the selected Region plus the 2 lines below that to give the site line.然后我整理并搜索这些结果以仅返回站点行。然后,我可以只使用与用户选择的区域相关的站点来更新“站点”下拉框。这是为了拆分屏幕上列出的站点数量。

例如。站点信息.txt:

[UK - London]
Region = EMEA
Timezone = xxx
Site = London

[AU - Brisbane]
Region = APAC 
Timezone = xxx
Site = Brisbane

例如。脚本(在区域列表中选择“APAC”):

$input = get-content C:\Temp\siteinfo.txt
$SearchString = 'Region = APAC' 
$SearchStringsite = 'SiteName = '
$sitelist = $input | select-string $SearchString -Context 2 | select-string "Site = " | ForEach-Object {$_ -Replace $SearchStringsite,""} 

上述脚本失败且没有错误,还尝试拆分选择字符串命令并将区域结果注入到选择字符串中的变量中,但得到的结果相同。

但是我能够将第一个选择字符串结果写入一个文件,然后将该文件读入第二个选择字符串并且它可以工作。我试图避免必须输出到文件,因为环境可能已经锁定了运行脚本的写入策略。

有什么想法可以做到这一点吗?

【问题讨论】:

    标签: variables powershell search pipe


    【解决方案1】:

    问题在于Select-String 返回MatchInfo 对象,但默认显示使它看起来只是返回一个字符串。要访问上下文行,您必须将它们引用为 .context.postcontext

    我将您的 $input 换成 $data($input 实际上是作为自动变量保留的),并将其折叠在管道上以提高可读性:

    $data = get-content C:\Temp\siteinfo.txt
    $SearchString = 'Region = APAC' 
    $SearchStringsite = 'SiteName = '
    $sitelist = $($data |
     select-string $SearchString -Context 2).Context.PostContext |
     select-string "Site = " |
     ForEach-Object {$_ -Replace $SearchStringsite,""} 
    

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      相关资源
      最近更新 更多