AliAlghamdi
AliAlghamdi

Reputation: 45

Checking if a file is a PDF or RTF then changing the extension to RTF Powershell script

I'm working on a PowerShell script that should do the following: I have a folder of PDF files but there's at least half of them in RTF format not PDF but the extension is still PDF. So what I've done is a script that will check the first few characters and will decide if it's RTF

$files = Get-ChildItem -Filter *.pdf -Recurse | % { $_.FullName }
foreach ($i in $files) {
    echo $i
$firstLine = Get-Content $i -TotalCount 1
$firstLine = $firstLine.Substring(0,6)
   echo $firstLine
if($firstLine -eq "{\rtf1") {
   echo "I'm here"
   $fileName= $i
   $newExtension="rtf"
   [io.path]::ChangeExtension($fileName,$newExtension)
}

}    

Upvotes: 1

Views: 477

Answers (1)

Avshalom
Avshalom

Reputation: 8899

Basically your problem is with this line:

if($firstLine -eq "{\rtf1") {

You should add escape characters so powershell threat this as regular text like this:

if($firstLine -eq "\{\\rtf1") {

Anyway here's an easier method IMO...

$files = Get-ChildItem -Filter *.pdf -Recurse
foreach ($file in $files)
{
    if (Get-Content $file.fullname | Select-String '\{\\rtf1' -Quiet) 
    {

    $NewFileEXT = $file.BaseName + '.rtf'
    Rename-Item $file.FullName $NewFileEXT

    }
}

To get more info about the Escape Characters, type:

Get-Help about_Escape_Characters

Upvotes: 1

Related Questions