【问题标题】:How to read specific line value with argument using PowerShell?如何使用 PowerShell 读取带有参数的特定行值?
【发布时间】:2019-04-02 04:07:25
【问题描述】:

我有一个这种格式的文件。

English
Name
    Gerry
Class
    Elementry
ID Number
    0812RX
Gender
    *Male
     Female
Address
     St.Joseph Rd.78
Member Name
     Jack

这个文件的结构是,Name的值,有一个enter和一个tab,然后是Gerry的值

我想读取每个项目的值。 我试过这段代码。

Param(
  [parameter(mandatory=$true)][string]$FilePath, $Key
)

$FileContent = Get-Content $FilePath | Where-Object{"^($Key)","`$1$Value"}
$FileContent

我的期望,当我执行这个命令时

powershell.ps1 -FilePath file.txt -Key Name

它将返回:Gerry

拜托,任何人都可以给我一些想法。谢谢

【问题讨论】:

  • 该文件看起来不像一个标准化的结构。您将不得不自己解析它。你从哪里得到这个文件?您从中获取此文件的程序/进程是否能够以标准化文件格式(如 CSV、JSON 或 XML)提供数据?

标签: powershell text-parsing


【解决方案1】:

最好的选择是将switch statement-File 参数一起使用:

$found = $false
$value = switch -File file.txt {
  'Name' { $found = $true }
  default { if ($found) { $_.Substring(1); break } }
}

使用您的示例输入,$value 应包含 Gerry

$found 设置为 $true,一旦在自己的一行中找到 'Name';在为所有其他行执行的default 块中,然后返回以下行,去除其初始(制表符)字符。

包装在带有参数的脚本中,为简洁起见,此处使用脚本块进行模拟:

# Create a sample file; "`t" creates a tab char.
@"
Name
`tGerry
Class
`tElementary
ID Number
`t0812RX
"@ > file.txt

# Script block that simulates a script file.
& {

  param(
    [Parameter(Mandatory)] [string] $FilePath,
    [Parameter(Mandatory)] [string] $Key
  )

  $found = $false
  switch -File $FilePath { 
    $Key { $found = $true }
    default { if ($found) { return $_.Substring(1) } }
  }

} -FilePath file.txt -Key Name

以上产生Gerry

注意,如果你的键名有空格,你必须将它引用传递给脚本;例如:

... -FilePath file.txt  -Key 'ID Number'

【讨论】:

  • 请再问一个问题,我想将值设置为变量,我试过这个$GetValue = switch -File $FilePath {$Key { $found = $true } default { if ($found) { return $_.Substring(1) } }} $test = $GetValue + "ok" $test 但我无法得到值@mklementO
【解决方案2】:

当您执行Get-Content 时,文件将被提取为您可以引用的字符串数组。

这假定您的文件具有一致的格式 - 它们具有相同的行数,并且这些行对应于您在示例中指定的字段。如果没有,可以用正则表达式做一些事情,但我们现在不会深入。

$file = (get-content c:\temp\myfile.txt).trim()
$lang = $file[0]
$name = $file[3]
$class = $file[5]
$idNo = $file[7]
if ($file[9] -match '`*') {$gender = "Male"}
if ($file[10] -match '`*') {$gender = "Female"}
$address = $file[12]

然后,您可以将捕获的值分配给 PSCustomObject 或哈希表。事实上,同时进行是最简单的。

$student= [PsCustomObject]@{
    Lang = $file[0]
    Name = $file[3]
    Class = $file[5]
    ...
}

我将以您所描述的方式输出对象属性作为您自己享受的练习!

【讨论】:

  • 我不想通过给出索引号来识别它,因为有时位置不同。
猜你喜欢
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 2019-12-21
  • 2021-12-20
  • 1970-01-01
相关资源
最近更新 更多