Выразите несколько часто используемых условных выражений - PullRequest
1 голос
/ 15 июня 2019

Существует несколько общих условных выражений, которые часто используются, например:

Содержит ли оно содержимое, начинается ли оно с букв, заканчивается ли оно буквами, является ли оно пустым.

Может кто-нибудь написать код унифицированно?

$var = "word somestring"
if ($var --Does not contain-- "somestring") {
    Write-Host "true"
}
$var="word somestring"
if ($var --Does not start with-- "somestring") {
    Write-Host "true"
}
$var = "word somestring"
if ($var --Does not Ends with-- "somestring") {
    Write-Host "true"
}
$var = "word somestring"
if ($var --Is Not Empty--) {
    Write-Host "true"
}

Ответы [ 3 ]

2 голосов
/ 15 июня 2019

вам нужны строковые методы ИЛИ регулярное выражение и оператор -match.[ ухмылка ]

вот один способ увидеть методы ...

'asdf' |
    Get-Member -MemberType Methods

вот один способ увидеть статические методы типа [string]..

'asdf' |
    Get-Member -Static

для регулярных выражений, я рекомендую regex101.com ... [ ухмылка ]

вот несколько демонстрационных кодов для задействованных идей ...

$StringList = @(
    'qwerty is at the start of this string'
    'at the string-end, is qwerty'
    'in the middle, qwerty is placed'
    'the target word is not in this string'
    # below is an empty string
    ''
    )
$Target = 'qwerty'

foreach ($SL_Item in $StringList)
    {
    '+' * 50
    '--- Current test string   = "{0}"' -f $SL_Item
    '=== String Methods ==='
    'Target at start           = {0}' -f $SL_Item.StartsWith($Target)
    'Target at end             = {0}' -f $SL_Item.EndsWith($Target)
    'Target anywhere in string = {0}' -f $SL_Item.Contains($Target)
    ''
    '=== Regex ==='
    'Target at start           = {0}' -f ($SL_Item -match "^$Target")
    'Target at end             = {0}' -f ($SL_Item -match "$Target$")
    'Target anywhere in string = {0}' -f ($SL_Item -match $Target)
    ''
    '=== Empty ==='
    'String is $Null or empty  = {0}' -f [string]::IsNullOrEmpty($SL_Item)
    'String is $Null or empty  = {0}' -f ([string]::Empty -eq $SL_Item)
    ''
    }

усеченный вывод ...

++++++++++++++++++++++++++++++++++++++++++++++++++
--- Current test string   = "qwerty is at the start of this string"
=== String Methods ===
Target at start           = True
Target at end             = False
Target anywhere in string = True

=== Regex ===
Target at start           = True
Target at end             = False
Target anywhere in string = True

=== Empty ===
String is $Null or empty  = False
String is $Null or empty  = False

[*...snip...*] 

++++++++++++++++++++++++++++++++++++++++++++++++++
--- Current test string   = ""
=== String Methods ===
Target at start           = False
Target at end             = False
Target anywhere in string = False

=== Regex ===
Target at start           = False
Target at end             = False
Target anywhere in string = False

=== Empty ===
String is $Null or empty  = True
String is $Null or empty  = True
2 голосов
/ 15 июня 2019
$var = "word somestring"

# $var --Does not contain-- "somestring"
if ($var -notmatch "somestring") {
    Write-Host "true"
}

# $var --Does not start with-- "somestring"
if ($var -notmatch "^somestring") {
    Write-Host "true"
}

# $var --Does not start with-- "somestring"  - case sensitive
if (-not $var.StartsWith("somestring")) {
    Write-Host "true"
}

# $var --Does not Ends with-- "somestring"
if ($var -notmatch "somestring`$") {
    Write-Host "true"
}

# $var --Does not Ends with-- "somestring"  - case sensitive
if (-not $var.EndsWith("somestring")) {
    Write-Host "true"
}

# $var --Is Not Empty--
if (-not [String]::IsNullOrEmpty($var)) {
    Write-Host "true"
}

Обратите внимание: строковые (скажем, .Net) методы по умолчанию чувствительны к регистру, где PowerShell нечувствителен к регистру.

1 голос
/ 15 июня 2019

Вот вариант ответа ответа 2. (переключатель также имеет опцию -regex)

$StringList = 'qwerty is at the start of this string', 
  'at the string-end, is qwerty', 'in the middle, qwerty is placed', 
  'the target word is not in this string', ''

$Target = 'qwerty'

switch -wildcard ($StringList) {
  { $_.StartsWith($Target)      } { "'$target' at start of '$_'" }
  { $_.EndsWith($Target)        } { "'$target' at end of '$_'" }
  { $_.Contains($Target)        } { "'$target' anywhere in '$_'" }
  { $_ -match "^$Target"        } { "'$target' at start of '$_' (regex)" }
  { $_ -match "$Target$"        } { "'$target' at end of '$_' (regex)" }
  { $_ -match $Target           } { "'$target' anywhere in '$_' (regex)" }
  { [string]::IsNullOrEmpty($_) } { "'$target' not in IsNullOrEmpty() '$_'" }
  { ([string]::Empty -eq $_)    } { "'$target' not in ::Empty '$_'" }
  $target*                        { "'$target' start of '$_' (wildcard)" }
  *$target                        { "'$target' end of '$_' (wildcard)" }
  *$target*                       { "'$target' anywhere in '$_' (wildcard)" }
  ''                              { "'$target' not in empty '$_'" }
}


'qwerty' is at start of 'qwerty is at the start of this string'
'qwerty' is anywhere in 'qwerty is at the start of this string'
'qwerty' at start of 'qwerty is at the start of this string' (regex)
'qwerty' anywhere in 'qwerty is at the start of this string' (regex)
'qwerty' start of 'qwerty is at the start of this string' (wildcard)
'qwerty' anywhere in 'qwerty is at the start of this string' (wildcard)
'qwerty' is at end of 'at the string-end, is qwerty'
'qwerty' is anywhere in 'at the string-end, is qwerty'
'qwerty' is at end of 'at the string-end, is qwerty' (regex)
'qwerty' anywhere in 'at the string-end, is qwerty' (regex)
'qwerty' end of 'at the string-end, is qwerty' (wildcard)
'qwerty' anywhere in 'at the string-end, is qwerty' (wildcard)
'qwerty' is anywhere in 'in the middle, qwerty is placed'
'qwerty' anywhere in 'in the middle, qwerty is placed' (regex)
'qwerty' anywhere in 'in the middle, qwerty is placed' (wildcard)
'qwerty' not in IsNullOrEmpty() ''
'qwerty' not in ::Empty ''
'qwerty' not in empty ''
...