firekid2018
firekid2018

Reputation: 145

How to add filename suffix inside text using powershell?

I am not sure if it's possible. i want to add filename at the end of text file each line.

assume i have a text file Sam_NEW.txt Tom_New.txt Robin_New.txt etc. inside the text follow line available

test1.rar test2.rar test3.rar

i want to have output

copy "C:\test1.rar" "F:\Sam_NEW\" copy "C:\test2.rar" "F:\Sam_NEW\" copy "C:\test3.rar" "F:\Sam_NEW\"

copy "C:\test1.rar" "F:\Tom_New\" copy "C:\test2.rar" "F:\Tom_New\" copy "C:\test3.rar" "F:\Tom_New\"

copy "C:\test1.rar" "F:\Robin_New\" copy "C:\test2.rar" "F:\Robin_New\" copy "C:\test3.rar" "F:\Robin_New\"

and save the text files. english is not my first language here is the image what i am trying to do

https://i.sstatic.net/42IpE.png

here is replace code so far i have.

(Get-Content C:\temp\*.txt) -creplace '^', '"C:\' | Set-Content C:\temp\*.txt

(Get-Content C:\temp\*.txt) -creplace '$', '"F:\HOW TO add here filename \"' | Set-Content C:\temp\*.txt

i am stuck in last part. how to add file name for the destination folder?

Upvotes: 0

Views: 595

Answers (2)

David Mayo
David Mayo

Reputation: 53

I don't know that this code will do exactly what you're looking for, but I've tried to write it in a clear way with lots of explanation. Hopefully the techniques and cmdlets in here are helpful to you.

$RarFileNames   = Get-ChildItem -Path C:\Temp -Filter *.rar | Select-Object -ExpandProperty Name

$NewFolderPaths = Get-ChildItem -Path F:\ -Directory | Select-Object -ExpandProperty FullName

foreach( $NewFolderPath in $NewFolderPaths )
{
    foreach( $RarFile in $RarFileNames )
    {
        # EXAMPLE: C:\Temp\test1.rar
        $RarFilePath = Join-Path -Path $RarFolderPath -ChildPath $RarFile

        # EXAMPLE: Sam_New.txt
        $NewFileName = (Split-Path $NewFolderPath -Leaf) + '.txt'

        # EXAMPLE: F:\Sam_NEW\Sam_NEW.txt
        $NewFilePath = Join-Path -Path $NewFolderPath -ChildPath ($NewFileName)

        # This is the string that will be saved in the .txt file
        # EXAMPLE: copy "C:\Temp\test1.rar" "C:\Sam_NEW\"
        $StringToOutput = 'copy "' + $RarFilePath + '" "' + $NewFolderPath + '"'

        # Append that string to the file:
        Add-Content -Value $StringToOutput -Path $NewFilePath
    }
}

Upvotes: 0

hcm
hcm

Reputation: 1010

You'll want something like this:

$item = get-item -path "C:\temp\test.txt"
$lines = get-content -path $item.fullname
$newfileoutput = @()
foreach ($line in $lines){
    $newfileoutput += 'copy "C:\' + $line + '" "F:\' + $item.basename + '\"'
}
$newfileoutput | set-content $item.fullname

But I can only encourage you to deepen your knowledge of simple cmdlets like get-item, get-content and the like. I don't have the impression that you understand the code you're writing. Sometimes, less code (and more pipelining) is making things more complicated. Try and write code that you understand.

Upvotes: 1

Related Questions