问题描述
名称: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上的视频。