gpt4 book ai didi

excel - 如何使用 PowerShell 保存只读文件

转载 作者:行者123 更新时间:2023-12-03 01:49:55 28 4
gpt4 key购买 nike

我正在打开一个 Excel 文件,为其应用密码,然后使用 PowerShell 保存它。我收到以下错误:

Exception calling "SaveAs" with "3" argument(s): "Cannot save as that name. Document was opened as read-only." At C:\PasswordProtectExcelFiles.ps1:38 char:45
+ $a = $wb.SaveAs("$($FilePath)",$xlNormal,"$($Password)")
+ ~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation

我进行了很多搜索,但没有解决我的问题。以下是我已经提到过的一些问题: Powershell - SaveAs function when file already exists How to Remove ReadOnly Attribute on File Using PowerShell?

我的代码:

param([string]$FilePath, [string]$Password )
$xl = new-object -comobject excel.application
$xl.Visible = $True
$xl.DisplayAlerts = $False

$wb = $xl.Workbooks.Open("$($FilePath)")

$a = $wb.SaveAs("$($FilePath)",$xlNormal,"$($Password)")

$a = $xl.Quit()

$a = Release-Ref($wb)
$a = Release-Ref($xl)

我在 Workbooks.Open 语句之后尝试了这些代码,看看它是否会保存只读文件,并且它有效,但是当我关闭并重新打开代码时,它停止工作:

Code1:
$file = Get-Item "$($FilePath)"
if ($file.IsReadOnly -eq $true)
{
$file.IsReadOnly = $false
}

Code2:
Set-ItemProperty "$($FilePath)" -name IsReadOnly -value $false

实际上,该文件不是只读的,但文件夹是只读的,我无法选中只读框。与此问题相同:https://social.technet.microsoft.com/Forums/windowsserver/en-US/f7ec4fc5-3bbe-4fd0-a8ca-c4ead75b010c/unable-to-removeclear-readonly-attribute-from-folder-in-windows-server-2008

最佳答案

根据the documentation for the Open() method ,第三个参数允许您指定是否以只读模式打开文件。

将其设置为$false:

$wb = $xl.Workbooks.Open("$($FilePath)", 0, $false)

关于excel - 如何使用 PowerShell 保存只读文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43460800/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com