PowerShell中使用变量匹配SID无结果问题排查
问题描述
我编写了一个流程清晰的脚本,步骤如下:
- 导出secedit;
- 查找特定SID并存储;
- 为每个SID返回对应的组名。
但当我尝试使用变量在Where语句中过滤Get-LocalGroup的SID值时,没有得到任何结果;若直接使用SID实际值则能正常运行。请问我哪里操作有误?
脚本代码:
secedit /export /areas USER_RIGHTS /cfg c:\temp\logs.txt $userrights = Select-String -Path "c:\temp\logs.txt" -Pattern 'SeRemoteInteractiveLogonRight' | Out-String $userrights = $userrights.Replace("C:\temp\logs.txt:35:SeRemoteInteractiveLogonRight = ", "").Replace("*", "").Split(",") $userrights foreach ($userright in $userrights) { Get-LocalGroup | Where {$_.SID -Match $userright} }
问题分析与解决
你的脚本存在两个核心问题:
- SID字符串含多余空白字符:通过
Split(",")拆分后,每个SID元素可能带有前导/尾随空格、换行符,导致和Get-LocalGroup返回的SID字符串无法匹配。 - 错误使用正则匹配运算符:
-Match会将右侧字符串当作正则表达式解析,而SID中的-是正则元字符,会被误判为范围运算符,导致匹配逻辑失效。
修正后的脚本:
# 导出用户权限配置 secedit /export /areas USER_RIGHTS /cfg c:\temp\logs.txt # 提取目标权限对应的SID列表,清理冗余字符与空白 $userrights = (Select-String -Path "c:\temp\logs.txt" -Pattern 'SeRemoteInteractiveLogonRight').Line ` -replace 'SeRemoteInteractiveLogonRight = ', '' ` -replace '\*', '' ` -split ',' | ForEach-Object { $_.Trim() } # 遍历SID,精确匹配本地组 foreach ($userright in $userrights) { # 跳过空字符串,避免无效循环 if ([string]::IsNullOrWhiteSpace($userright)) { continue } Get-LocalGroup | Where-Object { $_.SID.Value -eq $userright } }
关键修改点:
- 直接调用
Select-String结果的Line属性,避免Out-String引入多余的文件路径、换行信息,简化字符串清理逻辑。 - 用
Trim()去除每个SID的前后空白字符,保证字符串纯净。 - 替换
-Match为精确匹配的-eq,同时调用$_.SID.Value获取SID的字符串值($_.SID是SecurityIdentifier对象,直接比较需取其Value属性)。 - 添加空值判断,过滤拆分后产生的无效空字符串。
内容的提问来源于stack exchange,提问作者Kuba
相关产品推荐
相关产品推荐

