Copy-Item: Illegal characters in path - powershell

I'm trying to create a powershell script that will copy files from a source to the same path on multiple destination machines. I found this on the web and have pointed toward my test data, however, I continue to receive the following error (for each system it finds in the pc_list.txt).
Script:
$Computers = gc "C:\Temp\Script\PC_List.txt"
$Source = "C:\Temp\Script\AAAAA.txt"
$Destination = "C$\Temp\"
foreach ($Computer in $Computers) {
Copy-Item -Path $Source -Destination "\\$Computer\$Destination\" -Recurse
}
Error:
Copy-Item : Illegal characters in path.
At line:4 char:36
+ ... Computers) {Copy-Item $Source -Destination "\\$Computer\$Destination\ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.CopyItemCommand
PC Names in PC_List.txt:
DEPT-PC1
DEPT-PC2
DEPT-PC3
Can someone point me in the right direction?

BenH is correct. While I did not have any blank lines in the PC_List.txt, I did have a space at the end of each line... Great catch!!!
Now I’m getting “The target account name is incorrect”.
I’m thinking I’m going to need to add a $session credentials line but will need to figure out how to implement that piece...

Related

How to use * in a powershell path with [

I need to copy images generated by software (HWMonitorPro). Folders and sub-folders of images cannot be modified (or I did not find how).
The images are stored in the following path:
C:\Users\hugo\Documents\DossierTest\logs\[JUN 13, 2022 - 11:06]\[LAPTOP-P15V]\[1280x960].
As you can see, a directory is created with each recording, with the date and time.
So I decided to use the following technique to be able to take the images of several captures at once:
$C = "C:\Users\hugo\Documents\DossierTest\logs"
copy-item $C'\*\`[LAPTOP-P15V`]\`[1280x960`]\789.txt' -Destination $C\test3
The line works with "[JUN 14, 2022 - 9:22]" instead of "*". This is what I get when I use the line show above:
PS C:\Windows\system32> C:\Users\hugo\Documents\DossierTest\ScriptCC.ps1
Copy-Item : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: [LAPTOP-P15V
At C:\Users\hugo\Documents\DossierTest\ScriptCC.ps1:3 char:1
+ copy-item $C'\*\`[LAPTOP-P15V`]\`[1280x960`]\789.txt' -Destination $C ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Copy-Item], ParameterBindingException
+ FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.CopyItemCommand
If anyone could help me solve my problem that would be great!
PS: I'm French, sorry if it's badly written.
As it seems there's something strange with paths containing square brackets, you can use CopyTo method to copy files instead of copy-item cmdlet.
E.g. like this:
$rootfolder = "E:\tmp\logs"
$destfolder = "E:\tmp\foldertest3"
$allfiles = gci $rootfolder -File -Recurse
foreach ($file in $allfiles) {
$newfile = $file.CopyTo("$destfolder\$($file.Name)")
}
This copies all files in subdirectories to single destination folder =
you'll need to deal with t further in case there are files with same name in different subfolders.
PS: Your $C is really a terrible variable name when dealing with file paths :-)

Powershell Copy-item fails on unc path with space and ampersand

I am trying to use the powershell Copy-Item command to copy a file to a UNC Path.
Unfortunately, the UNC path on this production server has both spaces and an ampersand in the name.
I've tried a bunch of things, but haven't had any luck yet.
Could you please suggest a way to resolve this issue.
$InvokeExpressionPath = "\\servername\This Folder Has Spaces & Ampersand\Folder"
$TransfersSharePath = Invoke-Expression $InvokeExpressionPath
$TransfersSharePathFile = $InvokeExpressionPath + "\" + $FileName
Copy-Item -Path $CheckFileExists -Destination $TransfersSharePathFile -Force -ErrorAction SilentlyContinue
This is the error message that I get:
Invoke-Expression : At line:1 char:41
+ \\servername\This Folder Has Spaces & Ampersand\Folder
+ ~
The ampersand (&) character is not allowed. The & operator is reserved for future use; wrap an ampersand in double quotation marks ("&") to pass it as part of a string.
At E:\Scripts\CopyFile_Test.ps1:33 char:27
+ $TransfersSharePath = Invoke-Expression $InvokeExpressionPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ParserError: (:) [Invoke-Expression], ParseException
+ FullyQualifiedErrorId : AmpersandNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
If I try to wrap the ampersand in double-double quotes (""&""), I get this error when the code runs.
\\servername\This : The term '\\servername\This' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At line:1 char:1
+ \\servername\This Folder Has Spaces "&" Ampersand\Folder
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\servername\This:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
DEBUG: This is the value of TransfersSharePathFile - \\servername\This Folder Has Spaces & Ampersand\Folder\file.zip
Copy-Item : Illegal characters in path.
At E:\Scripts\CopyFile_Test.ps1:36 char:5
+ Copy-Item -Path $CheckFileExists -Destination $TransfersSharePathFile -Force ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.CopyItemCommand
Thanks in advance for your help.
Thanks very much to AdamL and dread1 for their help. I used both suggestions.
For reference, this is what the working code now looks like.
$InvokeExpressionPath = "\\servername\This Folder Has Spaces & Ampersand\Folder"
$TransfersSharePathFile = Join-Path -Path $InvokeExpressionPath -ChildPath $FileName
$TransfersSharePathFile = $InvokeExpressionPath + "\" + $FileName
Copy-Item -Path $CheckFileExists -Destination $TransfersSharePathFile -Force -ErrorAction SilentlyContinue
Ampersand or spaces in path are not the problem. You're trying to use Invoke-Expression supplying path as parameter, which is not a valid command. Get rid of $TransfersSharePath line and use what's in $InvokeExpressionPath directly. Just change double quotation marks to single just in case. Also I suggest you create path using Join-Path instead of contatenating the strings.
Try:
$InvokeExpressionPath = '\\servername\This Folder Has Spaces & Ampersand\Folder'
Should do the job

PowerShell script to copy a file from a Mapped Network Drive to a Subfolder of the same mapped, network drive then add the date to the file name

I'm new to PowerShell and have read many of the similar questions. The answers seem way to complicated for what I want to do.
I want to:
Copy a file, testVerifyLog.xlsm
Paste into a subfolder of the same mapped network drive named:
Copies of Logs
Rename the file with the current date (YYYYMMDD) added to the
end, so that the final result for June 1, 2020 is:
testVerifyLog_20200601.xlsm
The code below is what I have come up with but obviously does not work. The error I get in the PowerShell ISE is:
copy-item : Illegal characters in path.
At \TheMappedDrive\Share\AllDepts\OneDept\VerifyLogsMove.ps:2 char:1
copy-item testVerifyLog.xlsm -
destination'\TheMappedDrive\Share\AllDepts\OneDept...
CategoryInfo : NotSpecified: (:) [Copy-Item], ArgumentException
FullyQualifiedErrorID :
System.ArgumentException,Microsoft.PowerShell.Commands.CopyItemCommand
Set-Location \\TheMappedDrive\Share\AllDepts
copy-item testVerifyLog.xlsm -destination '\\TheMappedDrive\Share\AllDepts\OneDept\Copies of Logs\testVerifyLog ; testVerifyLog-$(((get-date).ToUniversalTime()).ToString("yyyyMMdd")).xlsm'
Something like this
$curDate = Get-Date -Format yyyyMMdd
$destinationFolder = '\\TheMappedDrive\Share\AllDepts\OneDept\Copies of Logs\testVerifyLog'
$destinationFile = Join-Path $destinationFolder -ChildPath ('testVerifyLog_' + $curDate + '.xlsm')
copy-item '\\TheMappedDrive\Share\AllDepts\testVerifyLog.xlsm' -destination $destinationFile

Array with Commands

I have a list of files which I would like to move to other destinations. Issues:
Destination is different
Errors can occur, e.g. File does already exist in Destination.
If so, I would like to delete the existing file (e.g. $StartM\C\A.Lnk)
How can I do this with a list / foreach or other possibility?
Move-Item -Path "$StartM\C\A.Lnk" -Destination "$StartM\Maintenance"
Move-Item -Path "$StartM\C\B.Lnk" -Destination "$StartM"
The canonical way of dealing with a situation like that is to define a mapping between sources and destinations:
$shortcuts = #{
"$StartM\C\A.Lnk" = "$StartM\Maintenance"
"$StartM\C\B.Lnk" = "$StartM"
}
and then process that mapping like this:
foreach ($src in $shortcuts.Keys) {
Remove-Item $shortcuts[$src] -Force -EA SiltenlyContinue
Move-Item $src -Destination $shortcuts[$src]
}
Thank you Ansgar. I got some issues:
1. Remove-Item:
The Argument can not be bound with the Parameter "Path", because it is an empty string.
CategoryInfo: InvalidData: (:) [Remove-Item], ParameterBindingValidationException
FullyQualifiedErrorId: ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.RemoveItemCommand
2. Move-Item:
No position parameter was found, which accept the argument "\Maintenance"
May be there is a missunderstanding. Source should be deleted if exists in Destination. E.g.: "$StartM\C\A.Lnk" = "$StartM\Maintenance".
Goal: "$StartM\C\A.Lnk" should be deleted if "A.Lnk" exists in "$StartM\Maintenance\A.Lnk".
Move-Item $src = $shortcuts[$src]
CategoryInfo: InvalidArgument: (:) [Move-Item], ParameterBindingException
FullyQualifiedErrorId: PositionalParameterNotFound,Microsoft.PowerShell.Commands.MoveItemCommand
3. ErrorAction
Remove-Item: The Parameter "ErrorAction" can not be bound. Type "SiltenlyContinue" can not be converted in type "System.Management.Automation.ActionPreference" ...
I just changed "-EA" ... -Force -EA SilentlyContinuefrom to "-Error Action". This type of Error has gone.
4. Double keys
If there are some constelations in the array like this:
"$StartM\C\B.Lnk" & "$End\C\B.Lnk" I got an error that double keys are not allowed in Hashliterals.
CategoryInfo : InvalidOperation: (System.Collections.Hashtable:Hashtable) [], RuntimeException
FullyQualifiedErrorId : DuplicateKeyInHashLiteral

Move-Item with -match and -LiteralPath not working

I have a file move script that looks for files with keywords in the name and moves them to a specific folder. There's about a hundred lines that all work fine, except for one of them, and the only thing I can think of is that the file has brackets in the name.
I'm already using -LiteralPath to grab the full path, but the error is weird. I've tried double quotes, double backticks, and some other options that I've found elsewhere on the boards, but nothing is working.
Here is all the relevant parts of the script (without posting the whole thing):
# Source folders
$RecipesFolder = "F:\Downloads\Downloaded Recipes\"
# Destination Folders Drive I
$CoffeeRecipes = "I:\My Recipes\Coffee Recipes\"
# Get list of files
$Files = Get-ChildItem $RecipesFolder -File -Recurse
# Process Files
foreach ($File in $Files) {
if ($File -match "Coffee") {
Move-Item -LiteralPath $RecipesFolder$File -Destination "$CoffeeRecipes" -Force
}
It's a really simple script, and every other line works fine, except that one. All the lines are written identically.
This is the full error I get (sourcepath obfuscated for security), and thank you in advance for any assistance:
Move-Item : Cannot move item because the item at 'F:\Downloads\Downloaded Recipes\[1]
Coffee Recipe - 11[1].txt' does not exist.
At Path-to-powershell-script-file:153 char:13
+ Move-Item -LiteralPath $RecipesFolder$File -Destina ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Move-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand
When I receive this error, the file disappears, and doesn't get moved to the folder, it just vanishes.