基于文本的自动生成邮件合并

基于文本的自动生成邮件合并

我有一个文本文件。

如果可能的话,我想要一个简单的便携式应用程序,它可以自动生成 176 个不同的版本,其中唯一的区别(例如 {%FIELD1%} 是从一个单独的文件中提取的,每个文件都从换行符中提取。

我见过这个,但这是一个单词插件,不是我想要的 https://www.gmayor.com/individual_merge_letters.htm

答案1

该脚本如下:

  • 加载文本文件
  • 加载包含列表的单独文件
  • {%FIELD1%}用列表中的值替换文本文件中的术语
  • 每次替换都会写出一个单独的文本文件

使用说明:

  • 将以下代码复制粘贴到带有扩展名的文件中ps1
  • 使用 Windows PowerShell ISE(或文本编辑器)打开它并根据需要编辑$mainfile$mergelistfile和。$fieldstring$outpath
  • 运行该.ps1文件。
# A very simple "mail-merge" script that replaces text in a template file with a 
# value from a list and then writes the text with the replacement to another file.
# This script assumes the following:
# - a $mainfile exists: this is the text file where you want to do the replacements in
# - a $mergelist exists: this is a list of values which you want to use as replacements
# - $mainfile uses the value $fieldstring to indicate the part that should be replaced
# - There either is a writable $outpath or you have permission to create one

$mainfile = '.\mainmerge.txt'
$mergelistfile = '.\mergelist.csv'
$fieldstring = '{%FIELD1%}'
$outpath = '.\mergeoutput'

# Get the mainfile and mergelistfile contents
$maincontent = Get-Content -Path $mainfile -Raw
$mergelist = Get-Content -Path $mergelistfile

# Create the output directory if it doesn't exist yet
if(-Not (Test-Path $outpath)){
    New-Item -ItemType directory -Path $outpath
}

# Loop through $mergelist
$counter = 1
foreach($entry in $mergelist){
    # The output filename with a zero padded number prepended 
    $outfilename = ([string]$counter).PadLeft(3,'0') + " merged.txt"

    # Replace the $fieldstring by the current entry from the mergelist
    $merged = $maincontent -replace $fieldstring, $entry

    # Create the full path of the output file
    $fulloutpath = Join-Path -Path $outpath -ChildPath $outfilename

    # Write the merged file to the full outputpath
    $merged | Add-Content -Path $fulloutpath

    # Increment the counter for the output filename
    $counter++
}

相关内容