Powershell从每行读取一些字符串

时间:2015-04-10 10:36:58

标签: powershell text

我有一个要求:

以下列模式提供包含以下内容的文本文件

172.26.xxy.zxy:Administrator:Password
172.26.xxy.yyx:Administrator:Password
172.26.xxy.yyy:Administrator:Password
172.26.xxy.yxy:Administrator:Password

我需要我的powershell脚本来阅读每个单词并在需要时使用该单词。例如,

foreach(something)
{
 I want the IP's(172.26.---.---) to read and store the value as a variable.
 I want to store the two words after **:** in seperate variables.
}

如何做到这一点?我知道要读取整个文件或获取一些特定的字符串。但我需要在每一行都做同样的事情。非常感谢你的帮助。

3 个答案:

答案 0 :(得分:2)

这样的东西?您可以在:上拆分,然后根据索引存储变量

$contents = Get-Conent C:\your\file.txt

foreach($line in $contents) {
  $s = $line -split ':'
  $ip = $s[0]
  $user = $s[1]
  $pass = $s[2]
  write-host $ip $user $pass
}

答案 1 :(得分:0)

您可以编写正则表达式来替换以删除不需要的部分

$ip_address= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$1'
$user= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$2'
$pwd= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$3'

答案 2 :(得分:0)

我认为更通用和纯粹的Powershell方式是这样的:

Select-String "(.*):(.*):(.*)" c:\file.txt |
 Select @{Name="IP"; Expression = {$_.Matches.Groups[1]}},
  @{Name="User"; Expression = {$_.Matches.Groups[2]}},
  @{Name="Password"; Expression = {$_.Matches.Groups[3]}}

输出将是一个对象数组,每个对象具有三个属性IP,用户和密码。因此,您现在可以将它们用于您的目的,或者只需在管道的末尾添加更多命令。

相关问题