When i run the following PowerShell (v5) code, the exclusions (C$, ADMIN$, IPC$ are not happening).
$shares = Get-SmbShare | where {$_.Name -ne "IPC$" -or $_.name -ne "C$" -or $_.name -ne "ADMIN$"}
$shares
the output is
Name ScopeName Path Description
---- --------- ---- -----------
ADMIN$ * C:\WINDOWS Remote Admin
C$ * C:\ Default share
IPC$ * Remote IPC
share2 * C:\Temp\share2
Sharetest * C:\Temp\Share
I can remedy the issue with this:
$shares = Get-SmbShare | where {$_.Name -ne "IPC$"} | where {$_.name -ne "C$"} | where {$_.name -ne "ADMIN$"}
$shares
which gives the desired output of:
Name ScopeName Path Description
---- --------- ---- -----------
share2 * C:\Temp\share2
Sharetest * C:\Temp\Share
I'm looing for something that could handle a bigger exclusion list more elegantly and efficiently.
This is an often-confused issue when using -and
and -or
, or their equivalent in other programming and/or scripting languages.
If you are looking to completely exclude a set of names, you want the match to use -and
- If the name is not C$ AND the name is not IPC$ AND the name is not ADMIN$, then include it in the list. Try
$shares = Get-SmbShare | where {$_.Name -ne "IPC$" -and $_.name -ne "C$" -and $_.name -ne "ADMIN$"}
$shares
-or
doesn’t work because the share name C$
returns $true
for the match $_.Name -ne "IPC$"
, and $true -or
«anything» is $true
.
A possibly “cleaner” way of handling this might be to create an array of exclusions, and then use -notin
to check the list of objects to be selected from:
$Exclusions = "C$", "ADMIN$", "IPC$"
$Shares = Get-SMBShare | Where-Object {$_.Name -notin $Exclusions}
With this, instead of making an increasingly long and unwieldly string of comparisons joined with -and
or -or
, you would just add the specific exclusion to the list of exclusions, and leave the rest of the code the same.