powershell contains not working

后端 未结 4 973
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-27 00:36

I am trying filter by the name of each share using $Share.Name. However, when I try to use -contains in the if statement below, I get no r

4条回答
  •  耶瑟儿~
    2021-01-27 01:16

    You can do this in one line:

    Get-WmiObject -Class win32_share | where -Property Name -like "*admin*" | % { "$($_.Name) - $($_.Path)" }
    

    Don't forget the asterisks in the where statement. It looks for exact values in that case.

    If you want to write it out, this does the same thing:

    $shares = Get-WmiObject -Class win32_share
    
    # I pipe the $shares collection into the where-object command to filter on "admin"
    $adminshares = $shares | where -property Name -like "*admin*"
    
    # now we can loop with a foreach, which has the "%" operator as it's shorthand in the oneliner
    foreach ($share in $adminshares) 
    {
        # variables in strings are a bit weird in powershell, but you have to wrap them like this
        write-host "$($share.Name) - $($share.Path)"
    }
    

提交回复
热议问题