powershell - 使用 switch -regex 从文本文件读取字符串返回 null 元素

标签 powershell powershell-ise

问题:

我的脚本的目的是从两个文本文件中过滤出姓名和电话号码,并将它们添加到哈希表中,其中姓名为键,电话号码为值。

我面临的问题是 $name = $_.Current 返回 $null,因此我的哈希值未填充。

有人可以告诉我问题是什么吗?

File1.txt 的内容:

洛瑞

东二街234号

罗利 NC 12345

9199617621

[email protected]

=================

File2.txt 的内容:

罗伯特

第十大道 2531 号

西雅图 WA 93413

2068869421

[email protected]

示例代码:

$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/

相关文章:

powershell - 在powershell中比较哈希并删除具有相同哈希的文件不起作用

windows - 通过 PowerShell 使用路径组件创建注册表项

windows - Windows高对比度主题中的Powershell ISE编辑器

powershell - 如何在 PowerShell 中使用 Set-NetConnectionProfile 更改 NetConnectionProfile 的名称

传递给函数的 Powershell 参数似乎不起作用

windows - Powershell 锁定第一个和最后一个文件,如果不关闭 powershell ISE,我无法删除它们

windows - 新 WebBinding : Cannot retrieve the dynamic parameters for the cmdlet

powershell - 我可以从 Powershell 登录 App Insights(可能通过 log4net)吗?

shell - Azure powershell cmdlet : Login-AzureRmAccount interactive doesn't work on windows server R8

powershell - 检查服务是否正在运行或停止并相应输出