首页 > 解决方案 > Powershell 代码无法识别当前位置的所有 excel 文件(*.xlsm)

问题描述

我目前正在使用 Powershell 来处理 excel 文件(*.xlsm)。问题是下面的代码只能读取“test.xlsm”。当名称不是 test 像 "this.xlsm" 时,该代码无法读取该文件。有什么帮助...?提前感谢您的回答:)

$destination = "C:\JJ\"

$dirName = Get-ChildItem -Name -Filter *.xlsm
$saveAs = $destination + "new\"

foreach($z in $dirName){
    $excel=New-Object -ComObject Excel.Application
    $excel.visible=$false
    $excel.Displ`ayAlerts=$false
    $book=$excel.Workbooks.Open($destination + $z)
    $sheet=$book.Worksheets.item(1)  
    $sheet.Cells.Item(1,5)="=max(B2:B6)"
    $book.SaveAs($saveAs + $z)
    $excel.Quit()
    $excel=$null
}

标签: excelpowershell

解决方案


# remove -name to get a directory object instead of a string
$dirName = Get-ChildItem -Filter *.xlsm

# you need the file name from the directory object listing
foreach($z in $dirName.name){ ...... }

推荐阅读