powershell to move files based on part of file name

后端 未结 3 1042
夕颜
夕颜 2020-12-17 03:54

I have thousands of files like the following in a directory called D:\\queries\\

#TIM_DV_ORDERINQUERY.SQL
#TIM_QA_ORDERINQUERY.SQL
#TIM_P1_ORDERINQUERY.SQL
         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-17 04:09

    This makes use of the FileInfo class, to get information pertaining to the directory.

    $SourceFolder = "G:\queries\"
    $targetFolder = "G:\queries\"
    
    # Find all files matching *.sql in the folder specified
    Get-ChildItem -Path $SourceFolder -Filter *.sql | ForEach-Object {
    
        # Combine the source filename and target directory
        # The source filename has all instances of _ replaced with \
        # Cast the resulting string to a FileInfo object to take advantage of extra methods
        [System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace("_","\"))
    
        # Create the directory if it doesn't already exits
        if (!(Test-Path) $destination.Directory.FullName)
        { 
            New-item -Path $destination.Directory.FullName -ItemType Directory 
        }
    
        # Copy the source to the target directory
        copy-item -Path $_.FullName -Destination $Destination.FullName 
    }
    

提交回复
热议问题