我有以下的代码,适用于大多数文件。输入文件(FoundLinks.csv)是一个UTF-8文件,每行一个文件路径。这些文件路径是需要处理的特定驱动器上的完整路径。
$inFiles = @()
$inFiles += @(Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv")
foreach ($inFile in $inFiles) {
Write-Host("Processing: " + $inFile)
$objFile = Get-ChildItem -LiteralPath $inFile
New-Object PSObject -Prop @{
FullName = $objFile.FullName
ModifyTime = $objFile.LastWriteTime
}
}
但是,即使我使用了-LiteralPath,它仍然无法处理文件名中包含非断空格的文件。
Processing: q:\Executive\CLC\Budget\Co 2018 Budget - TO Bob (GA Prophix).xlsx
Get-ChildItem : Cannot find path 'Q:\Executive\CLC\Budget\Co 2018 Budget - TO Bob (GA Prophix).xlsx'
because it does not exist.
At ListFilesWithModifyTime.ps1:6 char:29
+ $objFile = Get-ChildItem <<<< -LiteralPath $inFile
+ CategoryInfo : ObjectNotFound: (Q:\Executive\CL...A Prophix).xlsx:String) [Get-ChildItem], ItemNotFound
Exception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
我知道我的输入文件路径中有不间断空格,因为我可以在记事本中打开它,复制有问题的路径,将其粘贴到Word中,并打开段落标记。在2018年之前它显示正常空格后跟着一个NBSP。
PowerShell读取NBSP吗?我是否将其传递给-LiteralPath时出了问题?我已经无计可施了。我看到此解决方案,但在那种情况下,他们是在脚本中提供字面路径,所以我不知道如何使用该方法。
我还尝试过:在Get-Content上使用
-Encoding UTF8
参数,但没有任何区别。我甚至不确定如何在代码中检查$inFile,只是为了确认它是否仍然包含NBSP。
感谢任何帮助来解决这个问题!
确认$inFile中有NBSP
谢谢大家!根据@TheMadTechnician的建议,我已经更新了代码,并且将我的输入文件减少到只有一个文件有问题。
$inFiles = @()
$inFiles += @(Get-Content -Path "C:\Users\sw_admin\FoundLinks.csv" -Encoding UTF8)
foreach ($inFile in $inFiles) {
Write-Host("Processing: " + $inFile)
# list out all chars to confirm it has an NBSP
$inFile.ToCharArray()|%{"{0} -> {1}" -f $_,[int]$_}
$objFile = Get-ChildItem -LiteralPath $inFile
New-Object PSObject -Prop @{
FullName = $objFile.FullName
ModifyTime = $objFile.LastWriteTime
}
}
现在我可以确认$inFile确实仍然包含NBSP,就像它传递给Get-ChildItem一样。然而,Get-ChildItem却说文件不存在。
我尝试过以下操作:
- 如果我使用Get-Item而不是Get-ChildItem,则结果相同。 - 如果我使用-Path而不是-LiteralPath,则结果相同。 - Windows资源管理器和Excel可以成功处理该文件。
我使用的是Windows 7机器,PowerShell版本为2。
再次感谢所有回复!
-LiteralPath
?我没有看到你的路径中有任何可以被解释为通配符语言的内容。 - Maximilian Burszley$inFiles [4]
(第5个文件)有一个NBSP。您可以运行此命令,并查找应该是NBSP的内容,然后查看旁边空格的数字是否与其相同:$inFiles [4] .ToCharArray() |%{“ {0} - > {1}” -f $ _,[int] $ _}
- TheMadTechnician