Michael Strauss
Michael Strauss

Reputation: 55

powershell script to rename all files in directory

Task:
Directory that will have various .csv files dumped into it. These could be like file1.csv, file2.csv, etc.
Problem:
Iterate through the files and rename one to a standardized 'newfilename.csv'. This file will then be processed by an external program and get renamed and moved out of the directory. I have a powershell script which does this up to a point:

ent## Set the file location where the log files are
$file = "C:\logs"   

$new = "newfilename.csv"
$chkFile = "C:\logs\newfilename.csv"
$fileExists = Test-Path $chkFile

## Loop through all the .csv files in the log folder
foreach ($file in gci $file -include *.csv -recurse){       
    if($fileExists -eq $True){
        Write-Host "that file exists!"
        Start-Sleep -s 60
    } else{
    Write-Host "file doesn't exist, renaming..."
    rename-item -path $file -newname ("$new")}
    Start-Sleep -s 10   
}

The problem is that, given 5 files in the directory, it will go through, rename the first file and then, going back through the file list, it returns 'false' on "-eq $True" for $fileExists. Is the file list just not refreshing when it starts back through (IE: is there some sort of an array being created at the beginning of the 'foreach')? I've never actually written a PowerShell script. Should I be using some other procedure to go through the files? Is there a "refresh" of the list I should be performing?

Upvotes: 0

Views: 1897

Answers (1)

chwarr
chwarr

Reputation: 7192

The test for whether $chkFile is being done once before the loop runs. If you want to evaluate that for each file (e.g., the other process has already done its work and moved "newfilename.csv" away during the sleep), move the TestPath call inside the foreach.

Yes, the gci $file -include *.csv -recurse is evaluated once before starting the foreach loop . If you want to refresh the list each time, I'd do something like the following, which actually calls the foreach loop multiple times.

while($true) {
    $csvFiles = gci $file -include *.csv -recurse

    if ($csvFiles.Length -eq 0) {
         break
    }

    foreach ($file in gci $file -include *.csv -recurse) {       
        if (Test-Path $chkFile) {
            Write-Host "that file exists!"
            Start-Sleep -s 60
        } else {
            Write-Host "file doesn't exist, renaming..."
            rename-item -path $file -newname ("$new")
            Start-Sleep -s 10
        }
    }
}

Upvotes: 1

Related Questions