Question:
I’m trying to check wheter some network drives are mapped via logon script. If they’re not mapped, the script should be able to map them but My Foreach-Object in the code below doesn’t work. why? Can’t I use it on hashtables?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
$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)} } |
How do I have to use foreach
in this situation? Or is there a better way to solve this issue instead of a hashtable or a foreach loop?
Answer:
To iterate over a [hashtable]
you need to get an enumerator for it:
1 2 3 4 5 6 7 8 9 10 11 |
$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)} } |