Rename files in Powershell based on destination folder

Asked

Viewed 628 times

1

I have the way A and fate B. This destination is repeated for several clients as the structure below shows:

A
-->app.exe
-->server.ini
-->js.png.

B-Cliente 01 
-->app_cliente01.exe
-->server.ini
-->js.png.

B-Cliente 02 
-->app_cliente02.exe
-->server.ini
-->js.png

B-Cliente 03 
-->app_cliente03.exe
-->server.ini
-->js.png.

I need to copy all the files from the directory A to the paths of B, but when making this copy I need to rename the files with part of the destination name.

Example: app.exe would be app_cliente01.exe when copied to the folder B-Cliente 01.

  • What is your question? There is an error when copying?

  • So I don’t know much about Powershell I wanted at least one idea for me to start researching the commands and how can I do this

  • Okay, if your goal is to better understand what is being done, I suggest rolling up your sleeves and practicing. The answer given by the Omni user will help you. But no free lunch, most materials are in English. See the links:<br> Windows Powershell Basics<br> about_Comparison_Operators<br> Learn How to Load and Use Powershell Snap-ins<br> [Create Custom Win

1 answer

1

You can do the following (the explanation is in the form of comments):

# Primeiro defina a pasta onde estao os ficheiros a copiar
$caminhoFonteFicheiros = Resolve-Path ".\A"

# Depois defina uma mascara para usar quando for necessario encontrar as pastas de destino
$mascaraDestino = "B-*"

# E defina o caminho onde se encontram as pastas
$caminhoFonteDestino = Get-Location

# Por cada pasta de destino encontrada
foreach($destino in $(Get-ChildItem -Path $caminhoFonteDestino -Filter $mascaraDestino -Directory)) {

    # Crie o nome que vai adicionado aos ficheiros copiados 
    $marcador = ($destino.Name -replace $mascaraDestino).Replace(" ", "").ToLowerInvariant();

    # Agora por cada ficheiro que exista no directorio fonte
    foreach($origem in $(Get-ChildItem -Path $caminhoFonteFicheiros -File)) {

        # Separe a extensao e o nome original
        $extensao = [System.IO.Path]::GetExtension($origem.FullName);
        $nomeAntigo = [System.IO.Path]::GetFileNameWithoutExtension(($origem.FullName))

        # E por fim junte-os de novo com o marcador do directorio actual
        $novoNome = "$nomeAntigo`_$marcador$extensao"

        # Crie o novo caminho do ficheiro juntando o caminho da pasta de destino e o novo nome
        $novoCaminho = Join-Path $destino.FullName $novoNome

        # E por fim copie os ficheiros
        Write-Host "A copiar o ficheiro '$($origem.FullName)' para '$novoCaminho'"
        Copy-Item -Path $origem.FullName -Destination $novoCaminho
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.