You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL查询含多词字符串时Windows 10桌面搜索索引抛出异常求助

问题:PowerShell查询WDS索引时多词搜索报错,资源管理器却可正常查询

我写了一个PowerShell脚本查询Windows 10的Windows Desktop Search(WDS)索引,基础代码如下:

$query = "
    SELECT System.DateModified, System.ItemPathDisplay 
    FROM SystemIndex 
    WHERE CONTAINS(System.Search.Contents, '$($text)')
"

$objConnection = New-Object -ComObject adodb.connection
$objrecordset = New-Object -ComObject adodb.recordset

$objrecordset.CursorLocation = 3

$objconnection.open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")

$objrecordset.open($query, $objConnection, $adOpenStatic)

单个单词测试一切正常,但用多词(比如“and then”)查询时,出现以下错误:

Searching for 'and then'...

SELECT System.DateModified, System.ItemPathDisplay 
FROM SystemIndex 
WHERE CONTAINS(System.Search.Contents, 'and then')

Exception from HRESULT: 0x80040E14
At D:\searchSystemIndex.ps1:72 char:1
+ $objrecordset.open($query, $objConnection, $adOpenStatic)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

但在资源管理器里用content:"and then"查询索引却能正常运行,请问该怎么解决?


解决方案

问题出在WDS的CONTAINS查询语法上:当搜索多词短语时,需要用双引号把搜索内容包裹起来,否则像“and”这类SQL保留字会被错误解析为逻辑运算符,导致语法错误。资源管理器里的content:"and then"本质就是给短语加了双引号,所以能正常工作。

修改PowerShell代码里的查询语句部分,给搜索文本加上双引号并正确转义即可:

# 给搜索文本添加双引号,避免保留字冲突
$quotedSearchText = "`"$text`""
# 用Here-String拼接查询语句,更易读且避免转义问题
$query = @"
    SELECT System.DateModified, System.ItemPathDisplay 
    FROM SystemIndex 
    WHERE CONTAINS(System.Search.Contents, $quotedSearchText)
"@

$objConnection = New-Object -ComObject adodb.connection
$objrecordset = New-Object -ComObject adodb.recordset

$objrecordset.CursorLocation = 3

$objconnection.open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")

$objrecordset.open($query, $objConnection, $adOpenStatic)

补充说明

  • 如果需要搜索多个独立关键词(而非连续短语),可以用AND连接并分别给关键词加双引号,比如:
    $quotedSearchText = "'`"and`" AND `"then`"'"
    
  • 用PowerShell的Here-String(@"..."@)来写SQL语句,能避免很多字符串转义的麻烦,可读性也更强。

内容的提问来源于stack exchange,提问作者Dude named Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:31:18