微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Powershell解析未格式化的文本文件

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

名称:James

位置:英国

我认为使用Select-String最有意义:

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

但是,这将返回比我所需更多的方式。有人可以告诉我如何将“ 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
#>

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

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

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

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

我正在使用PowerShell变量压缩来分配给该变量并同时输出到屏幕。 “这不是必需的。”这只是在需要时同时执行两项操作的捷径。

(
$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' ...和Youtube上的视频。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。