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?
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.
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.
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.
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.
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)}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With