HondaKillrsx
HondaKillrsx

Reputation: 349

Getting error when using Copy-Item in Simple Powershell Script

I receive the error message "Illegal Characters in path" when running the following simple script that utilizes the Copy-Item command:

$Files = Get-Content output.txt
  ForEach($File in $Files){
     echo $File
     $Directory = Split-Path -Parent $File
     $newDirectory = ($Directory | Out-String) -replace "C:\\test", "C:\Backup"
    echo $newDirectory
    Copy-Item $File $newDirectory -force -recurse
}

As you can see the $Files variable is pulling each line into an array. Each line is actually a file path and name. The echo outputs look fine and are below:

  1. C:\test\testing\text.txt

  2. C:\Backup\testing

The first is the orginal file location that is to be copied, the second is the folder to copy it into. Can anyone help me figure out what the "Illegal character" is in these two paths. The error points to the source path.

Full Error Code is below:

 Copy-Item : Illegal characters in path.
 At C:\users\lane.pulcini\desktop\searchfiles\testcopy.ps1:7 char:10
 + Copy-Item <<<<  $File $newDirectory -force -recurse
 + CategoryInfo          : NotSpecified: (:) [Copy-Item], ArgumentException
 + FullyQualifiedErrorId :       S   System.ArgumentException,Microsoft.PowerShell.Commands.CopyItemCommand

Upvotes: 0

Views: 4094

Answers (1)

Tony Hinkle
Tony Hinkle

Reputation: 4742

Out-String is putting something on the end of the string, so you need to trim it:

$newDirectory = (($Directory | Out-String) -replace "C:\\test", "C:\Backup").TrimEnd()

...or, remove Out-String--I'm not sure why you have it there:

$newDirectory = $Directory -replace "C:\\test", "C:\Backup"

You can see this by checking the length property:

PS C:\> $d = $Directory | out-string
PS C:\> $d.Length
17
PS C:\> $Directory.Length
15

If you want the script to create the subfolder under C:\Backup if it doesn't exist, place the following before the Copy-Item line:

if(!(test-path $newDirectory)){
    New-Item $newDirectory -type directory
}

Upvotes: 2

Related Questions