Powershell包含不起作用 [英] powershell contains not working

查看:97
本文介绍了Powershell包含不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 $ Share.Name 按共享的名称进行过滤。但是,当我尝试在下面的 if 语句中使用 -contains 时,没有任何结果。

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 results.

我想要的结果应该是
ADMIN $-C:\ADMIN $

我正在努力使自己具有以下变量:
$ ExcludeShares = ADMIN $ 并根据如果 $ String.Name $ ExcludeShares

I am working my way to being able to have a variable like: $ExcludeShares = "ADMIN$" and filtering based on if the $String.Name is in $ExcludeShares

我愿意接受其他过滤方法的想法。

I am open to ideas on other ways to filter this.

预先感谢!

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
        }

    }   
}


推荐答案

包含旨在对数组进行处理的功能。考虑以下示例

Contains is meant to work against arrays. Consider the following examples

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

如果您要查看是否 string 包含文本模式,那么您有几个选择。前两个将是 -match 运算符或 .Contains()字符串方法

If you are looking to see if a string contains a text pattern then you have a few options. The first 2 would be -match operator or the .Contains() string method


  1. -match 将是在If语句中使用的更简单示例之一。 注意: -Match 支持.Net正则表达式,因此请确保不要输入任何特殊字符,因为可能无法获得预期的结果。

  1. -match would be one of the simpler examples to use in and If statement. Note: -Match supports .Net regular expressions so be sure you don't put in any special characters as you might not get the results you expect.

PS C:\Users\Cameron> "Matt" -match "m"
True

PS C:\Users\Cameron> "Matt" -match "."
True

-比赛是默认情况下不区分大小写,因此上面的第一个示例返回True。第二个示例正在寻找匹配 any 字符,这是的含义。在正则表达式中表示,这也是为什么它也返回True的原因。

-match is not case sensitive by default so the first example above returns True. The second example is looking to match any character which is what . represents in regex which is why it returns True as well.

。Contains() -match 很好,但对于简单的字符串,您就可以....

.Contains(): -match is great but for simple strings you can ....

"123".Contains("2")
True

"123".Contains(".")
False

注意 .Contains()是区分大小写的

"asdf".Contains('F')
False

"asdf".Contains('f')
True


这篇关于Powershell包含不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆