1

原谅新手的问题,我是 powershell 的新手,我正在尝试做一些应该很容易的事情!

我有一个包含以下内容的文本文件

DEVICE ID:   {E24CF707-F030-48DC-8E1A-59B96148BF52}
DEVICE NAME: All Devices (RAINBOW-SRV)
TYPE:        Drive pool
DEVICE ID:   {D16DC75F-8A8B-4AEC-A411-9B0BC58CBF16}
DEVICE NAME: HP 1
TYPE:        Drive
DEVICE ID:   {F2D2AB4A-1FBE-4158-AB62-6A94AE4392E2}
DEVICE NAME: RAINBOW-SRV
TYPE:        Machine
DEVICE ID:   {23AD5D42-00A8-496B-96E5-1F5CAA3F9E9D}
DEVICE NAME: Symantec Protection Network (RAINBOW-SRV)
TYPE:        Symantec Protection Network
RETURN VALUE: 1

我正在尝试将 DEVICE NAME: 后面的字符串在每次出现时放入一个数组中,以传递给下一行的命令。我尝试了以下代码,但收到一条错误消息,指出 Substring 不是有效的方法。

我觉得我错过了一些非常明显但看不到的东西!任何帮助将非常感激。

非常感谢

4

3 回答 3

1

读取文件内容,过滤以'DEVICE NAME:'开头的行,对于每一行删除(替换为空)'DEVICE NAME:'

Get-Content devices.txt | Where-Object {$_ -like 'DEVICE NAME:* '} | Foreach-Object {$_ -repla
ce '^DEVICE NAME: '}

All Devices (RAINBOW-SRV)
HP 1
RAINBOW-SRV
Symantec Protection Network (RAINBOW-SRV)

更新:根据 OT 请求,如何将值传递给可执行命令

Get-Content devices.txt | 
Where-Object {$_ -like 'DEVICE NAME:* '} | 
Foreach-Object {
    $device = $_ -replace '^DEVICE NAME: '
    app.exe "$device"
}
于 2012-05-22T13:47:01.690 回答
1

另一种解决方案:

$list = @((get-content devices.txt) | where { $_ -match "DEVICE NAME:\s*(?<Device>.+)\s*" } | %{ $matches["Device"] })

$list
于 2012-05-22T14:10:15.483 回答
0

另一个解决方案:

Get-Content -Path .\devices.txt |
    Select-String 'DEVICE NAME: ' |
        Foreach-Object {
            $_.ToString() -replace '^DEVICE NAME: ','app.exe '
        }
于 2015-02-18T02:40:13.553 回答