PowerShell中Get-FileHash用变量路径报错,直接指定路径正常的问题排查
问题排查与解决:Get-FileHash路径错误问题
问题描述
执行以下代码生成文件哈希时出现报错:
$newHash = (Get-FileHash $PathToFile -Algorithm $Algorithm).hash
错误提示:
Get-FileHash: Cannot find the path '/Users/name/Downloads' /Users/name/Downloads/filename.txt'' because it does not exist.
但直接硬编码文件路径运行相同逻辑却能正常工作:
$newHash = (Get-FileHash '/Users/name/Downloads/filename.txt' -Algorithm $Algorithm).hash
完整原始代码如下:
$VendorHash = Read-Host -Prompt "Paste hash here.." if ($VendorHash) { Write-Host "Continue.." } else { Write-Warning -Message "You must paste hash here.." } $PathToFile = Read-Host -Prompt "Drop file here.." $Algorithm = Read-Host -Prompt "Enter algorithm.." if ($PathToFile) { Write-Host "Generating hash please wait.." } else { Write-Warning -Message "Path to file is missing.." } $NewHash = (Get-FileHash -Path $PathToFile -Algorithm $Algorithm).hash Compare-Object -ReferenceObject $VendorHash -DifferenceObject $NewHash
报错原因
当你在macOS终端拖拽文件到Read-Host输入框时,系统会自动给路径添加单引号(如果路径含空格还会额外处理),但Read-Host会把这些单引号一并读取为字符串的一部分。比如$PathToFile的实际值是'/Users/name/Downloads/filename.txt'(带首尾单引号),传给Get-FileHash时,PowerShell会把单引号当成路径的一部分,导致路径格式错乱,出现无效的路径字符串。
解决方法
在获取$PathToFile后,添加代码去除字符串首尾的单引号或双引号,确保路径是纯净的有效路径:
修正后的完整代码
$VendorHash = Read-Host -Prompt "Paste hash here.." if ($VendorHash) { Write-Host "Continue.." } else { Write-Warning -Message "You must paste hash here.." } $PathToFile = Read-Host -Prompt "Drop file here.." # 去除路径首尾的单引号和双引号 $PathToFile = $PathToFile.Trim("'""") $Algorithm = Read-Host -Prompt "Enter algorithm.." if ($PathToFile) { Write-Host "Generating hash please wait.." } else { Write-Warning -Message "Path to file is missing.." } # 额外添加路径存在校验,增强健壮性 if (Test-Path -Path $PathToFile) { $NewHash = (Get-FileHash -Path $PathToFile -Algorithm $Algorithm).hash Compare-Object -ReferenceObject $VendorHash -DifferenceObject $NewHash } else { Write-Warning "File path does not exist: $PathToFile" }
内容的提问来源于stack exchange,提问作者mrn3ff
相关产品推荐
相关产品推荐

