
[英]Is there a better way to delete shapes in a Word document, with PowerShell?
[英]Is there a better way to combine multiple scripts for Word in PowerShell?
我一直在尝试运行一个批处理文件,它读取一个文本文件,然后运行一堆 powershell 脚本文件。 但是,当我以这种方式尝试时似乎没有任何反应。
我一直将其用作我的 batch.ps1 文件:
Add-Type -AssemblyName Microsoft.Office.Interop.Word
if(!$word){
$word = New-Object -ComObject Word.Application
$word.Visible = $false
}
$directory = "C:\temp"
$DocxFiles = Get-ChildItem -Path $directory -Filter "*.docm"
$counter = 1
#Menu
Write-Host "==========" -BackgroundColor DarkGreen
Write-Host "===MENU===" -BackgroundColor DarkGreen
Write-Host "==========" -BackgroundColor DarkGreen
$(for($i=0; $i -lt $DocxFiles.Count; $i++){
[PSCustomObject]@{
'File Name' = "${i}: $($DocxFiles.BaseName[$i])"
'Last Write Time' = $DocxFiles.LastWriteTime[$i]
}
}) | Out-Host
Write-Host ""
$fileToEdit = Read-Host -Prompt "Select a file from the menu"
Clear-Host
$fileToEdit = "$($DocxFiles[$fileToEdit].FullName)"
# Get list of scripts to run
$file = Get-Content "C:\paths_02.txt"
# Loop through each script and run it, passing the file to edit as a parameter
foreach ($line in $file) {
if ($line.StartsWith("#")) {continue}
$scriptPath = $line.Trim()
Start-Process powershell.exe -ArgumentList "-File $scriptPath -fileToEdit $fileToEdit" -Wait
}
$word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word)
然后这是应该阅读的脚本示例:
param($fileToEdit)
$input = $fileToEdit
$doc = $word.Documents.Open($input,$false,$false,$false)
$header = $doc.Sections.Item(1).Headers.Item(1).Range
#delete header
$header.Delete()
#select footer
$footer = $doc.Sections.Item(1).Footers.Item(1).Range
#Delete footer
$footer.Delete()
$doc.Save()
$doc.Close()
Write-Host "The header and footer of the file '$input' have been deleted" -ForegroundColor Green
但是,正如我所说,似乎什么都没有发生。
你说什么都没有发生是什么意思? 它至少应该要求Read-Host
的输入
我看到的一个问题是您正在为每个脚本启动单独的 powershell 实例,并且它们不会加载$word
COM 内容。 这也意味着您不会看到它们抛出的任何错误。
尝试对每个脚本进行点源,而不是像:
# uncommented script names
$scripts = (Get-Content "C:\test\test.txt") -notmatch '^#'
foreach ($line in $scripts) {
Write-Output "running script $line"
# execute each script
if (Test-Path $line) {
. $line.Trim() -fileToEdit $fileToEdit
}
else { Write-Error "could not find $line" }
}
为了可读性,我不建议将您的子脚本加载为来自另一个文件的文本路径。 Powershell 支持多种方式来捆绑多个脚本,例如将它们加载为可以直接运行的函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.