Windows Search SQLをWSLからPowershellへ投げる

任意の Windows Search SQL のSELECT文を実行するために以前は C# のサンプルをコンパイルしてました。

Windows検索インデックスに直接SQLを投げてあげましょう

Windows 10の検索の問題

このサンプルは更新されてないので、Powershell のスクリプトでも十分であろうと思い乗り換えることにしました。

いくつか候補はありましたが以下からコードをコピーしました。

index is stored in a SQL database and the following script shows how to connect and search using PowerShell,

Using built-in OS indexing features for credential hunting · Embrace The Red

内容を少し削ったりして以下になりました。

$ grep -v '^ *#' /mnt/c/kinoue/misc/Invoke-WindowsSearch.ps1
function Invoke-WindowsSearch
{
    param
    (
        [Parameter()][string]   $query   = "select system.itempathdisplay from systemindex where contains('password')"
    )
    $provider = "Provider=Search.CollatorDSO.1;Extended?PROPERTIES='Application=Windows'"
    $adapter  = new-object System.Data.OleDb.OleDBDataAdapter -Argument $query, $provider
    $results = new-object System.Data.DataSet
    $adapter.Fill($results)
    $results.Tables
}
Invoke-WindowsSearch $args[0]

この powerpoint ファイルが検索で見つかるか試します。

$ powershell.exe -NoProfile -NoLogo -ExecutionPolicy Bypass \
  $(wslpath -w /mnt/c/kinoue/misc/)\\Invoke-WindowsSearch.ps1 \
  '"select system.itempathdisplay from systemindex 
   where 
  contains('\''""Dynatrace University login"" AND 
  ""Application Security"" AND ""Synthetic Monitor""'\'')"'
1

SYSTEM.ITEMPATHDISPLAY
----------------------
C:\Users\katsumi.inoue\OneDrive - Dynatrace\Documents\dynatrace_0.pptx

見事瞬時に pptx ファイルがヒットしました!

WSL: pass special char args to Powershell ps1 script

I use WSL2. When I need to run powershell, I tend to do it in one-liner. i.e.) I don’t interact with Powershell prompt.

Today, I found a way to pass strings with ‘space’ and ‘single quote’ to Powershell script which typically has filename extension of “*.ps1”.

Let’s use below article for example.

Name the script Unnamed_Arguments_Example_1.ps1 and run it with the argument FOO

How to Use Parameters in PowerShell Part I – Simple Talk

I used the slightly modified 2nd sample in above page.

Let’s pass ‘space’ character as is. One needs to use both ‘(single quote) and “(double quote) like below.

$ cat Unnamed_Arg_Example.ps1
$servername=$args[0]
$envname=$args[1]
write-host "on $servername in the $envname env."
$ powershell.exe -NoProfile -NoLogo -ExecutionPolicy Bypass \
  $(wslpath -w $PWD)\\Unnamed_Arg_Example.ps1 \
  '"Server_01 Server_02"' 'Env_01'
on Server_01 Server_02 in the Env_01 env.

To pass ‘single quote’ was even more trickier. I had to use ‘\” (singlequote, backslash, singlequote,singlequote) sequence.

$ powershell.exe -NoProfile -NoLogo -ExecutionPolicy Bypass \
  $(wslpath -w $PWD)\\Unnamed_Arg_Example.ps1 \
   '"Server_01'\''Server_02"' 'Env_01'
on Server_01'Server_02 in the Env_01 env.