CopyTo() Coppying form one array to another.

Hi

I’m Trying to Copy content of one file to another file using the copy() Method.

File 1 this is the file I want copy :

$folder2 =@(“C:\Users\spate\Documents\SampleFile10.txt”)

To

$path2 = @(“C:\Users\spate\Documents\SampleFile17.txt”)

 

Doing this and getting error:

$folder2.CopyTo(“C:\Users\spate\Documents\SampleFile10.txt” + $path2)

Thanks

Sunny!

You cannot change the size of a standard array in PowerShell. You can instantiate a new array by using the + operator to do what you are trying to do with the copyto method.

$folder2 =@(“C:\Users\spate\Documents\SampleFile10.txt”)
$path2 = @(“C:\Users\spate\Documents\SampleFile17.txt”)

$folder2 + $path2
C:\Users\spate\Documents\SampleFile10.txt
C:\Users\spate\Documents\SampleFile17.txt

Having said that in your post you said, [quote quote=291502]Copy content of one file to another file[/quote]
None of this has to do with the content of a file only an array of strings containing a PATH to a file NOT it’s contents. To do that you will need to use some cmdlets let Get-Content and Add-Content

$folder2 =“C:\Users\spate\Documents\SampleFile10.txt”
$path2 = “C:\Users\spate\Documents\SampleFile17.txt”

Add-Content -Path $path2 -Value (Get-Content -Path $folder2)

See Get-Help Add-Content and Get-Help about_arrays

There are many easier ways you can copy the contents of a file to a another file in PS.

But if you are really into using Copyto(), you should know that this function copies the content of an existing file to a new file with same attributes and it does not allow overwriting, which means that you need to delete any existing files with the same name as the destination file to be used in the CopyTo().

 

Below code should work using CopyTo()

$file1path = "D:\powershell org\file1.txt"
$file1info = [System.io.FileInfo]($file1path);
$file2path = "D:\powershell org\file2.txt"
$file2info = [System.io.FileInfo]($file2path);
if(Test-Path $file2path)
{
Remove-Item $file2path -Force
}
$file1info.CopyTo($file2info)

 

 

Hi Mike

I’m knew to powershell scripting. The second script you have shown will definetly do the trick.

My whole point of doing the way I tried was to understand how i can encorperate the copy() method to do the same.

Basically understand

CopyTo Method void CopyTo(array array, int index), void CopyTo(array array, long index), void ICollection.CopyTo(array arr…

Thanks

Sunny

Hey James

I can follow your logic and understand the the flow/sructure of the script. This really helps.

But What you are doing in this step is confusing for me.

Are you initiating a array here?

$file1info = [System.io.FileInfo]($file1path);

Thanks

Sunny

 

 

Hi Sunny,

No, I am not initializing an error here. I am creating a FileInfo Object for your source/destination files. A FileInfo object provides properties and instance methods for the creation, copying, deletion, moving, and opening of files.

GOT IT TY