我正在尝试使用$Share.Name
按每个共享的名称进行过滤。但是,当我尝试在下面的-contains
声明中使用if
时,我没有得到任何结果。
我想要的结果应该是
ADMIN$ - C:\ADMIN$
我正在努力获得一个变量:
$ExcludeShares = "ADMIN$"
并根据$String.Name
是否在$ExcludeShares
我对其他过滤方法的想法持开放态度。
提前致谢!
function GetAllUsedShares{
[psobject]$Shares = Get-WmiObject -Class win32_share
Foreach($Share in $Shares){
$name = [string]$Share.Name
if ($name -contains 'admin'){
Write-Host $Share.Name - $Share.Path
}
}
}
答案 0 :(得分:11)
包含意味着对阵列。请考虑以下示例
PS C:\Users\Cameron> 1,2,3 -contains 1
True
PS C:\Users\Cameron> "123" -contains 1
False
PS C:\Users\Cameron> "123" -contains 123
True
如果您想查看字符串是否包含文本模式,那么您有几个选项。前2个是-match
运算符或.Contains()
字符串方法
-match
将是使用in和If语句的简单示例之一。 注意: -Match
支持.Net正则表达式,因此请确保您没有输入任何特殊字符,因为您可能无法获得预期的结果。
PS C:\Users\Cameron> "Matt" -match "m"
True
PS C:\Users\Cameron> "Matt" -match "."
True
默认情况下, -match
不区分大小写,因此上面的第一个示例返回True。第二个示例是匹配任何字符,这是.
在正则表达式中表示的原因,这也是它返回True的原因。
.Contains()
:-match
很棒,但对于简单的字符串,你可以......
"123".Contains("2")
True
"123".Contains(".")
False
请注意,.Contains()
区分大小写
"asdf".Contains('F')
False
"asdf".Contains('f')
True
答案 1 :(得分:0)
如果您正在测试$name
确切地说' admin'你可以使用-eq
比较器。这将检查$ name的内容是否等于指定字符串的内容' admin'
答案 2 :(得分:0)
您可以在一行中执行此操作:
Get-WmiObject -Class win32_share | where -Property Name -like "*admin*" | % { "$($_.Name) - $($_.Path)" }
不要忘记where语句中的星号。在这种情况下,它会查找确切的值。
如果你想写出来,这也是做同样的事情:
$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)"
}
答案 3 :(得分:0)
Bizarrely,.contains()的作用类似于-contains在数组上:
$a = 'one','two','three'
$a.contains('one')
True
$a.contains('o')
False
$a.contains
OverloadDefinitions
-------------------
bool IList.Contains(System.Object value)