powershell to move files based on part of file name

后端 未结 3 1041
夕颜
夕颜 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:16

    You'll probably want to use a regular expression for this. That will help to ensure that only files that match the specified pattern get moved, and you don't have any "accidents."

    # 1. Get a list of files in the d:\queries folder
    $FileList = Get-ChildItem -Path d:\queries;
    
    # 2. Parse file names, create folder structure, and move files
    foreach ($File in $FileList) {
        $File.Name -match '(?.*?)(?:_)(?\w{2})(?:_)(?.*)';
        if ($matches) {
            $Destination = 'd:\queries\{0}\{1}\{2}' -f $matches.folder, $matches.subfolder, $matches.filename;
            mkdir -Path (Split-Path -Path $Destination -Parent) -ErrorAction SilentlyContinue;
            Move-Item -Path $File.FullName -Destination $Destination -WhatIf;
        }
        $matches = $null
    }
    

提交回复
热议问题