有几种常用的条件语句,例如:
是否包含,是否以字母开头,是否以字母结尾,是否为空。
有人可以用统一的方式编写代码吗?
$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"
}
最佳答案
$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不区分大小写。
关于powershell - 表达几个常用的条件语句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56606492/