You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell获取DLL文件版本时遇类型转换错误求助

解决PowerShell获取DLL版本时的类型转换错误

问题场景

编写PowerShell脚本获取DLL文件版本,目标文件确认存在版本信息,脚本如下:

$version = ''
$file = Get-ChildItem $path
$version = $file.VersionInfo.FileVersion

脚本有时能正常输出类似2023.3.0.8的版本号,但偶尔触发类型转换错误:

Cannot convert value "2023.3.0.8" to type "System.Int32". Error:
"Input string was not in a correct format."

  • $version = $file.VersionInfo.FileVersion
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  • CategoryInfo : MetadataError: (:) [],
    ParentContainsErrorRecordException
  • FullyQualifiedErrorId : RuntimeException

问题原因

PowerShell的动态类型特性导致:如果$version变量之前被赋值过整数类型(比如在之前的脚本执行或交互式会话中),后续赋值字符串格式的版本号时,PowerShell会自动尝试将字符串转换为整数,而带点的版本号无法转换为Int32,从而抛出错误。即使初始化为空字符串,若变量类型被后续操作修改,也会触发该问题。

解决方案

1. 显式声明变量类型为字符串

强制$version始终为字符串类型,避免自动类型转换:

# 显式声明字符串类型变量
[string]$version = $null
# 若$path是单个文件路径,用Get-Item比Get-ChildItem更准确
$file = Get-Item $path
$version = $file.VersionInfo.FileVersion

2. 避免提前初始化变量,直接赋值

跳过不必要的空字符串初始化,直接赋值版本号,让PowerShell自动推断正确的字符串类型:

$file = Get-Item $path
$version = $file.VersionInfo.FileVersion
# 直接使用版本号,例如输出
Write-Output $version

3. 清除已有变量(适用于交互式会话或脚本复用场景)

如果脚本在交互式会话中运行,先清除可能存在的旧变量,避免类型污染:

# 清除之前的$version变量(忽略不存在的错误)
Remove-Variable version -ErrorAction SilentlyContinue

$file = Get-Item $path
$version = $file.VersionInfo.FileVersion

额外优化建议

  • 若$path指向单个文件,优先使用Get-Item而非Get-ChildItem,后者更适合批量获取目录下的文件,避免返回多个文件导致的意外问题。
  • 可以添加错误处理,确保文件存在且能正常获取版本信息:
if (Test-Path $path -PathType Leaf) {
    $file = Get-Item $path
    [string]$version = $file.VersionInfo.FileVersion
    Write-Output "文件版本:$version"
} else {
    Write-Error "目标文件不存在:$path"
}

内容的提问来源于stack exchange,提问作者Naveen V

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 15:49:53