IGGt
IGGt

Reputation: 2759

powershell v2 - find a file in a directory and rename it

I'm trying to write a simple script that allows me to check a directory, and find any matching filenames. Once I find a match, I simply want to append the curent datetime to the front of the filename.

This sounds easy, but I can't quite figure it out

So far I have got

$directory = "c:\directoryName\"
$filename = "filename.log"
$d = Get-Date -format "yyyyMMddHHmm" 

get-childitem -Path $cfg_logDirectory | foreach-object 
{ 
    if ($_.name -eq $cfg_fileName)
        {
            $fname = $_.name
            Rename-Item -NewName $d."_".$fname
        }
}

But When I run this (in ISE at least), I get a window comes up asking me for

"Cmdlet ForEach-Object at Command pipeline position 2 - Supply values for the following parameters: Process[0]"

Is this the way to go, or is there a better way to do this?

Upvotes: 1

Views: 646

Answers (1)

Ryan Bemrose
Ryan Bemrose

Reputation: 9266

Move your opening curly brace to the end of the previous line.

get-childitem -Path $cfg_logDirectory | foreach-object { 

You're getting that error because Powershell is assuming the end of the line is the end of the statement, and then trying to prompt you for the missing parameter to foreach-object - in this case, its script block*. Moving the opening brace to the same line tells Powershell that there are more statements coming.

*Why 'Process'? The foreach-object cmdlet can take three script blocks as parameters: Begin, Process, and End. Begin and End are optional, but Process is required. If you supply a script block without a name, it is assumed to be Process.

Upvotes: 4

Related Questions