Home > Blockchain >  Using Variables with Directories & Filtering
Using Variables with Directories & Filtering

Time:07-16

I'm new to PowerShell, and trying to do something pretty simple (I think). I'm trying to filter down the results of a folder, where I only look at files that start with e02. I tried creating a variable for my folder path, and a variable for the filtered down version. When I get-ChildItem for that filtered down version, it brings back all results. I'm trying to run a loop where I'd rename these files.

File names will be something like e021234, e021235, e021236, I get new files every month with a weird extension I convert to txt. They're always the same couple names, and each file has its own name I'd rename it to. Like e021234 might be Program Alpha.

set-location "C:\MYPATH\SAMPLE\"
$dir = "C:\MYPATH\SAMPLE\"
$dirFiltered= get-childItem $dir | where-Object { $_.baseName -like "e02*" } 
get-childItem $dirFiltered |
Foreach-Object {
$name = if ($_.BaseName -eq "e024") {"Four"}
elseif ($_.BaseName -eq "e023") {"Three"}
 get-childitem $dirFiltered | rename-item -newname { $name   ".txt"}   
}

CodePudding user response:

There are a few things I can see that could use some adjustment.

My first thought on this is to reduce the number of places a script has to be edited when changes are needed. I suggest assigning the working directory variable first.

Next, reduce the number of times information is pulled. The Get-ChildItem cmdlet offers an integrated -Filter parameter which is usually more efficient than gathering all the results and filtering afterward. Since we can grab the filtered list right off the bat, the results can be piped directly to the ForEach block without going through the variable assignment and secondary filtering.

Then, make sure to initialize $name inside the loop so it doesn't accidentally cause issues. This is because $name remains set to the last value it matched in the if/elseif statements after the script runs.

Next, make use of the fact that $name is null so that files that don't match your criteria won't be renamed to ".txt".

Finally, perform the rename operation using the $_ automatic variable representing the current object instead of pulling the information with Get-ChildItem again. The curly braces have also been replaced with parenthesis because of the change in the Rename-Item syntax.

Updated script:

$dir = "C:\MYPATH\SAMPLE\"
Set-Location $dir
Get-ChildItem $dir -Filter "e02*" |
Foreach-Object {
     $name = $null     #initialize name to prevent interference from previous runs
     $name = if ($_.BaseName -eq "e024") {"Four"}
         elseif ($_.BaseName -eq "e023") {"Three"}
     if ($name -ne $null) {
         Rename-Item $_ -NewName ($name   ".txt")
         }
}
  • Related