Powershell从文本文件读取多个变量 [英] Powershell reading multiple variables from text file

查看:68
本文介绍了Powershell从文本文件读取多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对PS还是很陌生,所以如果分辨率很简单,请不要杀了我:)我试图在这里和Google中找到解决方案,但是没有运气.

I'm quite new to PS, so please don't kill me if the resolution is so easy :) I've tried to find a solution here and in google, but no luck.

这是代码的一部分,无法正常工作

This is part of code which don't work as I want

$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 ,则该变量为空.

The output from Write-Host is ok, but the main problem is when I want to use those variables after end of foreach loop. If I call any variable after foreach, for example Write-Host $Value_Name it is just empty.

我需要使用这些变量 $ RegPath,$ Value_Name,$ Type,$ Value 在后面的脚本代码中.我不知道该怎么做.如果有任何帮助/想法,我将不胜感激.预先谢谢你

I need to use those variables $RegPath, $Value_Name, $Type, $Value in later code of script. I can't figure how to do it. I would appreciate any help/idea how to do it. Thank you in advance

添加了test.txt

Added 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的输出是正确的

And the output from the first Write-Host in foreach is correct

Software/Test
Test
String
Value

当我只想使用 $ Value_Name 时,在 foreach

推荐答案

有一个误解:

  • 在迭代ForEach时,每个 $ Line 被拆分并返回一个物品.$ s [0..3]仅在至少有三个时填充同一行中的冒号.
  • 如果您想将前4行的冒号分隔值分配给这些变量,请尝试此操作
  • while iterating the ForEach each $Line is split and returns a single item. $s[0..3] would only be populated if there were at least three colons in the same Line.
  • Provided you want to assign the colon separated values of the first 4 lines to these variables, try this
$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

这篇关于Powershell从文本文件读取多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆