Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach-Object with HashTables?

Tags:

powershell

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?

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

like image 252
SimonS Avatar asked Nov 09 '15 22:11

SimonS


People also ask

How do I ForEach an object in PowerShell?

If you want ForEach-Object to run a command or script block before it processes any input objects, use the Begin parameter of the PowerShell ForEach-Object command to specify the command. After ForEach-Object runs the commands you specify in the Begin parameter, it proceeds to the Process parameter.

How do I iterate through a Hashtable in PowerShell?

In the first method, the one that I prefer, you can use the GetEnumerator method of the hash table object. In the second method, instead of iterating over the hash table itself, we loop over the Keys of the hash table. Both of these methods produce the same output as our original version.

How do I merge two hash tables in PowerShell?

Adding values of the hash table is simple as the adding string. We just need to use the addition operator (+) to merge two hash table values.

How do I get key value pairs in PowerShell?

The key/value pairs might appear in a different order each time that you display them. Although you cannot sort a hash table, you can use the GetEnumerator method of hash tables to enumerate the keys and values, and then use the Sort-Object cmdlet to sort the enumerated values for display.


1 Answers

To iterate over a [hashtable] you need to get an enumerator for it:

   $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)}
    }
like image 84
briantist Avatar answered Oct 21 '22 10:10

briantist