用powershell将word文档另存为docx或者pdf的时候,如果所指向的目录文件夹不存在就会报错

用powershell将word文档另存为docx或者pdf的时候,如果所指向的目录文件夹不存在就会报错,如何解决呢?如果不存在就先创建再保存可以吗?怎么写?

注:我的需求是,保存为docx和pdf都先判断,如果文件夹不存在就先创建再保存。


$word=new-object -ComObject "Word.Application"
$word.visible=$true
$doc=$word.documents.Add()
$docfile="D:\hi5f5t\theCollection\test.docx"
$pdffile="D:\hi5f5t\theCollection\test.pdf"
$Doc.SaveAs([ref] $pdffile, [ref] 17)
$doc.SaveAs([ref] $docfile)

报错信息如下


这不是有效文件名。
请试用下列方法: 
* 检查路径,确认键入无误。
* 从文件和文件夹列表中选择文件。
所在位置 D:\hi5f5t\bin\writeMyDoc - 副本.ps1:17 字符: 1
+ $doc.SaveAs([ref] $docfile)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

该回答引用ChatGPT

如有疑问,可以回复我!

测试一下我这个

$word = New-Object -ComObject "Word.Application"
$word.Visible = $true
$doc = $word.Documents.Add()

$docfile = "D:\hi5f5t\theCollection\test.docx"
$pdffile = "D:\hi5f5t\theCollection\test.pdf"
$directory = "D:\hi5f5t\theCollection"

if (!(Test-Path -Path $directory)) {
    New-Item -ItemType Directory -Path $directory
}

$doc.SaveAs([ref] $docfile)

$word.ActiveDocument.ExportAsFixedFormat($pdffile, 17) # 使用ExportAsFixedFormat方法将文件另存为PDF格式
$doc.Close([ref] $false)
$word.Quit()


参考GPT和自己的思路:可以使用PowerShell中的Test-Path cmdlet来检查目录是否存在,如果不存在,可以使用New-Item cmdlet创建目录。以下是修改后的代码:

$word = New-Object -ComObject "Word.Application"
$word.Visible = $true
$doc = $word.Documents.Add()
$docPath = "D:\hi5f5t\theCollection\test.docx"
$pdfPath = "D:\hi5f5t\theCollection\test.pdf"

# 判断目录是否存在,如果不存在,创建目录
if (!(Test-Path -Path (Split-Path -Path $docPath -Parent))) {
    New-Item -ItemType Directory -Force -Path (Split-Path -Path $docPath -Parent)
}

if (!(Test-Path -Path (Split-Path -Path $pdfPath -Parent))) {
    New-Item -ItemType Directory -Force -Path (Split-Path -Path $pdfPath -Parent)
}

$doc.SaveAs([ref] $docPath)
$doc.SaveAs([ref] $pdfPath, [ref] 17)


在此代码中,我们首先检查目录是否存在,如果不存在,则使用New-Item cmdlet创建目录。然后我们保存Word文档和PDF文档,分别使用SaveAs方法,并使用[ref]参数传递参数以便在COM调用时使用。

参考GPT和自己的思路,按照你的需求已修改代码如下:

# Word 文件路径以及目标保存路径
$docfile = "D:\hi5f5t\theCollection\test.docx"
$pdffile = "D:\hi5f5t\theCollection\test.pdf"

# 检查文件夹是否存在,不存在就创建文件夹
$folderPath = Split-Path $docfile -Parent
if (!(Test-Path $folderPath)) {
    New-Item -ItemType Directory -Force -Path $folderPath
}

# 创建 Word 实例并添加一个空白文档
$word = New-Object -ComObject "Word.Application"
$document = $word.Documents.Add()

# 保存为 PDF 和 DOCX 格式
[ref]$saveAsPdf = $pdffile
[ref]$saveAsDocx = $docfile
$document.SaveAs($saveAsPdf, [ref]17)
$document.SaveAs($saveAsDocx)

# 关闭 Document 和 Word 实例
$document.Close()
$word.Quit()

以上代码会在 $docfile 指定的路径下创建文件夹(如果不存在的话),然后创建 Word 实例并添加空白文档,最后保存为 PDF 和 DOCX 格式。

如果您需要在后续代码中对 Word 文档进行操作,请记得首先退出 Word 实例,否则可能会造成无法预期的问题。下面是退出 Word 实例的代码:

$document.Close()
$word.Quit()
Remove-Variable word, document