问题:
我的脚本的目的是从两个文本文件中过滤出姓名和电话号码,并将它们添加到哈希表中,其中姓名为键,电话号码为值。
我面临的问题是
$name = $_.Current
返回 $null
,因此我的哈希值未填充。
有人可以告诉我问题是什么吗?
File1.txt 的内容:
洛瑞
东二街234号
罗利 NC 12345
9199617621
=================
File2.txt 的内容:
罗伯特
第十大道 2531 号
西雅图 WA 93413
2068869421
示例代码:
$hash = @{}
Switch -regex (Get-content -Path C:\Users\svats\Desktop\Fil*.txt)
{
'^[a-z]+$' { $name = $_.current}
'^\d{10}' {
$phone = $_.current
$hash.Add($name,$phone)
$name=$phone=$null
}
default
{
write-host "Nothing matched"
}
}
$hash
最佳答案
从 $_
中删除 current
属性引用:
$hash = @{}
Switch -regex (Get-content -Path C:\Users\svats\Desktop\Fil*.txt)
{
'^[a-z]+$' {
$name = $_
}
'^\d{10}' {
$phone = $_
$hash.Add($name, $phone)
$name = $phone = $null
}
default {
Write-Host "Nothing matched"
}
}
$hash
关于powershell - 使用 switch -regex 从文本文件读取字符串返回 null 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40538930/