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

如何使用PowerShell读取带参数的特定行值?,powershell,text-parsing,Powershell,Text Parsing,我有一个这种格式的文件 English Name Gerry Class Elementry ID Number 0812RX Gender *Male Female Address St.Joseph Rd.78 Member Name Jack 该文件的结构是,Name的值,有一个enter和一个tab,然后是值gery 我想读取每个项目的值。 我试过这个密码 Param( [parameter(mandatory=$tru

我有一个这种格式的文件

English
Name
    Gerry
Class
    Elementry
ID Number
    0812RX
Gender
    *Male
     Female
Address
     St.Joseph Rd.78
Member Name
     Jack
该文件的结构是,
Name
的值,有一个
enter
和一个
tab
,然后是值
gery

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

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


请,任何人给我一个主意。谢谢

当您执行
获取内容
时,该文件将作为您可以引用的字符串数组接收

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

$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]
    ...
}

我将以您描述的方式输出对象属性,这是一种供您自己享受的练习

最好的选择是与
-File
参数一起使用:

$found = $false
$value = switch -File file.txt {
  'Name' { $found = $true }
  default { if ($found) { $_.Substring(1); break } }
}
对于示例输入,
$value
应该包含
gery

$found
设置为
$true
,只要
'Name'
位于其自身的一行上;在对所有其他行执行的
default
块中,返回下一行,去掉其初始(tab)字符

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

# 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
以上结果将产生
gery

注意,如果键名有空格,则必须将其引用传递给脚本;e、 g:

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

该文件看起来不像标准化结构。您必须自己解析它。你从哪里得到这个文件?您从中获取此文件的程序/进程是否能够以标准文件格式(如CSV、JSON或XML)提供数据?我不想通过给出索引号来识别它,因为位置有时会有所不同。请再问一个问题,我想将该值设置为一个变量,我尝试了以下方法{$found=$true}默认值{if($found){return$\子字符串(1)}}}$test=$GetValue+“ok”$test但我无法获取@mklementO的值