开发者

Powershell program issues

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 =""

$NonHiddenS开发者_如何学Chares =""

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:

$shares | ForEach-Object {
    if ($_.Name -like "*$") {
        #Do Something
    } else {
        #Do something else
    }
}

or

foreach ($share in $shares) {
     if ($share.Name -like "*$") {
        #Do Something
     } else {
        #Do Something else
     }
}

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,

$Shares = Get-WmiObject Win32_Share
$HiddenShares =""
$NonHiddenShares =""
Foreach($share in $Shares)
{
    If($share.Name -like "*$")
        {
            $HiddenShares += "`n$($share.Name)"
        }
        Else
        {
            $NonHiddenShares += "`n$($share.Name)"
        }
}
Write-Host "Hidden Shares"
Write-Host $HiddenShares 

Write-Host "`nNon-hidden Shares"
Write-Host $NonHiddenShares

Another solution could be:

$shares = Get-WmiObject Win32_Share

$objShares = @{}
$hiddenShares = @()
$nonHiddenShares = @()
$shares | ForEach-Object {
    if ($_.Name -like "*$") {
        $hiddenShares += $_.Name
    } else {
        $nonHiddenShares += $_.Name
    }
}

$objShares.Add("Hidden Shares",$hiddenShares)
$objShares.Add("Non-hidden Shares",$nonHiddenShares)
$objShares

This will return something like:

Name                           Value                                               
----                           -----                                               
Hidden Shares                  {ADMIN$, C$, IPC$}                                  
Non-hidden Shares              {}    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜