I’m having an issue with my code. I want to list the hidden and non hidden shares. I must do so using the if/else structure. My issue seems to be in the $HiddenShares and $NonHiddenShares arrays. I want the list to have the headings Hidden Shares and Non-hidden Shares followed by the shares, with each shares on a separate line.
Example:
Hiddden Shares
Videos$
Music$
Non-hidden Shares
TV$
Photos$
Here is my code:
$Shares = Get-WmiObject Win32_Share
$HiddenShares =""
$NonHiddenShares =""
Foreach($_ in $Shares)
{
If($_ | Where-Object {$_.Name -like "*$"})
{
$HiddenShares += $_.Name
}
Else
{
$NonHiddenShares += $_.Name
}
}
Write-Host "Hidden Shares"
Write-Host $HiddenShares
Write-Host "Non-hidden Shares"
Write-Host $NonHiddenShares
There are multiple issues in your sample code.
$_ is an automatic variable. The correct way to use that is:
or
By doing something like
$HiddenShares += $_.Name, you are actually concatenating the strings. A real dirty way to fix this is: $HiddenShares += “`n$($_.Name)”.Also, insdie the if statement, you can directly get the property. You need not do use
Where-Object.So, your code will look like,
Another solution could be:
This will return something like: