[英]How can I remove unwanted characters from date-like strings within an array?
[英]How do I remove characters like "?" from an array powershell
我正在嘗試驗證從 Active Directory 中的 PC 描述中獲取的文本字符串。
但我想刪除像“??”的單個值這樣的流氓字符。 在驗證任何文本之前從任何文本。
我以這個測試代碼為例。 但每當它碰到隨機字符“??” 它拋出這個錯誤:
錯誤:
parsing "??" - Quantifier {x,y} following nothing.
At C:\Users\#####\OneDrive\Workingscripts\testscripts\removeingfromarray.ps1:11 char:5
+ If ($charigmorematch -match $descstr)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
當我想要做的就是將它從數組中刪除! 非常感謝任何幫助。
這是我的示例代碼。
##Type characters to remove in array.
$charigmorematch = @("?"; "@"; "$")
##array declare
$userdesc = @()
###Where this would be an AD description from AD.
$ADUser = "Offline - ?? - test"
###Split AD Descrip into individual strings
$userdesc = $ADUser.Split("-").Trim()
###Run through them to check for rogue characters to remove
ForEach($descstr in $userdesc)
{
###If match found try and take it out
If ($charigmorematch -match $descstr)
{
###Store match in variable.
$strmatch = ($charigmorematch -match $descstr)
###Get the index of the string
$indexstr = $userdesc.indexof($descstr)
Write=host "Match: $strmatch Index: $indexstr"
###Once found a match of a rogue character then remove from the array!
##But I haven't figured out that code yet.
###Then a command to remove the string from the array with the index number.
###In this case it's likely to be [1] to remove. But the code has to work that out.
}
}
# Sample input.
$ADUser = "Offline - ?? - test"
# Split into tokens by "-", potentially surrounded by whitespace,
# and filter out tokens that contain '?', '@', or '$'.
($ADUser -split '\s*-\s*') -notmatch '[?@$]'
結果是以下標記數組: 'Offline', 'test'
請注意, -notmatch
與(也)對字符串進行操作的所有比較運算符一樣,充當過濾器,將數組作為 LHS,就像這里的情況一樣( -split
始終返回一個數組)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.