Getting error when using Copy-Item in Simple Powershell Script - powershell

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:
C:\test\testing\text.txt
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

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
}

Related

Unable to work with lines i csv created by export-csv

After running this script:
# Input path
$input_path = 'C:\Users\larry\Pictures\2003'
# Export file
$documents_export_file = 'C:\Users\larry\Documents\Temp\ffmpeg\fullnames.csv'
# Copy-to folder
$copy_to = "C:\Users\larry\Documents\Temp\ffmpeg\movies"
# List filenames in $documents_export_file
Get-ChildItem -Attributes !Directory -Path $input_path -Recurse -force | select-object -Property fullName | Export-Csv $documents_export_file
# Copy the files listed in $documents_export_file to $copy_to folder
get-content $documents_export_file | Foreach-Object { copy-item -Path $_ -Destination $copy_to}
I get the following error:
copy-item : Cannot find drive. A drive with the name '"C' does not exist.
At line:18 char:55
+ ... ort_file | Foreach-Object { copy-item -Path $_ -Destination $copy_to}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: ("C:String) [Copy-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
copy-item : Cannot find drive. A drive with the name '"C' does not exist.
At line:18 char:55
+ ... ort_file | Foreach-Object { copy-item -Path $_ -Destination $copy_to}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: ("C:String) [Copy-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
As far as I can figure out, it has something to do with my Export-Csv, bur I canĀ“t figure it out.
Please give me a hand.
There's no need to export the list of files to CSV in the first place - assign the output from Get-ChildItem to a variable instead, and then pipe the contents directly to Copy-Item:
$files = Get-ChildItem -Attributes !Directory -Path $input_path -Recurse -Force
$files |Copy-Item -Destination $copy_to

PowerShell copy-item

I am trying to copy latest 30days files to the folder by this code:
$month = (get-date).AddDays(-30).ToString("yyyMM")
$lastmonthfiles = Write-Host (-join('DCP_', $month,"*.csv"))
Copy-Item -Path Write-Host (-join ("C:\DC+\History\", $lastmonthfiles)) -Destination C:\DC+\History\Backup
but I am having a problem in path in copy-item instruction, which is
Copy-Item : A positional parameter cannot be found that accepts argument 'C:\DC+\History\'.
At line:5 char:1
+ Copy-Item -Path Write-Host (-join ("C:\DC+\History\", $lastmonthfiles ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Copy-Item], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
I am new in PowerShell, and programming so, I could not understand, how can I update and achieve a goal.
Try this:
$Source = Get-Item "C:\Games"
$Destination = "E:\Backup"
$LogFile = "C:\Copy-LogFile.txt"
Copy-Item -Path $( $Source | Where LastWriteTime -LE (Get-Date).AddDays(-30) ) -Destination $Destination -Recurse -PassThru |
Out-File $LogFile -Force
This takes care of your copy function and generates an output log.
Sorry, but your code makes no sense to me...
If it is your aim to copy files to a subfolder in a backup path, try this:
# get the date to use as subfolder to copy to and also to filter the last 30 days files
$refDate = (Get-Date).AddDays(-30).Date # .Date sets it to midnight
# set this variable to the folder where the csv are to be found
$sourceFolder = 'X:\Path\To\Where\The\Files\Are'
# create a destination path to copy to (just a string)
$destination = Join-Path -Path 'C:\DC+\History\Backup' -ChildPath ($refDate.ToString("yyyMM"))
# create this destination folder
$null = New-Item -Path $destination -ItemType Directory -Force
# get the files and copy them to the destination folder
Get-ChildItem -Path $sourceFolder -Filter '*.csv' -File | # filter on CSV fies only
Where-Object { $_.LastWriteTime -ge $refDate } | # filter on date 'last 30 days'
Copy-Item -Destination $destination -Force

Powershell | Rename file with random name

I'm making a script to rename a specific file with a random name. But when running, the following error always occurs:
It is not possible to convert the value ".jpg" to the type "System.Int32". Error: "The input string was not in the correct format."
In C:\Windows\system32\WindowsPowerShell\v1.0\Modules\SetDiscordWallpaper\SetDiscordWallpaper.ps1:7 character:7
+ Rename-Item -Path $file.FullName -NewName ($random + $file.Exte ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger
Here is the code I am using
function Set-DiscordWallpaper {
$path = "C:\Windows\Temp\*"
foreach($file in $(Get-ChildItem -Path $path -Include "Wallpaper.jpg")) {
$extension = [System.IO.Path]::GetExtension($file.FullName);
$randomName = [System.IO.Path]::ChangeExtension([System.IO.Path]::GetRandomFileName(), $extension)
$newPath = "C:\inetpub\wwwroot\"
Write-Host "Changing File $($file.Name) to $randomName"
Move-Item -Path $file.FullName -Destination $newPath
}
}
I ask you to help me please. I'm waiting the answer. Thanks
The code (second part in your question) creates the new random filename just fine, only the line Move-Item -Path $file.FullName -Destination $newPath does nothing with that new name and moves the file with its original name to the new path.
Change that line to
Move-Item -Path $file.FullName -Destination (Join-Path -Path $newPath -ChildPath $randomName)
so the file gets moved with the random name in the new path.
Or is your intention to copy the file to its new destination keeping the original filename there and after that rename the original?
In that case do:
Write-Host "Changing File $($file.Name) to $randomName"
Copy-Item -Path $file.FullName -Destination $newPath # copy with original name
$file | Rename-Item -NewName $randomName # rename the original file

Error message in script

I am trying to script a solution copying some files from one location to another..
I have a list of files in a .csv format, with headers
"ParentFolder, Name, FullName, lastwritetime."
Content of file is, which has hundreds of lines, and different paths, but same drive letter:
"X:\clients\A90\201AA3.05\","2012.08 RAP Proposal.xlsm","X:\clients\A90\201AA3.05\2012.08 RAP Proposal.xlsm","20/05/2016 10:41:08"
What i would like to do is copy the above..
"X:\clients\A90\201AA3.05\2012.08 RAP Proposal.xlsm" to a new location with differnet drive, but same directory structure. So in the csv file i have the filename and path, but am unsure how to split the drive from there and make a variable.
I have a foreach loop..
$ToCopy = Import-Csv "c:\temp\log.csv"
foreach($Line in $ToCopy)
{
$FullPath = $Line.ParentFolder
$File = $Line.Name
$FullName = $Line.FullName
$file = "$FullPath\$FullName"
$DestPath = Split-Path $FullPath -NoQualifier
Copy-Item "$FullName" -Destination c:\test\$DestPath
}
Error message that i am getting is :
+ CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand
Copy-Item : Could not find a part of the path 'C:\test\clients\A90\Support\_index0901\'.
At line:9 char:9
+ Copy-Item "$FullName" -Destination c:\test\$DestPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand
You get the error because the directory structure of your target path probably does not exist
To solve that you can create a 'temporary' file with New-Item ... -Force which creates the missing directories if necessary and then overwrite that file with Copy-Item like so
$ToCopy = Import-Csv "c:\temp\log.csv"
foreach($Line in $ToCopy)
{
$FullPath = $Line.ParentFolder
$File = $Line.Name
$FullName = $Line.FullName
$file = "$FullPath\$FullName"
$DestPath = Split-Path $FullPath -NoQualifier
$DestFile = c:\test\$DestPath
New-Item -ItemType File -Force $DestFile
Copy-Item "$FullName" -Destination $DestFile -Force
}
You need to create the folders before attempting to copy files in them.
Here's a way to do it, simplified from what you have, but with an added line to take care of the folders' creation.
foreach($File in $ToCopy)
{
$DestPath = Join-Path -Path 'c:\test' -ChildPath ( Split-Path $File.ParentFolder -NoQualifier )
If ( -not ( Test-Path -Path $DestPath ) ) { New-Item -Path $DestPath -Force -ItemType Directory }
Copy-Item $File.FullName -Destination $DestPath -WhatIf
}
(Be careful, I change the iteration variable from $Line to $File)
You are trying to copy files into c:\test\ directory which does not exist. Create this directory before loop:
mkdir c:\test\
or, in case directory may exist
mkdir c:\test\ -Force

Compress-Archive command returns "Exception: Stream was too long."

I have a simple script here to archive logs that begin with the name "Archive" then delete those files leaving only the archive.
cd L:\
$Source = Get-ChildItem L:\ | Where{$_.Name -match "^Archive.*\.evtx$"} |Get-ChildItem -name
$CurrentDate = get-date -Format M.d.yyyy
$Destination = "$CurrentDate.zip"
Compress-Archive -Path $Source -destinationpath $Destination
rm L:\$Source
However, I receive the below error when the script runs:
Exception calling "Write" with "3" argument(s): "Stream was too long." At
C:\windows\system32\windowspowershell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1:809
char:29
+ ... $destStream.Write($buffer, 0, $numberOfBytesRead)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IOException
Any suggestions?
Compress-Archive relies upon the Microsoft .NET Framework API System.IO.Compression.ZipArchive to compress files, the maximum file size that you can compress by using Compress-Archive is currently 2 GB. This is a limitation of the underlying API.
Please see more at : here
i would recommend using 7z.exe portable. here is my example script
$TempFolderName = "I:\TempLogs2\"
$source = $TempFolderName+'\Archive'
$destination = $TempFolderName+'\Archive'
$azcopylogs = Get-ChildItem $source -Include *.log -Recurse
foreach ($s in $azcopylogs) {
$azcopylogPath = $s.FullName
$azcopylogName = $s.Name
C:\Tools\7Z\7z.exe a -t7z $azcopylogPath'.7z' -r $azcopylogPath
;if (Test-Path $azcopylogPath'.7z') { Remove-Item $azcopylogPath -force }
}