Copy Single File to Destination Folder if Exist else Copy to Another Folder

84 Views Asked by At

I am trying to copy a file from one location to another. There are two possible source destinations on the computer I would like the script to check if the folder exists (i.e. -eq 'True') if doesn't exist then move the file to the older folder. I know on the computer that one or the other folder exists. For example, I want to copy an INI file (file.ini) located in C:\File\ to either C:\Temp\F1 or C:\Temp\F2 (NOTE this is not the actual file or folder just using them as an example) replacing the existing file that is already in that folder. In my example, I am copying to a blank folder as I assume the file will just be overwritten at the destination.

I know I can achieve this as simply as:

If (Test-Path “C:\Temp\F1”) 
    {Copy-Item “C:\File\file.ini” “C:\Temp\F1” –Force
}
ElseIf (Test-Path “C:\Temp\F2”) 
        {Copy-Item “C:\File\file.ini” “C:\Temp\F2” –Force
}

As soon as I start to include some variables to make this look nicer I can no longer get the script to work. The following are my variables (NOTE they may not all be needed by I used them all for my testing)

$Source = “C:\File\file.ini”
$F1 = “C:\Temp\F1”
$F2 = “C:\Temp\F2”
$test1 = Test-Path $F1
$test2 = Test-Path $F2

I feel like I don't need to bother testing the second location as I know if the first destination doesn't exist the second will for sure. I tried the following script:

If ($test1) {Copy-Item $Source $F1} Else {Copy-Item $Source $F2}

This worked to copy the file into F1, but when I renamed my F1 folder to F2 to test if it still works, all it did was create a new file in C:\Temp Called F1

enter image description here

When I check my variables $Test1 = True but there is no F1 folder created I am using F2 per the above image. However, if I try Test-Path $F1 it comes back False. Not sure what I am doing wrong.

enter image description here

I changed my double quotes to single quotes and added -pathtype info to my variables

$Source = 'C:\File\file.ini'
$F1 = 'C:\Temp\F1'
$F2 = 'C:\Temp\F2'
$test1 = Test-Path $F1 -PathType Container
$test2 = Test-Path $F2 -PathType Container

If($test1 -eq $true) {Copy-Item $Source $F1} Else {Copy-Item $Source $F2}

I tested different scenarios for my variables to see what the outcome was.

$F1
Test-Path $F1
Test-Path C:\Temp\F1 -PathType Container
$test1 -eq $True 

$F2
Test-Path $F2
Test-Path C:\Temp\F2 -PathType Container
$test2 -eq $True

With just F1 folder the results were all correct

results-f1-only

With just F2 folder the results were wrong. It should have been all False for the top and all True for the bottom

results-f2-only

And with F1 and F2 folders created the results were also wrong when they should be true for all the results

F1&f2

So what I am finding from this is I cannot use

$test1 -eq $true
0

There are 0 best solutions below