2

I'm doing a few small school assignments, but our teacher is doing a pretty bad job in explaining stuff, so I've basically just been googling watching videos etc.

But I have to make a script that copies a file from one path to another, and it has to give an error if the file doesn't exist. I've written this piece of code:

$testpath = Test-Path $destinationfolder
$startfolder = "C:\Desktop\Destination1\test.txt\"
$destinationfolder = "C:\Desktop\Destination2\"

If ($testpath -eq $true) {Copy-Item $startfolder -Destination $destinationfolder}
Else {Write-Host "Error file does not exist!"}

My problem is that when it successfully copies the file, it still prints out the error. Its almost like it completely ignores the if and else statements. Can someone please, explain to me what i'm doing wrong, so i can correct it and hopefully learn something today? :)

1 Answer 1

2

I couldn't replicate the idea when the script copies the file AND executes else code block. But:

$testpath = Test-Path $destinationfolder 
$startfolder = "C:\Desktop\Destination1\test.txt\"
$destinationfolder = "C:\Desktop\Destination2\"

You are checking path (line 1) BEFORE the path is defined (line 3). That's why (when executed in new shell session) it will always be false. There is no need to put "\" character at the end of path.

You can write the same thing like this:

#Setting variables
$destinationFolder = "C:\Desktop\Destination2"
$startfolder = "C:\Desktop\Destination1\test.txt"

#Checking if destination folder exists
if (Test-Path $destinationFolder) {
    Copy-Item $startfolder -Destination $destinationFolder 
}
else {
    Write-Host "Directory $destinationFolder does not exist!"
}

Or if you want script to be idempotent (behave exactly the same way every time) it can look like this:

$destinationFolder = "C:\Desktop\Destination2"
$file = "C:\Desktop\Destination1\test.txt"

If (!(Test-Path $destinationFolder)) {
    #Check if destinationFolder  is NOT present and if it's not - create it
    Write-Host "Directory $destinationFolder does not exist!"
    New-Item $destinationFolder -ItemType Directory
}

#Will always copy, because destination folder is present
Copy-Item $file -Destination $destinationFolder
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.