Powershell根据文件名的一部分移动文件

use*_*391 5 powershell

我在名为D:\ queries \的目录中有成千上万个类似以下文件的文件

#TIM_DV_ORDERINQUERY.SQL
#TIM_QA_ORDERINQUERY.SQL
#TIM_P1_ORDERINQUERY.SQL
#JACK_DV_SALESQUERY.SQL
#JACK_P1_PRODUCTQUERY.SQL
#ERIK_P1_EMPLOYEE-NY.SQL
#ERIK_P1_EMPLOYEE-TX.SQL
Run Code Online (Sandbox Code Playgroud)

::

I am need a script to move them to folders 
G:\queries\#TIM\DV\ORDERINQUERY.SQL
G:\queries\#TIM\QA\ORDERINQUERY.SQL
G:\queries\#TIM\P1\ORDERINQUERY.SQL
G:\queries\#JACK\DV\SALESQUERY.SQL
G:\queries\#JACK\P1\PRODUCTQUERY.SQL
G:\queries\#ERIK\P1\EMPLOYEE-NY.SQL
G:\queries\#ERIK\P1\EMPLOYEE-TX.SQL
Run Code Online (Sandbox Code Playgroud)

换句话说,第一个_之前的字符是G:\ queries中的子目录,然后第一个_和第二个_之间的字符是其中的子目录,然后测试名称是文件名。

我在网上搜索了很多内容,但无法弄清楚。我不熟悉Powershell或任何类型的脚本。任何帮助表示赞赏。

Dav*_*tin 5

这利用FileInfo类来获取与目录有关的信息。

$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 
}
Run Code Online (Sandbox Code Playgroud)


Tre*_*van 5

您可能需要为此使用正则表达式。这将有助于确保仅移动与指定模式匹配的文件,并且您没有任何“意外”。

# 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 '(?<folder>.*?)(?:_)(?<subfolder>\w{2})(?:_)(?<filename>.*)';
    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
}
Run Code Online (Sandbox Code Playgroud)