Powershell 字符串未正确连接

Powershell strings are not concatenating properly

所以我有

$Logfilename = "E:\Deployment Logs201026 - 1_ProductInfo"
Write-Host $Logfilename
E:\Deployment Logs201026 - 1_ProductInfo


$Newname = $Logfilename + ".log"
Write-Host $Newname
.logeployment Logs201026 - 1_ProductInfo


Get-Content -Path "E:\Deployment Logs201026 - 1_ProductInfo.log"
#returns file normally

但是,当我尝试从变量名 运行 Get-Content 时,出现此错误。这也很奇怪,因为错误消息显示了一个字符串,但上面的 Write-Host .logeployment Logs201026 - 1_ProductInfo 显示了不同的字符串。

Get-Content -Path $Newname
Get-Content : Illegal characters in path.
At line:1 char:1
+ Get-Content -Path $Newname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (E:\Deployment L...roductInfo.log:String) [Get-Content], ArgumentException
    + FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.GetContentCommand
 
Get-Content : Cannot find path 'E:\Deployment Logs201026 - 1_ProductInfo.log' because it does not exist.
At line:1 char:1
+ Get-Content -Path $Newname
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (E:\Deployment L...roductInfo.log:String) [Get-Content], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

我完全不知道这里发生了什么。该文件肯定存在于给定路径中。我尝试为隐藏的 \r 和 \n 字符添加 .replace 无济于事。我尝试通过 Out-String 编写变量内容并添加 .log 然后发生同样的事情。对此有任何解释或修复吗?

根据评论中的对话,您的脚本文件在 $Logfilename = "E:\Deployment Logs201026 - 1_ProductInfo" 行的字符串末尾有一个隐藏的 Carriage Return 字符(尚未复制到您问题中的脚本中).

当您使用 write-host 输出字符串时,Carriage Return 将光标移回控制台行的开头,然后继续写入字符串的其余部分。

一个简单的复制是:

PS> "E:\Deployment Logs201026 - 1_ProductInfo$([char]0x000D).log"
.logeployment Logs201026 - 1_ProductInfo

Carriage Return 不是文件名中的有效字符,这就是您也看到错误的原因。它看起来也被从错误消息中删除了,所以它只是显示了两个串联字符串的“预期”值:

Get-Content : Cannot find path 'E:\Deployment Logs201026 - 1_ProductInfo.log' because it does not exist.

这可能是因为您从其他系统剪切并粘贴了原始值,并且在不知情的情况下拾取了隐藏的字符。

要修复它,只需删除 $Logfilename = "E:\Deployment Logs201026 - 1_ProductInfo" 行中的最后几个字符,然后手动删除 re-type 它们。您可能会注意到,当您删除字符时,有一次您按 delbackspace 时似乎什么都没有发生 - 那就是您删除 non-printing 字符。

更新

如果评论被删除,我们通过以下测试解决了这个问题:

PS E:\Deployment Plans> $Logfilename.length
44

PS E:\Deployment Plans> $Newname.length
48

PS> "E:\Deployment Logs201026 - 1_ProductInfo".Length
43

PS> "E:\Deployment Logs201026 - 1_ProductInfo.log".Length
47

这告诉我们 $Logfilename 末尾可能有一个额外的 non-printing 字符。

下一个:

PS> [System.Text.Encoding]::UTF8.GetBytes("E:\Deployment Logs201026 - 1_ProductInfo.log".)
.
.
73
110
102
111

但是

PS> [System.Text.Encoding]::UTF8.GetBytes($Logfilename)
.
.
73
110
102
111
13

所以额外的字符是 UTF 字符 13(十进制),即 U+000D,即回车 Return - 参见 http://www.fileformat.info/info/unicode/char/000d/index.htm