English 中文(简体)
在 powershell 中读取文本文件的多个值,然后操控值
原标题:Reading multiple values from a text file in powershell then manipulating the values
  • 时间:2012-05-22 13:39:06
  •  标签:
  • powershell

恕我直言,我是新来的,想做点容易的事!

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

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 NAMEE之后的字符串移到一个阵列中, 以便传递到更远的线下命令。 我尝试过以下代码, 但发现一个错误, 显示Substring 不是一个有效的方法 。

我觉得我错过了一件显而易见的事,

非常感谢

最佳回答

读取文件内容, 过滤以 DEVICE 名称开头的行 :, 每行删除( 替换为无) DEVICE 名称 :

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"
}
问题回答

另一种解决办法:

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

$list

另一种解决办法是:

Get-Content -Path .devices.txt |
    Select-String  DEVICE NAME:   |
        Foreach-Object {
            $_.ToString() -replace  ^DEVICE NAME:  , app.exe  
        }




相关问题
Mutually exclusive powershell parameters

SCENARIO I m writing a cmdlet for Powershell 2.0 using Visual Studio 2008 and .NET 3.5 the cmdlet requires 3 arguments. my intended grammar of the cmdlet is something like this: cmdletname [foo|...

Run a program from PowerShell with timeout

I ll write a script that runs a program and wait for it finished. But if the program is not finished within a specified time I want that the program is killed.

How to transpose data in powershell

I have a file that looks like this: a,1 b,2 c,3 a,4 b,5 c,6 (...repeat 1,000s of lines) How can I transpose it into this? a,b,c 1,2,3 4,5,6 Thanks

Powershell v2 remoting and delegation

I have installed Powershell V2 on 2 machines and run Enable-PsRemoting on both of them. Both machines are Win 2003 R2 and are joined to the same active directory domain and I can successfully run ...

PowerShell -match operator and multiple groups

I have the following log entry that I am processing in PowerShell I m trying to extract all the activity names and durations using the -match operator but I am only getting one match group back. I m ...

热门标签