使用HashTables的Foreach-Object?

时间:2015-11-09 22:35:29

标签: powershell

我试图检查一些网络驱动器是通过登录脚本映射的。如果它们未映射,则脚本应该能够映射它们,但下面的代码中的My Foreach-Object不起作用。为什么?我不能在哈希表上使用它吗?

$Hash = @{
    "h:" = "\\server\share";
    "i:" = "\\server\share";
    "j:" = "\\server\share";
    "k:" = "\\server\share";
    "p:" = "\\server\share";
    "z:" = "\\server\share";
    }
        $Hash | ForEach-Object
        {
            If (!(Test-Path $_.Name))
            {
                $map = new-object -ComObject WScript.Network
                $map.MapNetworkDrive($_.Name, $_.Value, $true)
                Write-Host "Mapped That Stuff"
            }
            else
            {Write-Host ($Hash.Name) + ($Hash.Value)}
        }

在这种情况下如何使用foreach?或者有没有更好的方法来解决这个问题,而不是散列表或foreach循环?

2 个答案:

答案 0 :(得分:10)

要迭代[hashtable],您需要为其获取一个枚举器:

   $Hash.GetEnumerator() | ForEach-Object {
        If (!(Test-Path $_.Name))
        {
            $map = new-object -ComObject WScript.Network
            $map.MapNetworkDrive($_.Name, $_.Value, $true)
            Write-Host "Mapped That Stuff"
        }
        else
        {Write-Host ($_.Name) + ($_.Value)}
    }

答案 1 :(得分:5)

我通常只使用哈希表的Keys属性来迭代它。所以你的脚本将是:

$Hash = @{
    "h:" = "\\server\share";
    "i:" = "\\server\share";
    "j:" = "\\server\share";
    "k:" = "\\server\share";
    "p:" = "\\server\share";
    "z:" = "\\server\share";
    }
        $Hash.Keys | ForEach-Object
        {
            If (!(Test-Path $_))
            {
                $map = new-object -ComObject WScript.Network
                $map.MapNetworkDrive($_, $Hasj.$_, $true)
                Write-Host "Mapped That Stuff"
            }
            else
            {Write-Host ($_) + ($Hash.$_)}
        }

实际上,在查看之后我想我会采用更短的路线,使用Where语句找到不存在的驱动器,然后映射这些驱动器:

$Hash = @{
    "h:" = "\\server\share";
    "i:" = "\\server\share";
    "j:" = "\\server\share";
    "k:" = "\\server\share";
    "p:" = "\\server\share";
    "z:" = "\\server\share";
    }

$Hash.Keys | Where{!(Test-Path $_)} | ForEach{ New-PSDrive -Name $_.trim(':') -PSProvider FileSystem -Root $Hash.$_ -Persist }

我在那里使用了New-PSDrive cmdlet和-Persist参数,然后创建了一个标准的Windows映射驱动器,您可以通过Windows资源管理器查看和管理,就像任何其他映射驱动器一样。如果您不想要那种映射,只需删除-Persist参数,然后只为您的脚本映射它。