Windows powershell tips:Conditional Operators

复习下 -match,-like,-contains

1. -match 用在 regular expression 去匹配 可以使用wildcard

example 1: 不是必须用在开头的匹配

$guy = "Guy Thomas 1949"

$guy - match “Th”

# Result PS> True

 

Example2:  一个错误的名字是不行的

$guy = "Guy Thomas 1949"

$guy - match “Guido”

# Result PS> False

 

Example3: 用wildcard ?

$Guy ="Guy Thomas 1949"
$Guy -Match "19?9"

 # Result PS> True

 

Example4: 用wildcard *

Get-WmiObject -List | Where {$_.name -Match "cim*"}

 

Note:powershell recognized the following character classes:

\w : mathces any word character, meaning letters and mumbers

\s : matchs any space character,such as tab, space, and so for forth

\d : matches any digt charater

# PowerShell Character Class Example
$Guy ="Guy Thomas 1949"
$Guy -Match "\w"

        # Result PS> True

=====================================================================

2. -like 是表达式两边必须是一样的, 可以使用wikdcard *

Example1: 只有一部分相同是不可以的

$Guy ="Guy Thomas 1949"
$Guy -Like "Th"

        # Result PS> False

Example 2: 只有开始部分相同也是不可以的

$Guy ="Guy Thomas 1949"
$Guy -Like "Guy"

        # Result PS> False

Example3:用通配符就可以$Guy ="Guy Thomas 1949"
$Guy -Like "Guy*"

        Result PS> True

在-like 里面通配符是两边都可以用的

$Guy ="Guy Thomas 1949"
$Guy -Like "*Th*"

        # Result PS> True

=========================================================================

3.- contains  它和-eq 有点像,除了返回值都是true或者false 外,-contains 是用在array,collection,hashtable 里面test 一个元素

Example1:检查each item between commas

# PowerShell -Contains
$name = "Guy Thomas", "Alicia Moss", "Jennifer Jones"
$name -Contains "Alicia Moss"

# Result PS> True

Exameple2: 要求元素精确匹配才行

# PowerShell -Contains
$name = "Guy Thomas", "Alicia Moss", "Jennifer Jones"
$name -Contains "Jones"

# Result PS>       False

Exameple3:不可以使用wildcard

# PowerShell -Contains
$name = "Guy Thomas", "Alicia Moss", "Jennifer Jones"
$name -Contains "*Jones"

# Result PS>       False

 

=============================================================================

总结:-conains 用在array,collection,hashtable 中test 元素的,不可以使用通配符,要元素完全一致才可以

-like 要表达式两边完全一摸一样,可以使用wildcard,前后都可以使用wildcard

-match 是用在string 的任何地方,也可以用通配符,只能后面用一个

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值