简体   繁体   中英

How to copy **only** the folder content of a directory in powershell script with robocopy

I am trying to copy only the folders that are within a directory, the script provided in the answer to this question copies all content within the directory: How can i only copy folders with robocopy in powershell?

The code from this answer is provided below:

Get-ChildItem 'C:\temp\test' |
ForEach-Object {
    $newname = ($_.BaseName -Replace '[^\x20-\x5D,\x60-\x7E]+', '-')
    if (($_.GetType()).Name -eq "DirectoryInfo"){
        write-host "folder"
    }
    write-host $_.BaseName
    write-host $newname
    robocopy.exe "C:\temp\test\$($_.BaseName)" "C:\temp\test\copy\$newname"
}

You are looking to use the parameters: /E = copy directories even if empty /XF . = Exclude, in this case all files, ie anything with "." in the filename, eg. all files

Example of use:

    $Source = "C:\temp\test"
    $Destination = "C:\temp\test2"
    $robocopyOptions = "/E /XF *.*"
    # filelist is required but we will ignore it anyway with parameters we are passing
    $fileList = ''
    robocopy.exe $Source $Destination $fileList $robocopyOptions.split(' ')

As an alternative to robocopy you might also use the xcopy command , which features an option /T to create the destination directory tree without copying any files. Here is an excerpt of the help text when you enter xcopy /? into a command prompt window:

  /T Creates directory structure, but does not copy files. Does not include empty directories or subdirectories. /T /E includes empty directories and subdirectories. 

So you could use the following command line:

xcopy.exe /T /E /I "C:\temp\test\folder" "C:\temp\test\copy"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM