Powershell从文本文件中读取多个变量

时间:2018-06-15 12:29:26

标签: file powershell loops variables foreach

我对PS很新,所以如果分辨率如此简单,请不要杀了我:) 我试图在这里和谷歌找到解决方案,但没有运气。

这是代码的一部分,不能按我的意愿工作

$Contents = Get-Content "Path\test.txt"

foreach($Line in $Contents) {
  $Line = $Line.split(":")[1]
  $s = $line -split ':'
  $RegPath = $s[0]
  $Value_Name = $s[1]
  $Type = $s[2]
  $Value = $s[3]
  Write-host $RegPath $Value_Name $Type $Value
  }

Write-Host的输出没问题,但主要问题是我想在foreach循环结束后使用这些变量。如果我在foreach之后调用任何变量,例如Write-Host $Value_Name,它就是空的。

我需要使用这些变量$RegPath, $Value_Name, $Type, $Value 在以后的脚本代码中。我无法想象怎么做。我很感激任何帮助/想法如何做到这一点。提前谢谢

编辑:添加了test.txt

Just some text to ignore :Software\Test
Just some text to ignore :Test
Just some text to ignore :String
Just some text to ignore :Value

并且foreach中第一个Write-Host的输出是正确的

Software/Test
Test
String
Value

当我想仅使用$Value_Name时,foreach

后输出为空

4 个答案:

答案 0 :(得分:3)

有一种误解:

  • 在迭代ForEach时,每个$Line被拆分并返回一个 项目。如果至少有三个,则只会填充$ s [0..3] 在同一行的冒号。
  • 如果要将前4行的冒号分隔值分配给这些变量,请尝试使用
$Contents = Get-Content "Path\test.txt"

$RegPath    = $Contents[0].split(":")[1]
$Value_Name = $Contents[1].split(":")[1]
$Type       = $Contents[2].split(":")[1]
$Value      = $Contents[3].split(":")[1]

Write-host ("{0}|{1}|{2}|{3}" -f $RegPath,$Value_Name,$Type,$Value)

示例输出

Software\Test|Test|String|Value

答案 1 :(得分:1)

编辑:由于误解文件格式而改变答案。将它留在这里,因为它可能对将来有所帮助。

在使用循环之前:

$outputFromLoop = @() 

在循环中使用:

foreach ($Line in $Contents) {
    # Here goes your code and variables RegPath, Value_Name, Type, Value are assigned

    # Add this:
    $object = New-Object –TypeName PSObject
    $object | Add-Member –MemberType NoteProperty –Name "RegPath" –Value $RegPath 
    $object | Add-Member –MemberType NoteProperty –Name "Value_Name" –Value $Value_Name
    $object | Add-Member –MemberType NoteProperty –Name "Type" –Value $Type
    $object | Add-Member –MemberType NoteProperty –Name "Value" –Value $Value
    $outputFromLoop += $object
  }

现在您可以列出所有值:

$outputFromLoop

或者只是按索引访问任何元素:

$outputFromLoop[0]

可以像这样访问属性:

$outputFromLoop[0].RegPath
$outputFromLoop[0].Value_Name
$outputFromLoop[0].Type
$outputFromLoop[0].Value

测试输出:

Write-Host  $outputFromLoop[0].RegPath $outputFromLoop[0].Value_Name $outputFromLoop[0].Type $outputFromLoop[0].Value

简短说明

您在这里基本上要为每个$object创建自定义对象$Line,并将其添加到$outputFromLoop数组。完成ForEach循环后,您可以根据代码下面的示例访问任何元素及其属性。

答案 2 :(得分:1)

您可以创建哈希表并将其“保存”在数组中

SelectListItems

还有其他可能性,例如二维数组。

答案 3 :(得分:0)

在循环之后,你将只有最后的值,因为你的变量正在接收并覆盖以前的值。 你需要做所有事情。每个交互都是一组值。

$Contents = Get-Content "Path\test.txt"

foreach($Line in $Contents) {
  $Line = $Line.split(":")[1]
  $s = $line -split ':'
  $RegPath = $s[0]
  $Value_Name = $s[1]
  $Type = $s[2]
  $Value = $s[3]
  Write-host $RegPath $Value_Name $Type $Value

  # do here the operations
}
相关问题