Moritz
Moritz

Reputation: 389

For loop while rename and move files withing a folder

Good morning,

started last week using powershell for some small scripts and now I'm stucked at creating a for loop for rename and move files. I've got these 2 commands

get-childitem "$Quellordner" | Rename-Item -NewName {$_.Name.Replace("[Index]","-")}
get-childitem "$Quellordner" | Move-Item -Force -Destination $Zielordner -Verbose *>&1 | Set-Content $Logfileordner$Logfilename

and they are working fine but it's a bit odd not using a for loop for this. Unfortunately I can't get it to work :/

Any help will be appreciated!

(PS: Is there an other way to create a descending log file (newest to oldest) than copy the actual content and paste it belowe the new line?)

Upvotes: 3

Views: 355

Answers (2)

boxdog
boxdog

Reputation: 8442

You can combine the rename and move by simply extending the pipeline:

Get-ChildItem -Path *.txt |
    Rename-Item -NewName {$_.Name -replace "[Index]","-"} -PassThru |
        Move-Item -Destination $Zielordner -Force

Writing to the start of a file is not directly supported, likely because it is an expensive operation (you need to move everything along somehow to make room), and seems like it will be more prone to corruption/data loss. One thing to look at is writing to the log as normal, but displaying it in reverse order. For example, Get-Content can read the individual lines of a text file into an array, which could easily be output from the end to the start.

Upvotes: 2

TobyU
TobyU

Reputation: 3918

You're actually already using a foreach loop. ForEach-Object to be precise.

Your line of code:

get-childitem "$Quellordner" | Rename-Item -NewName {$_.Name.Replace("[Index]","-")}

does exactly the same as the following code does:

$files = get-childitem "$Quellordner"
foreach($_ in $files){
    Rename-Item -NewName {$_.Name.Replace("[Index]","-")}
}

About your PS: there is no way, I know of, to add a new line at the top of a text file without reading the file, adding the line you want to add at the top and write it back.

Upvotes: 0

Related Questions