Copy a file from current script directory? RRS feed

  • Question

  • I’m new to PowerShell so I’m likely doing this wrong but I cant seem to find an example for what I’m trying to do.

    The goal is to copy a file from the directory the script is running from, and paste it to a set location. The script is running from an external drive so the source drive letter is not absolute. I’ve managed to get it to see the directory its launched from, just haven’t quite figured out how to get it to copy from that point. This is what I have so far:

    # Determine script location for PowerShell
    $ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
    Write-Host "Current script directory is $ScriptDir"
    # Copy Prefrence file from current dir
    xcopy $PSScriptRoot\Prefrences /h "C:\Users\$user\appdata\local\PFH\"
    Any assistance is greatly appreciated.
    Monday, June 25, 2018 4:00 PM

All replies

  • XCOPY is not a PowerShell command.

    The code you posted does not make much sense. You get "$ScriptDir" and never use it.

    Use "Copy-Item".  To copy hidden files use the "-Force" parameter.


    Monday, June 25, 2018 4:28 PM
  • Sry, ignore the $ScriptDir - leftovers from another script :/

    I swapped Xcopy /h for Copy-item -Force as  suggested  Also had to change $user to $env:UserName to get it to go to the current user.

    # Determine script location for PowerShell
     Write-Host "Current script directory is $ScriptDir"
    # Copy Pref file from current dir
    Copy-item $PSScriptRoot\Preferences "C:\Users\$env:UserName\appdata\local\PFH" -Force

    It works! many thanks.

    • Proposed as answer by Loic Joalland Monday, November 18, 2019 10:44 AM
    Monday, June 25, 2018 5:47 PM