将文件另存为现有脚本的对话框

Dialog box to save file as on existing script

我有以下代码,但我试图让它通过动态对话框提示用户将输出文件获取到 "save as"。

$pathtsv = "c:\test.txt"
$pathxlsx = "c:\NBP ESP-152 REV F TEMPLATE.xlsx"

$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true 

$Workbook = $Excel.Workbooks.Open($pathxlsx) # Open Template
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv) # Open text file in excel

$temp = $excel.Workbooks.Item(2)  #select workbook with text
$temp = $temp.Worksheets.Item(1) #select text worksheet
$CopyRange = $temp.Range("A1:G8") #set range
$CopyRange.Copy()  #copy data

$workbooksheet = $Workbook.Worksheets.Item(1)#sets doc to copy to
$Workbooksheet.activate()
$PasteRange = $workbooksheet.Range("A3:J10") #sets range
$workbooksheet.Paste($PasteRange)#paste data

#save and close the workbook
$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()

所以我尝试添加:

$SaveFileDialog = New-Object windows.forms.savefiledialog   
    $SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory() 

但它似乎不起作用。不知道为什么,也许是因为我对 powershell 脚本编写仍然是新手。我只想让它在另存为对话框中结束,就好了。我必须把原件的结尾剪掉吗? (IE。这会被删掉吗?

$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()

)

您需要做一些事情才能完成这项工作。首先,添加对System.Windows.Forms

的引用
Add-Type -AssemblyName System.Windows.Forms

在您的 copy/paste 操作之后创建对话框并设置几个属性

$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()
$SaveFileDialog.Filter = 'All files (*.*)|*.*'

您需要在此处决定显示对话框时要执行的操作。您是否允许用户取消,您如何处理空路径、不正确的扩展名等......为了举例,我将继续展示它直到选择路径。我不认为这是一个好的选择。

$dialogResult = $null
while($dialogResult -ne "OK"){
    $dialogResult = $SaveFileDialog.ShowDialog()
}

然后您可以使用文件名 属性 访问选定的路径并对其执行所需的检查

$SaveFileDialog.FileName

将此传递给 excel 工作簿的 SaveAs 方法。有关此方法的详细信息,请参阅此答案

$WorkBook.SaveAs($SaveFileDialog.FileName, 51, [Type]::Missing, [Type]::Missing, $false, $false, 1, 2)

最后关闭您的工作簿并 excel。执行清理等