使用Powershell筛选文件夹中的所有Excel文件

时间:2019-02-27 16:13:46

标签: excel powershell

我对Powershell还是很陌生,但我希望这很容易,而且我刚刚弄错了代码片段。我收到以下代码的运行错误,我希望该代码可以遍历文件夹和子文件夹中的所有文件,并对其中的所有文件放置过滤器。如果有帮助,所有文件都将始终为.xlsx。

$ErrorActionPreference= 'silentlycontinue'
Write "Loading Files..."
$path = "C:\test"
$files = Get-ChildItem C:\test\*.xlsx
Write "Files Loaded."
ForEach ($file in $files)
{

## Instantiate the COM object
$excelObj = New-Object -ComObject Excel.Application

$excelWorkBook = $excelObj.Workbooks.Open($path)
$excelWorkSheet = $excelObj.WorkSheets.item("sheet1")
$excelWorkSheet.activate()

## Turn on auto-filter
$headerRange = $excelWorkSheet.Range("a1","z1").AutoFilter() | Out-Null

## close everything
$excelWorkBook.Save()
$excelWorkBook.Close()
$excelObj.Quit()

## make sure the process is really gone...
Get-Process | where {$_.Name -like "Excel*"} | % {
    $Id = $_.id
    if ((Get-WmiObject Win32_Process -Filter "ProcessID = '$id'" | select CommandLine) -like "*embed*")
    {
        Stop-Process -Id $id -WhatIf
    }
}

0 个答案:

没有答案