Test-Path powershell 在应该为 false 时返回 True

Test-Path powershell is returning True when it should be false

我正在为 运行 logparser 查询编写一个模块。我编写了一个函数来检查 LogParser 是否在系统根目录中,以便我可以 运行 logparser 作为后续函数中的命令。

我的代码:

function Add-LogParser
{
if(Test-Path "C:\Windows\System32\LogParser.exe")
    {
        Write-Host -ForegroundColor Cyan "Log Parser is in System Root"
    }
else
    {
        Copy-Item "C:\Program Files (x86)\WindowsPowerShell\Modules\Dealogic.LogAnalysis\LogParser.exe" -Destination "C:\Windows\System32\"  -Force
        if(Test-Path "C:\Windows\System32\LogParser.exe")
            {
                Write-Host -ForegroundColor Cyan "Log Parser has been added to System Root"
            }
        else
            {

                Write-Host -ForegroundColor Red "Unable to add Log Parser to System Root. This is a requirement of the Dealogic Log Analysis Module. Please verify you have write to copy to the C:\Windows\System32\ folder."
                break
            }
    }
}

我运行 函数和第一次将它添加到 root 很好。我再次 运行 该函数,因为它有逻辑来检查它是否在根目录中并且工作正常。然后我删除了 LogParser,期望它第三次看到它在那里并将它添加回 root,但相反,它认为 LogParser 仍然在那里。即使我开始新的 Powershell 会话并只是切换到它认为它在那里的路径。

即使在我的代码之外,此命令也无法正常工作:

测试路径-LiteralPath C:\Windows\System32\LogParser.exe

是不是因为在系统根目录下?是缓存在 Powershell 配置文件中还是什么?由于将它添加到 root 是一次性的事情,我不知道它会影响我的脚本,但我很惊讶地看到这种行为。

这似乎是在开发人员可能意外或无意间在 32 位和 64 位 Powershell 环境之间切换的情况下进行开发时的常见陷阱。

我进行了以下测试:

测试:仅在 system32 中创建文件并从 32 位和 64 位 PowerShell 检查 system32 和 syswow64。 结果:两者的 32 位会话 returned FALSE。 64 位会话 return对于 system32 为 TRUE,对于 syswow64 为 FALSE。

测试:仅在 syswow64 中创建文件并检查两个会话的两个路径。 结果:两者的 32 位会话 returned 为 TRUE。 64 位会话 return对于 system32 为 FALSE,对于 syswow64 为 TRUE。

测试:在两个位置创建文件并检查两个会话的两个路径。 结果:两个会话 return 两个路径都为 TRUE。

测试:在两个位置创建文件并仅从 system32 中删除。 结果:两者的 32 位会话 returns TRUE。 64 位会话 return仅适用于 syswow64。

测试:在两个位置创建文件并仅从 syswow64 中删除。 结果:两者的 32 位会话 returned FALSE。 64 位会话 returned TRUE 仅适用于 system32。

从这个测试来看,64 位版本似乎能够准确地检查 system32 和 syswow64 中的文件。 32 位应用程序似乎默认使用 wow64。如果文件存在,无论 system32 中有什么,它都会 return true,如果文件不存在,无论 system32 中有什么,它都会 return false。

感谢@Mathias R. Jessen 询问该文件是否存在于 syswow64 目录中,因为这让我想起我以前见过这个。

看来这都和wow64下key的重定向反射有关。有关详细信息,请在 msdn Microsoft 文档中搜索 "Registry Keys affected by WOW64"。本文https://support.microsoft.com/en-us/help/305097/how-to-view-the-system-registry-by-using-64-bit-versions-of-windows

包含一些相关信息并包括以下有趣的行:"To support the co-existence of 32-bit and 64-bit COM registration and program states, WOW64 presents 32-bit programs with an alternate view of the registry."