【问题标题】:Recursive file search using WMI Query and CIM_DataFile使用 WMI Query 和 CIM_DataFile 进行递归文件搜索
【发布时间】:2018-08-16 20:26:12
【问题描述】:

我希望能够在远程 Windows 桌面上查询特定文件,但是我有以下限制:

  1. 我无法假设 Powershell 远程处理已启用。
  2. 我不知道文件的确切位置
  3. 时间是一个因素

这导致我进行以下查询: SELECT * FROM CIM_DataFile WHERE Drive ='C:'AND FileName='Fake' AND Extension='dll'

与 powershell 中的 Get-childitem 之类的东西相比,这需要相对较长的时间,它允许我按文件夹和子文件夹优化搜索。

我总是可以这样做: SELECT * FROM CIM_DataFile WHERE Drive ='C:'AND FileName='Fake' AND Extension='dll' AND Path like '\\Windows\\System32\\%' 但是这个查询增加了遥控器的负载,实际上并没有减少任何时间。

有什么方法可以使用 WMI 进行某种类型的递归搜索?

【问题讨论】:

  • Get-CimInstance Win32_Directory -Filter "Name = 'C:\\Windows\\System32'" |Get-CimAssociatedInstance -Association Win32_Subdirectory
  • 你没有说什么操作系统和 PS 版本(源和目标)。有些 cmdlet 可以在不启用 PSRemoting 的情况下使用。 technet.microsoft.com/en-us/library/ff699046.aspx 或 Mathias 吹捧的路线。

标签: powershell wmi wmi-query


【解决方案1】:

如果您没有在目标计算机上启用 PowerShell 远程处理,则必须使用 DCOM 连接到 WMI。 DCOM 连接在现代 Windows 系统上默认关闭,因此您必须启用它 - 在这种情况下,您最好启用 PowerShell 远程处理。

如果你必须使用 WMI,你需要这样的东西

function get-wmifile {
[CmdletBinding()]
param (
 [Parameter(Mandatory = $true)]
 [string]$path,
 [string]$file
)

if ($path.IndexOf('\\') -le 0 ){
  $path = $path.replace('\', '\\')
}

if ($path.IndexOf('*') -ge 0 ){
  $path = $path.replace('*', '%')
}

Write-Verbose -Message "Path to search: $path"

$folders = Get-CimInstance -ClassName Win32_Directory -Filter "Name LIKE '$path'" 
foreach ($folder in $folders){
 if ($file) {
   Get-CimAssociatedInstance -InputObject $folder -ResultClassName CIM_DataFile |
   where Name -Like "*$file" |
   Select Name
 }
 else {
   Get-CimAssociatedInstance -InputObject $folder -ResultClassName CIM_DataFile |
   Select Name
 }
}

}

使用函数作为

PS> get-wmifile -path 'c:\test*'

Name                              
----                              
c:\test\counters.csv              
c:\test\p1.txt                    
c:\test\test.md                   
c:\test2\p1.txt                   
c:\test2\test3\p2.txt             
c:\testscripts\eventlogchanges.txt
c:\testscripts\tempfolderlog.csv  
c:\testscripts\test.ps1       

或查找文件

PS> get-wmifile -path 'c:\test*' -file 'p1.txt'

Name           
----           
c:\test\p1.txt 
c:\test2\p1.txt

正如您所说,使用 Get-ChildItem 会比 WMI 快得多。没有办法加快 WMI - 访问文件数据很慢 - 所以我的建议是坚持使用 get-ChildItem

【讨论】:

    猜你喜欢
    • 2012-01-30
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 2018-07-08
    • 1970-01-01
    相关资源
    最近更新 更多