如何使用PowerShell使用参数读取特定的行值?

问题描述 投票:1回答:2

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

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

拜托,有人给我一点想法。谢谢

powershell text-parsing
2个回答
2
投票

最好的选择是使用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块中,为所有其他行执行,然后返回以下行,剥离其初始(制表符)char。

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

# 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'

0
投票

当您执行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]
    ...
}

我将以您描述的方式输出对象属性,以供您自己享受!

© www.soinside.com 2019 - 2024. All rights reserved.