Home > Net >  Renaming all text files in a directory
Renaming all text files in a directory

Time:07-11

I altered some code for powershell:

Get-ChildItem -Filter *.txt  | ForEach-Object { # Loop over files of interest
  $newName = (Get-Content $_.FullName -Head 1)[-1] # Extract 1st line
  $_ | Rename-Item -NewName $newName     # Rename input file
}

It is supposed to take each text file in a directory, and rename it to the first line of the file.

Rename-Item : The path is not of a legal form.
At line:3 char:8
    $_ | Rename-Item -NewName $newName     # Rename input file
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : NotSpecified: (:) [Rename-Item], ArgumentException
      FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.RenameItemCommand

But it gives me that error.

CodePudding user response:

Use (Get-Content $_.FullName -First 1) instead of (Get-Content $_.FullName -Head 1)[-1]

-First has been introduced in PowerShell 3.0.

  • Related