【问题标题】:Search for special characters in a string in PowerShell在 PowerShell 中搜索字符串中的特殊字符
【发布时间】:2013-06-25 12:06:45
【问题描述】:

我有下面的代码,我正在尝试搜索特殊字符和字符串的长度。如果条件失败,则应向主机写入错误说明。我正在使用 PowerShell 2.0。该代码检查字符串长度,但无法检查任何特殊字符。

$chk = $user_logon.Output_Value
if($chk.length -gt 64 -or $chk -notmatch '[^a-zA-Z0-9]')
{
  Write-Host "Error - The Value ""$chk"" is greater than 64 bits or it contains a special character" -BackgroundColor "White" -ForegroundColor "Red";
}

我也试过了-

if($chk.length -gt 64 -or $chk -notmatch "^[a-zA-Z0-9\s]+$")

这已经奏效了。但我希望有一个条件来检查所有特殊字符,除非下划线“_”可以是 $chk 的一部分。

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    您需要将$chk -notmatch '[^a-zA-Z0-9]' 替换为$chk -match '[^a-zA-Z0-9]'

    【讨论】:

    • 谢谢。它解决了我匹配没有字母或数字的字符串的情况。我也很期待这样一种情况,我可以匹配一个没有特殊字符的字符串,除非下划线。
    • 案例 - if($chk.length -gt 64 -or $chk -match "[^a-zA-Z0-9_]") 有效。不确定它是否是最好的方法。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 2013-12-07
    • 2012-03-14
    • 1970-01-01
    相关资源
    最近更新 更多