64位PowerShell运行C#开发的CLI程序为何报64位环境异常?
问题:64位PowerShell运行CLI程序却提示需64位进程
我用C#开发了一款调用外部API的命令行程序(CLI),在cmd或bat文件中独立运行完全正常,但通过PowerShell脚本运行时,却抛出System.BadImageFormatException错误,提示ReMetrica API只能在64位进程中使用。但当前PowerShell进程确实是64位的(执行[Environment]::Is64BitProcess返回True)。
错误日志如下:
=== RM Tool - Remetrica Command Line Interface === RMTool.exe : At X:\Activities\2022\Remetrica Automation\prod_test_rmtool.ps1:1 char:1 + & rmtool.exe sample -r "X:/Activities/2022/Remetrica Automation/RM/20 ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError Unhandled Exception: System.TypeInitializationException: The type initializer for 'Aon.ReMetrica.Framework.Api.ReMetrica' threw an exception. ---> System.BadImageFormatException: The ReMetrica API can only be used in a 64 bit process. at Aon.ReMetrica.Framework.Api.ReMetrica..cctor() --- End of inner exception stack trace --- at Aon.ReMetrica.Framework.Api.ReMetrica.get_Study() at RemetricaController.RMTool.ExexSampleAndReturnExitCode(SamplePropertyOptions opts, TextWriter infoWriter, StreamWriter logWriter) in X:\Activities\2022\Remetrica Automation\RMTool\RMTool.cs:line 208 at RemetricaController.RMTool.<>c__DisplayClass5_0.<Main>b__0(SamplePropertyOptions opts) in X:\Activities\2022\Remetrica Automation\RMTool\RMTool.cs:line 131 at CommandLine.ParserResultExtensions.MapResult[T1,T2,T3,T4,T5,TResult](ParserResult`1 result, Func`2 parsedFunc1, Func`2 parsedFunc2, Func`2 parsedFunc3, Func`2 parsedFunc4, Func`2 parsedFunc5, Func`2 notParsedFunc) at RemetricaController.RMTool.Main(String[] args) in X:\Activities\2022\Remetrica Automation\RMTool\RMTool.cs:line 128 PS C:\Windows\system32> [Environment]::Is64BitProcess True
可能的原因及解决办法
1. 程序目标平台设置不当
如果你的CLI项目编译时目标平台设为Any CPU或x86,可能在PowerShell环境中以32位模式运行。
- 打开C#项目属性 → 生成 → 目标平台,确认设置为
x64,重新编译程序。 - 在PowerShell脚本中指定64位程序的完整路径调用,避免系统误加载32位版本。
2. 文件系统重定向导致依赖加载错误
64位Windows中,32位程序会被自动重定向到SysWOW64目录,可能导致程序加载32位版本的依赖DLL。
- 在PowerShell脚本中临时禁用文件系统重定向,再调用程序:
$ptr = [System.IntPtr]::Zero try { $ptr = [Microsoft.Win32.Win32Native]::Wow64DisableWow64FsRedirection() & rmtool.exe sample -r "X:/Activities/2022/Remetrica Automation/RM/20..." } finally { if ($ptr -ne [System.IntPtr]::Zero) { [Microsoft.Win32.Win32Native]::Wow64RevertWow64FsRedirection($ptr) } }
3. 依赖库位数不匹配
CLI程序本身是64位,但依赖的ReMetrica API或其他第三方DLL是32位,导致加载失败。
- 使用
dumpbin /headers工具或Process Explorer检查程序依赖的所有DLL位数,确保全部为64位,替换不匹配的依赖文件。
4. PowerShell环境被强制为32位
即使你打开的是64位PowerShell,某些场景下环境变量可能被修改为32位上下文。
- 执行
echo $env:PROCESSOR_ARCHITECTURE,确认返回AMD64;若返回x86,则需启动原生64位PowerShell(路径为C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe)。
内容的提问来源于stack exchange,提问作者DavveK
相关产品推荐
相关产品推荐

