2013-06-27 136 views
0

我有下面的代碼,其中我試圖搜索特殊字符&字符串的長度。如果條件失敗,則應向主機寫入錯誤提示。我正在使用Powershell 2.0。代碼檢查字符串長度,但不能檢查任何特殊字符。請幫忙。在PowerShell中搜索字符串中的特殊字符

$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的一部分的下劃線「_」。

謝謝。

回答

1

您需要將$chk -notmatch '[^a-zA-Z0-9]'更換爲$chk -match '[^a-zA-Z0-9]'

+0

謝謝。它解決了我的情況,它匹配沒有字母或數字的字符串。我也期待着能夠匹配沒有特殊字符的字符串,除了下劃線。 – 0nir

+0

案例 - 如果($ chk.length -gt 64 - 或$ chk -match [[a-zA-Z0-9_]「)已經起作用。不知道它是否是最好的方法。謝謝。 – 0nir