测试路径-使用变量时路径中的非法字符

时间:2019-07-03 11:44:40

标签: powershell

对于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

2 个答案:

答案 0 :(得分:2)

此声明:

$newFile = Out-String -InputObject $newFile

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

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

答案 1 :(得分:0)

您可以轻松地按以下步骤进行操作:

$file = "C:\Users\tom\Desktop\test\0_InstalledPrograms.log"
$splittedName = (Split-Path $file -leaf).split('_')
$newFileName = [string]([int]$splittedName[0] + 1) +'_'+ $splittedName[1]

Move-Item -Path $file -Destination (Join-Path (Split-path $file) -ChildPath $newFileName)