You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写PowerShell脚本将自定义Word模板部署到Office 365指定模板目录

Word自定义模板自动部署PowerShell脚本(适配Win10 + Office 365)
  • 脚本默认读取同目录下的template.dotm文件作为待部署的Word宏模板
  • 运行前请确保template.dotm文件和脚本放在同一文件夹下
  • 脚本默认的自定义模板路径和Office 365官方默认路径保持一致,可根据需求自行修改$newreg变量取值

完整可运行脚本

# 定义注册表路径与默认自定义模板路径
$regPath = "HKCU:\SOFTWARE\Microsoft\Office\16.0\Word\Options"
$regKeyName = "PersonalTemplates"
$newreg = Join-Path -Path $env:USERPROFILE -ChildPath "Documents\自定义 Office 模板"

# 1. 读取注册表判断是否存在有效配置
$regValue = $null
try {
    $getRegResult = Get-ItemProperty -Path $regPath -Name $regKeyName -ErrorAction Stop
    # 验证值类型为ExpandString且非空
    if ($getRegResult.PSObject.Properties[$regKeyName].Value.GetType().Name -eq "String" -and -not [string]::IsNullOrEmpty($getRegResult.$regKeyName)) {
        $regValue = $getRegResult.$regKeyName
    }
}
catch {
    Write-Host "未检测到已配置的PersonalTemplates注册表项,将使用默认路径创建"
}

# 2. 注册表项不存在/为空时创建对应ExpandString值
if ([string]::IsNullOrEmpty($regValue)) {
    # 注册表路径不存在则先创建路径
    if (-not (Test-Path -Path $regPath)) {
        New-Item -Path $regPath -Force | Out-Null
    }
    New-ItemProperty -Path $regPath -Name $regKeyName -PropertyType ExpandString -Value $newreg -Force | Out-Null
    $regValue = $newreg
}

# 3. 复制模板到目标路径
$templateSource = Join-Path -Path $PSScriptRoot -ChildPath "template.dotm"
$targetPath = Join-Path -Path $regValue -ChildPath "template.dotm"

# 校验源文件是否存在
if (-not (Test-Path -Path $templateSource)) {
    Write-Error "同目录下未找到template.dotm文件,请检查文件位置后重试"
    exit 1
}

# 目标目录不存在则自动创建
if (-not (Test-Path -Path $regValue)) {
    New-Item -Path $regValue -ItemType Directory -Force | Out-Null
}

# 覆盖复制模板文件
Copy-Item -Path $templateSource -Destination $targetPath -Force
Write-Host "模板已成功部署到:$targetPath"

使用说明

  • 将上述代码保存为后缀为.ps1的文件,和template.dotm放在同一目录
  • 右键点击脚本文件选择「使用PowerShell运行」即可执行
  • 若提示权限不足,可右键开始菜单选择「Windows PowerShell(管理员)」,执行Set-ExecutionPolicy RemoteSigned按Y确认后再运行脚本

内容的提问来源于stack exchange,提问作者SVR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:06:04