powershell - 带有哈希表的 Foreach 对象?

标签 powershell

我正在尝试检查是否通过登录脚本映射了某些网络驱动器。如果它们没有被映射,脚本应该能够映射它们,但下面代码中的我的 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 循环?

最佳答案

迭代 [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)}
    }

关于powershell - 带有哈希表的 Foreach 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33619616/

相关文章:

azure - “this.Client.SubscriptionId”不能为空

powershell - Azure 用户删除错误

windows - 在“任务计划程序”中的“路径开始”中被忽略

powershell - 无法识别“New-AzureStorageContext”

c# - 使用 C# 6.0 代码的 MSBuild 命令行无法构建

powershell - 在Powershell中切片数组(或列表)的更好方法

git - 如何使用 VSCode 1.5+ 作为 Git 的默认编辑器

rest - Azure 网站 Kudu REST API - 身份验证

powershell - 将 WMI 创建日期转换为格式表

powershell函数返回