如何从数组电源外壳中删除"?"等字符



我正在尝试验证从Active Directory中的PC描述中提取的文本字符串
但我想删除流氓角色,比如单个值"quot;在验证任何文本之前,从任何文本中删除。

我以这个测试代码为例。但每当它击中随机字符"它抛出以下错误:
错误:

parsing "??" - Quantifier {x,y} following nothing.
At C:Users#####OneDriveWorkingscriptstestscriptsremoveingfromarray.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 spaces,
# and filter out tokens that contain '?', '@', or '$'.
($ADUser -split ' *- *') -notmatch '[?@$]'

结果是以下令牌数组:'Offline', 'test'

请注意,-notmatch与所有(也(对字符串进行操作的比较运算符一样,充当过滤器,并将数组作为LHS,就像这里的情况一样(-split总是返回一个数组(。


根据您在后面的评论中提到的附加要求,您可能正在寻找这样的东西(通过-|进行拆分,修剪周围的(...)(:

# Sample input
$ADUser = "Notebook PC | (Win 10) | E1234567 - simple ^^ user | Location ?? not @ set" 
($ADUser -split ' *[-|] *') -notmatch '[?@$]' -replace '^(|)$'

这将产生以下令牌阵列:
'Notebook PC', 'Win 10', 'E1234567', 'simple ^^ user'

请注意,除非您的输入字符串具有前导尾随空格,否则不需要调用.Trim()


至于您尝试了什么

$charigmorematch -match $descstr

-match运算符:

  • 要求输入字符串LHS(左侧(操作数。

  • 需要regex(正则表达式(作为RHS(右侧(操作数,以形成与输入匹配的模式

相比之下,您尝试的操作:

  • 错误地颠倒了操作数的顺序($descstr,因为在其中查找正则表达式模式的字符串必须是LHS(。

  • 错误地使用数组作为比较模式($charigmorematch(,而不是使用字符集([...](指定感兴趣字符的(单个(正则表达式(表示为字符串(。

最新更新