Should Copy-Item create the destination directory structure?

后端 未结 6 1580
广开言路
广开言路 2020-12-08 12:46

I\'m trying to copy a file to a new location, maintaining directory structure.

$source = \"c:\\some\\path\\to\\a\\file.txt\"
destination = \"c:\\a\\more\\dif         


        
6条回答
  •  感动是毒
    2020-12-08 13:33

    The -recurse option only creates a destination folder structure if the source is a directory. When the source is a file, Copy-Item expects the destination to be a file or directory that already exists. Here are a couple ways you can work around that.

    Option 1: Copy directories instead of files

    $source = "c:\some\path\to\a\dir"; $destination = "c:\a\different\dir"
    # No -force is required here, -recurse alone will do
    Copy-Item $source $destination -Recurse
    

    Option 2: 'Touch' the file first and then overwrite it

    $source = "c:\some\path\to\a\file.txt"; $destination = "c:\a\different\file.txt"
    # Create the folder structure and empty destination file, similar to
    # the Unix 'touch' command
    New-Item -ItemType File -Path $destination -Force
    Copy-Item $source $destination -Force
    

提交回复
热议问题