如何在PowerShell脚本中为dsmadmc命令添加findstr过滤?
在PowerShell中整合findstr过滤dsmadmc.exe输出的方法
方法1:直接通过管道调用findstr.exe
如果你的原CMD命令类似:
dsmadmc.exe -username xxx -password yyy your_command | findstr.exe /v "要排除的行内容"
在PowerShell脚本里可以直接沿用管道逻辑,使用&操作符调用外部可执行文件:
# 替换为你实际的dsmadmc参数 & dsmadmc.exe -username "your_user" -password "your_pass" "your_query" | findstr.exe /v "要过滤的关键字"
&是PowerShell调用外部程序的标准操作符,即使命令无空格也可使用,能避免路径或参数带空格时的执行错误。
方法2:用PowerShell原生命令替代findstr
如果需要更灵活的过滤逻辑,或想避免依赖外部工具,可使用PowerShell原生的Where-Object:
- 正则匹配排除:
& dsmadmc.exe -username "your_user" -password "your_pass" "your_query" | Where-Object { $_ -notmatch "要排除的正则表达式" }
- 精确字符串匹配排除:
& dsmadmc.exe -username "your_user" -password "your_pass" "your_query" | Where-Object { $_ -notlike "*要排除的字符串*" }
特殊场景处理
如果dsmadmc.exe输出存在编码问题,导致findstr或PowerShell无法正确识别内容,可先转换输出编码:
& dsmadmc.exe -username "your_user" -password "your_pass" "your_query" | Out-String -Stream -Encoding UTF8 | findstr.exe /v "要过滤的关键字"
若脚本中使用变量传递参数,直接替换即可:
$user = "your_user" $pass = "your_pass" $query = "your_query" $filterKeyword = "要过滤的关键字" & dsmadmc.exe -username $user -password $pass $query | findstr.exe /v $filterKeyword
内容的提问来源于stack exchange,提问作者Eric van Loon
相关产品推荐
相关产品推荐

