0

I have a script that I've been working on, which reads a specified directory, locates .CSV files, and executes some logic for each of the .CSV files and ultimately renames them .csv.archived .

The code was working fine last night, however this morning, when I execute the code it only loops through once. For example, last night, I had 5 .csv files in the directory, it would return the file names for all 5 files in a single action. Now, each time I execute my script, it grabs the first file, performs the actions intended, and then exits forcing me to manually initiate the script for each file.

I've gutted the irrelevant code for testing purposes, and would be happy if someone could tell me that I am doing something wrong, and that I am not crazy.

Here's the code:

$iterations = 1

#set the location where the .CSV files will be pulled from
$Filecsv = get-childitem "\\SERVERPATH\Audit Test\" -recurse | where {$_.extension -eq ".csv"} | % {
$filename = $_.Name
}

#for each file found in the directory
ForEach ($Item in $Filecsv) {

 #spit out the file name
 "File Name: " + $filename

 #count the times we've looped through
 "Iterations : " + $iterations


# get the date and time from the system
$datetime = get-date -f MMddyy-hhmmtt
# rename the file 
rename-item -path ("\\SERVERPATH\Audit Test\"+ $filename) -newname ($filename + $datetime + ".csv.archived")
$iterations ++

}

...and here is the Output:

This is the output

For the example I showed you, I had four .CSV files in the directory. I had to manually execute my script, and each time it would perform as expected, but only for the first item it encounters in the directory. It doesn't actually loop through, what am I missing here?

1 Answer 1

2

Right here (folded at the pipe for readability):

$Filecsv = get-childitem "\\SERVERPATH\Audit Test\" -recurse |
 where {$_.extension -eq ".csv"} |
 % {$filename = $_.Name}

You're looping through your files and for each one setting $filename to the name of that file instead of letting the filenames accumulate in $Filecsv

$Filecsv = get-childitem "\\SERVERPATH\Audit Test\" -recurse |
where {$_.extension -eq ".csv"} |
% {$_.Name}
Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Today I learned that I was doing it all wrong. Thanks @mjolinor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.