Powershell script to read and split filename from a folder

Viewed 125

I'm new to powershell. I want to read names of each file in a folder for eg. 900_CA_2022.pdf, remove the _ from the filename and create a new text file which has name 900CA2022900_CA_2022.txt

Basically, I want to remove the _ from the extension-less file name, append the latter as-is, and use a new extension, .txt

2 Answers

Update:

  • The stated requirements are unusual, but the next section provides a solution to address them.

  • The fact that you later accepted Joma's answer indicates that simply appending .txt to each input file name is what you actually needed; this is most easily accomplished as follows:

Get-ChildItem -Filter *.pdf | New-Item -Path { $_.FullName + '.txt' } -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.


Important: All solutions below create the new files in the current directory. If needed, construct the target file path with an explicit directory path, using Join-Path, e.g.:
Join-Path C:\target (($_.BaseName -replace '_') + $_.BaseName + '.txt')


To create new, empty files whose names should be derived from the input files, use New-Item:

Get-ChildItem -Filter *.pdf | 
  New-Item -Path { ($_.BaseName -replace '_') + $_.BaseName + '.txt' } -WhatIf

Note: If the target file exists, an error occurs. If you add -Force, the existing file is truncated instead - use with caution.

  • $_.BaseName is the input file's name without the extension.
  • -replace '_' removes all _ chars. from it.

To create new files whose names should be derived from the input files and fill them, use ForEach-Object:

Get-ChildItem -Filter *.pdf | 
  ForEach-Object { 
    # Construct the new file path.
    $newFilePath = ($_.BaseName -replace '_') + $_.BaseName + '.txt'
    # Create and fill the new file.
    # `>` acts like Out-File. To control the encoding, use 
    # something like `| Out-File -Encoding utf8 $newFilePath` instead.
    "content for $newFilePath" > $newFilePath
  }

Note that > / Out-File and Set-Content (for string data) all quietly replace the contents of an existing target file.

Easiest way is use the same name of source file + .txt for create the text files without doing much damage to the source filenames.

E.g. 900_CA_2022.pdf -----> 900_CA_2022.pdf.txt

My alternative solution

Initial files
initial files

Script Code

$files = Get-ChildItem "./*.pdf" -Recurse -Force
$files | ForEach-Object{
    New-Item -Path "$($_ | Split-Path)/$($_ | Split-Path -Leaf).txt" -Force
}

Result files
result files
result files gui

Related