Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One possible way to achieve this is as follows:

  1. Use the Get-ChildItem cmdlet to get a list of all the text files in a directory:

    $files = Get-ChildItem -Path "C:\TextFiles" -Filter *.txt
    
  2. Iterate through the list of files using a foreach loop and for each file, open it and read the first line of the text:

    foreach($file in $files) {
      $firstLine = Get-Content $file.FullName | Select-Object -First 1
    }
    
  3. Use regular expressions or string manipulation to extract the desired text from the first line of the file. For example, if the first line contains the title of the file, you could extract that text using a regular expression:

    $title = $firstLine -replace '\W+', ' '
    

    This would remove any non-alphanumeric characters (e.g. punctuation) and replace them with spaces.

  4. Use the Rename-Item cmdlet to rename the file using the extracted text:

    Rename-Item $file.FullName -NewName "$title.txt"
    

    This would rename the file to the extracted text plus the ".txt" extension, e.g. "My Awesome File.txt".

Putting it all together, the full script might look something like this:

$files = Get-ChildItem -Path "C:\TextFiles" -Filter *.txt

foreach($file in $files) {
   $firstLine = Get-Content $file.FullName | Select-Object -First 1
   $title = $firstLine -replace '\W+', ' '
   Rename-Item $file.FullName -NewName "$title.txt"
}