Powershell 解析未格式化的文本文件

Powershell parse unformatted text file

我正在尝试解析基本上采用以下格式的文本文件:

姓名:詹姆斯

地点:英国

我认为使用 Select-String:

最有意义
$getName = "C:\account.txt"
Select-String -Path  $getName -Pattern 'Name:   '

但是,这 return 远远超出了我的需要。有人可以告诉我如何将“James”和“UK”作为不同的字符串。

谢谢!

你是说这个...

# Create user data sample and use regex match to get name and location only
Clear-Host
@'
Name: James
SomeOtherData: 
Location: UK
MoreStuff: 
'@ | Out-File -LiteralPath 'D:\Temp\account.txt'


Get-Content -Path 'D:\Temp\account.txt' | 
ForEach-Object {$PSItem | Select-String -Pattern '^(Name:\s|Location:\s).*'}
# Results
<#
Name: James
Location: UK
#>

或者这个...

Get-Content -Path 'D:\Temp\account.txt' | 
ForEach-Object {($PSItem | Select-String -Pattern '^(Name:\s|Location:\s).*') -replace '.*:\s'}
# Results
<#
James
UK
#>

有多种方法可以做到这一点。含义,列表格式如图所示或table格式。

此外,请查看 ConvertFrom-String cmdlet,将字符串转换为对象。

Clear-Host
$template = @'
{Property*:Name:} {Value:James}
{Property*:Location:} {Value:UK}
'@

$testText = @'
Name: James
SomeOtherData: 
Location: UK
MoreStuff: 
'@

我正在使用 PowerShell 变量压缩来分配给变量并同时输出到屏幕。 'This is not required.' 这只是在需要时同时做两件事的捷径。

(
$PersonalData = $testText | 
ConvertFrom-String -TemplateContent $template
)
# Results
<#
Property  Value
--------  -----
Name:     James
Location: UK  
#>

$PersonalData.Property
# Results
<#
Name:
Location:
#>


$PersonalData.Value
# Results
<#
James
UK
#>

(
$PersonalData = Get-Content -Path 'D:\Temp\account.txt'  | 
ConvertFrom-String -TemplateContent $template
)
# Results
<#
Property  Value
--------  -----
Name:     James
Location: UK  
#>

上述所有内容均有详细记录,PowerShell 帮助文件、MS Docs 站点、博客...

'PowerShell parsing text file' ...and videos on Youtube.