Search code examples
powershellcopy-item

Powershell copy-item issue


I have a very weird issue and been pulling my hair out.

I have two PowerShell scripts. Lets say Main and child. Child script is in a folder within mainfolder:

Mainfolder\Main_script    
MainFolder\ChildFolder\child_script.ps1 

The Main script runs from where the location can change. So I get the location of the script in the beginning

$ScriptDir = (Get-Location).path

I do some tasks including copying which works

copy-item -path $src -Destination $dst -force

Everything till this point is great. Then I call my child script

& "$scriptdir\childfolder\Child_script.ps1"

The scripts runs, and I see other tasks being executed. But I have some files in the child folder that I need to copy over. But the copy doesn't work with the child_Script. I even put

"Copying $src to $destination" | Out-file -append $logfile

and I see Copying C:\test\copythis.txt to C:\temp

The code in the childscript is this

$Scriptdir = (Get-Location).path
$src =  "$Scriptdir\copythis.txt"
$dst = "C:\temp"
copy-item -path $src -Destination $dst -force

If I try to copy the same files in the main script, everything works.Why does the copy-item doesn't work in the childscript? I should also mention that everything is running with the system account. So No permission issues.

Any help would be appreciated. Cheers,


Solution

  • Reading the documentation:

    Get-Location
    Gets information about the current working location or a location stack.

    ....

    The Get-Location cmdlet gets an object that represents the current directory, much like the pwd (print working directory) command.

    If you want to use the directory in which the script is located use the answer from this StackOverflow question.