简体   繁体   中英

powershell: Copy files to subdirectories based on name

I want to implement a particular copy.
Example: I have a file with name adidas[other part of name].jpg.
I want to read the first two file's character and insert in subfolder as images/A/D.
Others examples:
If I have Reebok the files goes to images/R/E
If I have Brooks the files goes to images/B/R
There is another problem. If in the first two character are present any symbol (.&$%- and all others) I have to skip them.

Dot is illigal charecter for dir name

param (
    $sourceFolder = "D:\tmp\001",
    $destFolder = "D:\tmp\002"
)
foreach($firstChar in "&$%".ToCharArray()){
    foreach($secondChar in "&$%".ToCharArray()){
        "some text" | Out-File ("$sourceFolder\{0}{1}sufix.txt" -f $firstChar, $secondChar)
    }    
}

Get-ChildItem $sourceFolder | %{
    $firstChar = $_.Name[0]
    $secondChar = $_.Name[1]
    $dir = (Join-Path (Join-Path $destFolder -ChildPath $_.Name[0]) -ChildPath $_.Name[1]) 
    New-Item $dir -ItemType Directory -ErrorAction SilentlyContinue
    Copy-Item $_ $dir
}

You can use a Where-Object clause to filter on files that have a name that always starts with (at least) two characters in the range of AZ and skip all other files.

Something like this:

$sourcePath  = 'D:\Test'
$destination = 'D:\Test\images'
Get-ChildItem -Path $sourcePath -File | Where-Object { $_.Name -match '^[a-z0-9]{2}' } | ForEach-Object {
    $targetPath = Join-Path -Path $destination -ChildPath (('{0}\{1}' -f $_.Name[0], $_.Name[1]).ToUpper())
    if (!(Test-Path -Path $targetPath -PathType Container)) {
        $null = New-Item -Path $targetPath -ItemType Directory
    }
    $_ | Copy-Item -Destination $targetPath
    Add-Content -Path 'D:\copylog.log' -Value "File '$_.Fullname' copied to '$targetPath'"
}

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