Powershell 2 copy-item which creates a folder if doesn't exist

前端 未结 9 2455
余生分开走
余生分开走 2020-12-05 12:55
$from = \"\\\\something\\1 XLS\\2010_04_22\\*\"
$to =  \"c:\\out\\1 XLS\\2010_04_22\\\"
copy-item $from $to -Recurse 

This works if c:\\out\\

9条回答
  •  一整个雨季
    2020-12-05 13:01

    Here's an example that worked for me. I had a list of about 500 specific files in a text file, contained in about 100 different folders, that I was supposed to copy over to a backup location in case those files were needed later. The text file contained full path and file name, one per line. In my case, I wanted to strip off the Drive letter and first sub-folder name from each file name. I wanted to copy all these files to a similar folder structure under another root destination folder I specified. I hope other users find this helpful.

    # Copy list of files (full path + file name) in a txt file to a new destination, creating folder structure for each file before copy
    $rootDestFolder = "F:\DestinationFolderName"
    $sourceFiles = Get-Content C:\temp\filelist.txt
    foreach($sourceFile in $sourceFiles){
        $filesplit = $sourceFile.split("\")
        $splitcount = $filesplit.count
        # This example strips the drive letter & first folder ( ex: E:\Subfolder\ ) but appends the rest of the path to the rootDestFolder
        $destFile = $rootDestFolder + "\" + $($($sourceFile.split("\")[2..$splitcount]) -join "\")
        # Output List of source and dest 
        Write-Host ""
        Write-Host "===$sourceFile===" -ForegroundColor Green
        Write-Host "+++$destFile+++"
        # Create path and file, if they do not already exist
        $destPath = Split-Path $destFile
        If(!(Test-Path $destPath)) { New-Item $destPath -Type Directory }
        If(!(Test-Path $destFile)) { Copy-Item $sourceFile $destFile }
    }
    

提交回复
热议问题