首页 > 解决方案 > 通过检查识别隐藏 (MZ) 可执行文件的 PowerShell 脚本 - 错误

问题描述

我正在网上搜索示例,以识别给定指定目录的隐藏 DLL 和 EXE。我遇到了以下代码并决定试一试,因为它似乎正是我需要的:

    #add extensions here to ignore
    $ignore_extensions = '.exe','.dll'

    #grab all items in the current directory
    $mylisting = Get-ItemProperty *

    Write-Host("Number of files/folders:")$mylisting.count
    $count_suspect = 0
    for($i=0;$i -lt $mylisting.count; $i++)
    {
         #for each item in the listing: ensure the item is not a directory and not an ignored extension
         if( (Test-Path $mylisting[$i] -PathType Leaf) -and ($mylisting[$i].extension -notin $ignore_extensions) )
         {

              $magicbytes = '{0:X2}' -f (Get-Content $myfiles[$i] -Encoding Byte -ReadCount 4)
              if($magicbytes -eq '4D 5A 90 00')
              {
                   write-host("Found atypical file:")$myfiles[$i]
                   $count_suspect++
              }
         }
    }
    Write-Host("Number of suspect files found:")$count_suspect

给出的示例输出是:

    Number of files/folders: 27
    Found atypical file: C:\ps.txt
    Found atypical file: C:\PsExec.exe.txt

    Number of Suspect files found: 2

如果有人有时间帮助了解该过程,以便我弄清楚如何完成这项工作,我将不胜感激。

更新

当目录匹配 false 以识别具有 MZ 字节序列的文件时,它可以正常工作并打印预期的内容:

    Number of files/folders: 16
    Number of suspect files found: 0

当目录匹配 true 以识别具有 MZ 字节序列的文件时,我收到以下错误:

    Cannot index into a null array.
    At C:\Users\nog\Desktop\find_magic_bytes.ps1:15 char:11
    + $magicbytes = '{0:X2}' -f (Get-Content $myfiles[1] -Encoding Byte -R ...
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       +CategoryInfo         : InvalidOperation: (:) [], RuntimeException
       +FullQualifiedErrorId : NullArray

标签: powershellvariablesscriptingnestedfile-extension

解决方案


推荐阅读