首页 > 解决方案 > 测试路径 - 使用变量时路径中的非法字符

问题描述

我对 PowerShell 相当陌生,如果这是一个愚蠢的问题,我提前道歉。

我正在尝试构建一个新的目标/文件名,在其中我采用旧文件名并用 +1 增加它的前缀

$destination = Split-Path -Path 'C:\Users\tom\Desktop\test\0_InstalledPrograms.log'
$file =  split-path "C:\Users\tom\Desktop\test\0_InstalledPrograms.log" -Leaf

$array = $file -split '_'
$prefix = $array[0] + 1
$suffix = $array[1]
$newFile = $prefix + '_' + $suffix
$newFile = Out-String -InputObject $newFile
$destination = $destination + '\' + $newFile

Test-Path $destination

Test-Path : Illegal characters in path.
At C:\Users\tom\Desktop\incrementFileName.ps1:18 char:1
+ Test-Path $destination
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (C:\Users\lgranc...dPrograms.log
:String) [Test-Path], ArgumentException
    + FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.TestPathCommand

False

标签: powershell

解决方案


这个说法:

$newFile = Out-String -InputObject $newFile

在字符串中添加一个新行(CR+LF),并且完全没有必要($newFile已经是一个字符串)。

删除该行,它将起作用:)


推荐阅读