PowerTip: Use PowerShell to Copy Files

PowerTip: Use PowerShell to Copy Files

  • Comments 8
  • Likes

Summary: Learn how to use Windows PowerShell to copy files from one location to another.

Hey, Scripting Guy! Question How can I use Windows PowerShell to copy a file to a new location?

Hey, Scripting Guy! Answer Use the Copy-Item cmdlet and specify the path to the original file and a destination for the copy. In this example, file 20110314.log in the C:\fso folder is copied to folder C:\fsox with the new name mylog.log.

Note   The destination folder C:\fsox must exist.

Copy-Item -Path C:\fso\20110314.log -Destination c:\fsox\mylog.log

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • How can we check if the same file is available or not if not then only copy?

  • Try using:

    if (-not(Test-path $dest)) {Copy-item c:\file $dest}

  • For large numbers of files, I just call robocopy from Powershell.  I set up a simple cmdlet that takes common robocopy parameters and options as cmdlet parameters, yet allows for the use of all the myriad of robocopy parameters when needed.

  • How would this script be different if the source path was a usb stick, ufd, external usb driver, cd drive, etc that might not always have the same drive letter when plugged into different computers?

  • @southerner - nothing would change.  The source folder and the destination folder are on  the same drive.

    This is a common misunderstanding for desktop users.  They seem to think things have to change when they dont'.

    The 'C' drive does not change when you run a script from a different location.

  • @southerner - if you are trying to guess at where a file is stored then you can't.

    That is not the purpose of the post.  It is a simple post to show how to use the copy command.

    If the USB is E then you would do this:

    Copy-Item -Path E:\fso\20110314.log -Destination c:\fsox\mylog.log

    In the end you have to tell Windows where things are.  It is not a mind reader.

    You can, however, create an event that can figure out where the USB drive is when you plug it in but that is an advance topic.

  • Unfortunately Powershell 3.0 doesn't appear to be capable of copying files if you need to use Net USE to establish an alternate set of credentials. Powershell seems hopeless stuck in a DC world of the past.
    If this was Ubuntu I would be done!

  • @mash - that is just silly PowerShell New-PsDrive works just fine with credentials.
    http://technet.microsoft.com/en-us/library/hh849829.aspx