打开文件夹中的所有 Excel 个文件并使用 PowerShell 保存

Open all Excel files in a folder and save using PowerShell

有很多小 excel table 引用了主 table,但用户没有主 table 的权限。所有者是 运行 脚本,因此 table 会更新,然后用户会看到新数据。每个人只能看到自己的 table(GDPR 数据)。

我无法在主 table 上设置权限,主 table 的密码不是解决方案,它会在更新数据时询问用户。

我找不到其他解决方案,所以我想使用脚本。

我想打开一个文件夹中的所有 Excel 个文件 (.xlsx) 并使用 PowerShell 保存它。

以下解决方案适用于文件:

$dir="C:\Temp\IPK_XY.xlsx"
$excl=New-Object -ComObject "Excel.Application"
$wrkb=$excl.Workbooks.Open($dir)
$excl.DisplayAlerts = $FALSE
$wrkb.Save()
$wrkb.Close()
$excl.Quit()

但是如何以类似的方式打开和保存所有文件?

谢谢你(对不起我的英语)!

此致, T

您想获取文件夹中的所有文件,然后运行 对每个项目进行循环。循环将重复您要执行的所有操作

# this is the path of the folder with all your files
# get all the files in this folder
$folderPath = "C:\Users\Scott\Desktop\gnl pbi\asdasd"    
$fileList = Get-ChildItem $folderPath

$excl = New-Object -ComObject "Excel.Application"
$excl.DisplayAlerts = $FALSE

# this is the loop with your desired actions
foreach ($fileName in $fileList)
{
    $filePath = Join-Path -Path $folderPath -ChildPath $fileName

    $wrkb = $excl.Workbooks.Open($filePath)
    $wrkb.Save()
    $wrkb.Close()
}

$excl.Quit()

继续我的评论,您需要一个循环来打开和保存这样的 xlsx 文件:

$allFiles = Get-ChildItem -Path 'X:\where\the\files\are' -Filter 'IPK_*.xlsx' -File
$excl     = New-Object -ComObject "Excel.Application"
$excl.DisplayAlerts = $false

foreach ($file in $allFiles) {
    $wrkb = $excl.Workbooks.Open($file.FullName)
    $wrkb.Save()   # or use just $wrkb.Close($true) to save and close
    $wrkb.Close()
}
# now quit excel and clean-up the used COM objects
$excl.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wrkb)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excl)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()