如何使用PowerShell从.dll或.exe文件中提取数据

时间:2017-08-30 06:49:03

标签: windows powershell extract powershell-v5.0

我想列出其启动类型设置为自动

的所有服务

我正在使用PowerShell 5

$path = 'hklm:\SYSTEM\ControlSet001\Services'
$services = get-childitem $path | get-itemproperty -name 'Start'
foreach ($s in $services){
    if($s.'Start' -like '2'){
        $dn = get-itemproperty $s.'pspath' -name 'DisplayName'
        echo $dn
    }
}

但问题是大多数条目都使用这样的东西:

@%systemroot%\system32\SearchIndexer.exe,-103
@%SystemRoot%\System32\wscsvc.dll,-200

那么如何从中提取字符串?

为了进一步澄清,@%systemroot%\system32\SearchIndexer.exe,-103显示名称为"Windows Search"。问题是,PowerShell是否能够从"Windows Search"中提取字符串SearchIndexer.exe?怎么做?

更新

基本上从How to extract string resource from DLL

中窃取了代码
$source = @"
using System;
using System.Runtime.InteropServices;
using System.Text;

public class ExtractData
{
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)]string lpFileName);

[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int LoadString(IntPtr hInstance, int ID, StringBuilder lpBuffer, int nBufferMax);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool FreeLibrary(IntPtr hModule);

public string ExtractStringFromDLL(string file, int number) {
    IntPtr lib = LoadLibrary(file);
    StringBuilder result = new StringBuilder(2048);
    LoadString(lib, number, result, result.Capacity);
    FreeLibrary(lib);
    return result.ToString();
}
}
"@

Add-Type -TypeDefinition $source

$ed = New-Object ExtractData

$path = 'hklm:\SYSTEM\ControlSet001\Services'
$services = get-childitem $path | get-itemproperty -name 'Start' -ErrorAction SilentlyContinue
foreach ($s in $services){
    if($s.'Start' -like '2'){
        $dn = get-itemproperty $s.'pspath' -name 'DisplayName'
        try{
        $dn = $dn.DisplayName.Split(',')
        $dn = $ed.ExtractStringFromDLL([Environment]::ExpandEnvironmentVariables($dn[0]).substring(1), $dn[1].substring(1))
        }
        catch{}
        finally{
        echo $dn
        }
    }
}

丑陋,但最终有效......

2 个答案:

答案 0 :(得分:4)

有什么问题
get-service | where-object StartType -eq Automatic

答案 1 :(得分:2)

试试这个。它适用于PowerShell 3,因此也应该使用更高版本。

Get-WmiObject -Class Win32_Service | 
    Where-Object StartMode -eq Auto | 
    Select-Object -Property DisplayName