Merhaba, Danışmanlık firmam var ve ilaç, kozmetik, takviye edici gıda gibi ürünlerin izinlerini alıyorum. Çok fazla dokümanlarla uğraşıyorum ve tek başıma olduğum için asistan gibi yapay zeka eğitimi alarak kullanmaya çalışıyorum. Ama şuanda ihtiyacım olan bir klasör içerisinde klasörlerin olduğunu düşünün ve her birinde wordler var ve ilaç ismi ve etkin maddesin yazdığım üst bilgiye yazdığım bir format var. Orada ilaç ismi ve etkin maddeyi değiştirip tüm klasörlerin içerisindeki wordlerdeki üst bilgiyi aynı anda değiştirmesini kodlayabilir miyiz?
Teşekkürler
Sevgilerimle
Word üst bilgisini ilaç ismine göre değiştirmek
- TRWE_2012
- Zettabyte1

- Mesajlar: 15612
- Kayıt: 25 Eyl 2013, 13:38
- cinsiyet: Erkek
- Teşekkür etti: 2710 kez
- Teşekkür edildi: 5626 kez
Re: Word üst bilgisini ilaç ismine göre değiştirmek
Klasör içi tüm .docx dosyalarının üst bilgisindeki (header) ilaç adı ve etkin maddeyi toplu değiştiren bir PS1 betiğiEmail Bot yazdı: 11 Eyl 2024, 12:40 Merhaba, Danışmanlık firmam var ve ilaç, kozmetik, takviye edici gıda gibi ürünlerin izinlerini alıyorum. Çok fazla dokümanlarla uğraşıyorum ve tek başıma olduğum için asistan gibi yapay zeka eğitimi alarak kullanmaya çalışıyorum. Ama şuanda ihtiyacım olan bir klasör içerisinde klasörlerin olduğunu düşünün ve her birinde wordler var ve ilaç ismi ve etkin maddesin yazdığım üst bilgiye yazdığım bir format var. Orada ilaç ismi ve etkin maddeyi değiştirip tüm klasörlerin içerisindeki wordlerdeki üst bilgiyi aynı anda değiştirmesini kodlayabilir miyiz?
Teşekkürler
Sevgilerimle
Kod: Tümünü seç
# ================================================================
# Word Header Batch Replacer - Drug Name & Active Ingredient
# Replaces specified text in headers of all .docx files found
# recursively inside a root folder.
#
# Requirements : Microsoft Word must be installed (COM automation).
# Compatibility: PowerShell 5.1 and PowerShell 7.x
# ================================================================
Set-StrictMode -Version Latest
$ErrorActionPreference = "Continue"
# ---- Log helpers -----------------------------------------------
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$LogFile = Join-Path $ScriptDir "header_replace_$Timestamp.log"
function Write-Log {
param(
[string]$Message,
[string]$Level = "INFO",
[System.ConsoleColor]$Color = [System.ConsoleColor]::Gray
)
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$line = "[$ts][$Level] $Message"
Write-Host $line -ForegroundColor $Color
Add-Content -Path $LogFile -Value $line -Encoding UTF8
}
# ---- Replace text inside all header sections of a document -----
function Invoke-HeaderReplace {
param(
[object]$Document,
[string]$FindText,
[string]$ReplaceText
)
# wdHeaderFooterPrimary = 1
# wdHeaderFooterFirstPage = 2
# wdHeaderFooterEvenPages = 3
$headerTypes = @(1, 2, 3)
$matchCount = 0
$wdReplaceAll = 2
$wdFindStop = 1
foreach ($section in $Document.Sections) {
foreach ($hType in $headerTypes) {
try {
$header = $section.Headers.Item($hType)
if (-not $header.Exists) { continue }
$find = $header.Range.Find
$find.ClearFormatting()
$find.Replacement.ClearFormatting()
# Execute(FindText, MatchCase, MatchWholeWord, MatchWildcards,
# MatchSoundsLike, MatchAllWordForms, Forward,
# Wrap, Format, ReplaceWith, Replace)
$result = $find.Execute(
$FindText, $false, $false, $false, $false,
$false, $true, $wdFindStop, $false,
$ReplaceText, $wdReplaceAll
)
if ($result) { $matchCount++ }
}
catch {
# Header type may not exist for this section — safe to skip
}
}
}
return $matchCount
}
# ---- Banner ----------------------------------------------------
Write-Host ""
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " Word Header Batch Replacer - Drug Name / Active Ingredient" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host ""
# ---- Input: root folder ----------------------------------------
$RootFolder = Read-Host "Root folder path (contains subfolders with .docx files)"
$RootFolder = $RootFolder.Trim().Trim('"')
if (-not (Test-Path -LiteralPath $RootFolder -PathType Container)) {
Write-Host "[ERROR] Folder not found: $RootFolder" -ForegroundColor Red
Read-Host "`nPress ENTER to exit."
exit 1
}
# ---- Input: find / replace pairs --------------------------------
Write-Host ""
Write-Host "--- Drug Name ---" -ForegroundColor Yellow
$OldDrugName = Read-Host " Current drug name (find)"
$NewDrugName = Read-Host " New drug name (replace with)"
Write-Host ""
Write-Host "--- Active Ingredient ---" -ForegroundColor Yellow
$OldIngredient = Read-Host " Current active ingredient (find)"
$NewIngredient = Read-Host " New active ingredient (replace with)"
# ---- Validate --------------------------------------------------
$pairsToProcess = @()
if ($OldDrugName.Trim() -ne "" -and $OldDrugName -ne $NewDrugName) {
$pairsToProcess += [PSCustomObject]@{ Find = $OldDrugName; Replace = $NewDrugName; Label = "Drug name" }
}
if ($OldIngredient.Trim() -ne "" -and $OldIngredient -ne $NewIngredient) {
$pairsToProcess += [PSCustomObject]@{ Find = $OldIngredient; Replace = $NewIngredient; Label = "Active ingredient" }
}
if ($pairsToProcess.Count -eq 0) {
Write-Host ""
Write-Host "[WARN] No replacement pairs defined (or old = new). Nothing to do." -ForegroundColor Yellow
Read-Host "`nPress ENTER to exit."
exit 0
}
# ---- Summary & confirm -----------------------------------------
Write-Host ""
Write-Log "Root folder : $RootFolder"
foreach ($pair in $pairsToProcess) {
Write-Log "$($pair.Label): '$($pair.Find)' --> '$($pair.Replace)'"
}
Write-Log "Log file : $LogFile"
Write-Host ""
$confirm = Read-Host "Proceed with replacement? (Y/N)"
if ($confirm -notmatch "^[Yy]$") {
Write-Host "Operation cancelled by user."
Read-Host "`nPress ENTER to exit."
exit 0
}
# ---- Discover .docx files --------------------------------------
Write-Host ""
$DocxFiles = Get-ChildItem -LiteralPath $RootFolder -Recurse -Filter "*.docx" |
Where-Object { -not $_.Name.StartsWith("~") } # skip Word temp/lock files
$TotalFiles = ($DocxFiles | Measure-Object).Count
Write-Log "Found $TotalFiles .docx file(s) under: $RootFolder"
if ($TotalFiles -eq 0) {
Write-Log "No .docx files found. Exiting." "WARN" Yellow
Read-Host "`nPress ENTER to exit."
exit 0
}
# ---- Start Word (COM) ------------------------------------------
Write-Log "Starting Microsoft Word via COM..."
$WordApp = $null
try {
$WordApp = New-Object -ComObject Word.Application
$WordApp.Visible = $false
$WordApp.DisplayAlerts = 0 # wdAlertsNone
}
catch {
Write-Log "Cannot start Microsoft Word. Is it installed? Error: $_" "ERROR" Red
Read-Host "`nPress ENTER to exit."
exit 1
}
# ---- Process files ---------------------------------------------
$SuccessCount = 0
$UpdatedCount = 0
$FailCount = 0
$FileIndex = 0
foreach ($File in $DocxFiles) {
$FileIndex++
$RelPath = $File.FullName.Replace($RootFolder, "").TrimStart("\").TrimStart("/")
Write-Log "[$FileIndex/$TotalFiles] $RelPath"
$Doc = $null
try {
# Open(FileName, ConfirmConversions, ReadOnly)
$Doc = $WordApp.Documents.Open($File.FullName, $false, $false)
$totalHits = 0
foreach ($pair in $pairsToProcess) {
$hits = Invoke-HeaderReplace -Document $Doc -FindText $pair.Find -ReplaceText $pair.Replace
$totalHits += $hits
if ($hits -gt 0) {
Write-Log " $($pair.Label) replaced ($hits section(s) matched)" "INFO" Green
}
}
$Doc.Save()
$Doc.Close($false)
$Doc = $null
$SuccessCount++
if ($totalHits -gt 0) {
$UpdatedCount++
} else {
Write-Log " No matches found in this file." "WARN" DarkYellow
}
}
catch {
Write-Log " FAILED: $_" "ERROR" Red
$FailCount++
if ($null -ne $Doc) {
try { $Doc.Close($false) } catch {}
$Doc = $null
}
}
}
# ---- Quit Word -------------------------------------------------
try { $WordApp.Quit() } catch {}
try {
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($WordApp) | Out-Null
} catch {}
$WordApp = $null
[GC]::Collect()
[GC]::WaitForPendingFinalizers()
# ---- Final summary ---------------------------------------------
Write-Host ""
Write-Log "================ SUMMARY ================"
Write-Log "Total .docx files : $TotalFiles"
Write-Log "Opened OK : $SuccessCount"
Write-Log "Headers updated : $UpdatedCount"
Write-Log "No match / skipped : $($SuccessCount - $UpdatedCount)"
Write-Log "Failed (errors) : $FailCount"
Write-Log "Log file : $LogFile"
Write-Log "========================================="
Write-Host ""
Read-Host "`nPress ENTER to exit."Uyarı :
Önce tüm belgelerin "YEDEKLERİNİ" alın....!!! (orjinallerin kopyası)
Kısa açıklama
Bu PowerShell betiği belirtilen kök klasör altındaki tüm .docx dosyalarını tarar, yalnızca belge header (üstbilgi) bölümlerinde verilen "bul / değiştir" çiftlerini uygular ve dosyaları kaydeder. Microsoft Word (COM) kullanır.
Gereksinimler
Windows + Microsoft Word yüklü.
PowerShell 5.1 veya 7.x.
Betiği .ps1 olarak kaydedip çalıştırma izniniz olmalı.
Nasıl kullanılır (adımlar)
Betiği bir .ps1 dosyası olarak kaydedin.
PowerShell'i açın (gerekiyorsa Yönetici olarak).
Betiği çalıştırın: PowerShell betiği başlatınca sizden
Root folder path (köK klasör)
Current drug name (bul)
New drug name (değiştir)
Current active ingredient (bul)
New active ingredient (değiştir) gibi girdiler istenir.
Onaylayın (Y) — script .docx dosyalarını açar, bölümlerdeki header’larda arama/yerine koyma yapar, kaydeder ve bir log dosyası oluşturur.İşlem bitince özet (kaç dosya, kaç güncelleme, hatalar) ve log dosyası yolu gösterilir.
Örnek (hayali senaryo)
Durum: İlaç katalogunuzda ürün adı değişti; 200'den fazla .docx şablonun üstbilgilerinde “OldMed” yazıyor ve etkin madde olarak “Acetaminophen” geçiyor. Yeni ad “NewMed”, yeni etkin madde yazımı “Paracetamol”.
Nasıl girersiniz:
Root folder path: C:\Projects\DrugDocs
Current drug name (find): OldMed
New drug name (replace with): NewMed
Current active ingredient (find): Acetaminophen
New active ingredient (replace with): Paracetamol
Ne olur ?:
Script C:\Projects\DrugDocs altındaki tüm .docx dosyalarını açar, her belgenin tüm header türlerinde (birinci sayfa, çift sayfa, normal) OldMed → NewMed ve Acetaminophen → Paracetamol aramalarını çalıştırır; eşleşme varsa dosyayı kaydeder. Her dosya için log kaydı tutulur; işlem sonunda toplam bulunan/ güncellenen dosya sayısını gösterir.
Kısıt/uyarılar
Sadece header (üstbilgi) içeriğini değiştirir; gövdedeki metinlere dokunmaz.
Word otomatik olarak açılıp kapatılır — Word yüklü değilse çalışmaz.
Geçici Word dosyaları (~ başlı olanlar) atlanır.

