
Eu estava tentando ajudar um amigo que recuperou vários dados, mas os metadados foram perdidos. Como a maior parte são artigos ou receitas, ela acredita que o título ou a primeira linha do texto serão bons o suficiente para um nome de arquivo.
Eu queria tentar usar um script do PowerShell para ... acessar/ler os arquivos, pegar a primeira linha (se possível definir um comprimento de caracteres) e depois renomear. Tipo... leia os primeiros 10 caracteres e renomeie o arquivo assim.
Encontrei este script, que parece ser para arquivos .txt. É possível retrabalhá-lo para .doc e, em seguida, eliminar a parte sobre O e apenas lê-lo, seja qual for a primeira linha, e renomeá-lo com os primeiros 10 caracteres lidos?
Qualquer ajuda seria muito apreciada. (desculpas se estraguei a postagem do script)
$myFolderFullOfTextFiles = 'C:\recoveredDocs'
$linesToReadInEachTextFile = 5
$myTextFiles = Get-ChildItem -Path $myFolderFullOfTextFiles
foreach( $textFile in $myTextFiles )
{
$newName = ''
foreach( $line in $(Get-Content -Path $textFile.FullName -Head $linesToReadInEachTextFile) )
{
if( $line -like 'O*' )
{
$newName = $textFile.DirectoryName + '\' + $line.Substring(0,6) + '.txt'
}
}
try
{
Write-Host $newName
Rename-Item -Path $textFile.FullName -NewName $newName
}
catch
{
Write-Host "Failed to rename $textFile."
}
}
Eu também encontrei esse script. que é mais focado em .doc. Tudo que preciso é ... ler qualquer que seja a primeira linha do texto, renomeá-la (com algum limite razoável nos caracteres, como os primeiros 10 caracteres).
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Open("C:\Scripts\Test.doc")
strText = objDoc.Paragraphs(1).Range.Text
arrText = Split(strText, vbTab)
intIndex = Ubound(arrText)
strUserName = arrText(intIndex)
arrUserName = Split(strUserName, " ")
intLength = Len(arrUserName(1))
strName = Left(arrUserName(1), intlength - 1)
strUserName = strName & ", " & arrUserName(0)
strText = objDoc.Paragraphs(2).Range.Text
arrText = Split(strText, vbTab)
intIndex = Ubound(arrText)
strDate = arrText(intIndex)
strDate = Replace(strDate, "/", "")
intLength = Len(strDate)
strDate = Left(strDate, intlength - 1)
strFileName = "C:\Scripts\" & strUserName & " " & strDate & ".doc"
objWord.Quit
Wscript.Sleep 5000
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.MoveFile "C:\Scripts\Test.doc", strFileName
Responder1
Copie o código a seguir e crie como script do PowerShell nomeando o arquivo com extensão .ps1 (testado ok com o PowerShell 4 no Windows 7 - verifique sua versão do PowerShell com "get-host|Select-Object version" ou "$PSVersionTable.PSVersion" )
$word_app = New-Object -ComObject Word.Application <# New word application #>
$source = 'C:\recoveredDocs' <# create the source variable #>
$destination = 'C:\renamedDocs' <# create the destination variable #>
if (!(Test-Path -path $destination)) { <# check to see if destination folder exists #>
New-Item -path $destination\ -type directory -Force } <# create destination folder if it doesn't already exist #>
echo 'checking files to convert...'
<# filter for word .doc files only #>
Get-ChildItem -Path $source -Filter *.doc? | ForEach-Object {
if (!(Test-Path "$destination\$($_.BaseName).doc")) { <# check to see if file is already in destination folder (Note. "!" is a PS Alias for "-Not") #>
$document = $word_app.Documents.Open($_.FullName) <# open word document #>
$pattern = '[^a-zA-Z1234567890 ]' <# create regex pattern of allowed characters #>
$textstring = $document.range().text <# get the text string from the document #>
$titlestring = $textstring -replace $pattern, '' <# apply the regex pattern to eliminate the reserved characters #>
$title = $titlestring.substring(0, [System.Math]::Min(10, $titlestring.Length)) <# limit the string to 10 characters #>
$doc_strNewName = "$destination\$($title).doc" <# create the new name and path for the doc #>
echo "$($_.FullName) converted to $doc_strNewName"
$document.SaveAs([ref] $doc_strNewName, [ref] 0) <# save the document with new name and path #>
$document.Close() <# close documnet #>
}
}
echo "No More Files to Convert"
$word_app.Quit() <# close the word application #>