使用Powershell来遍历Excel文件并检查Spreadsheet名称是否存在

我试图编写一个PowerShell脚本,将遍历给定的目录中的每个Excel文件,检查文件的具体命名的工作表,然后将该文件复制到另一个位置,如果它匹配。

请参阅下面我已经尝试过的内容:

[void][reflection.assembly]::Loadwithpartialname("microsoft.office.excel") $Excel = New-Object -ComObject Excel.Application $tempLocation = "C:\Test\" # Path to read files $files = Get-ChildItem C:\Test ForEach ($file in $files) { #Check for Worksheet named TestSheet $WorkBook = $Excel.Workbooks.Open($file) $WorkSheets = $WorkBook.WorkSheets foreach ($WorkSheet in $Workbook.Worksheets) { If ($WorkSheet.Name -eq "TestSheet") {$path = $tempLocation + "\" + $file Write "Saving $path" Copy-Item c:\Test\$file c:\Confirmed} Else {Write "$path does not contain TestSheet"} $WorkBook.Close() } } 

这个脚本在PowerShell中没有返回任何错误,只是坐在那里而不写任何东西或者复制任何文件。 有任何想法吗?

编辑:这是我现在正在运行成功的最终脚本

 $ErrorActionPreference= 'silentlycontinue' $tempLocation = "C:\Source" # Path to read files $targetlocation = "C:\Target" Write "Loading Files..." $files = Get-ChildItem C:\Source Write "Files Loaded." ForEach ($file in $files) { #Check for Worksheet named TestSheet $Excel = New-Object -ComObject Excel.Application $Excel.visible = $false $Excel.DisplayAlerts = $false $WorkBook = $Excel.Workbooks.Open($file.Fullname) $WorkSheets = $WorkBook.WorkSheets | where {$_.name -eq "TestSheet"} if($WorkSheets) { $path = $tempLocation + "\" + $file $dest = $targetlocation + "\" + $file Write "Saving $path" $WorkBook.SaveAs($dest) } $Excel.Quit() Stop-Process -processname EXCEL } Read-host -prompt "The Scan has completed. Press ENTER to close..." clear-host; 

我的脚本的逻辑有几个问题。 以下脚本成功运行! 花了数小时的研究

 $ErrorActionPreference= 'silentlycontinue' $tempLocation = "C:\Source" # Path to read files $targetlocation = "C:\Target" Write "Loading Files..." $files = Get-ChildItem C:\Source Write "Files Loaded." ForEach ($file in $files) { #Check for Worksheet named TestSheet $Excel = New-Object -ComObject Excel.Application $Excel.visible = $false $Excel.DisplayAlerts = $false $WorkBook = $Excel.Workbooks.Open($file.Fullname) $WorkSheets = $WorkBook.WorkSheets | where {$_.name -eq "TestSheet"} if($WorkSheets) { $path = $tempLocation + "\" + $file $dest = $targetlocation + "\" + $file Write "Saving $path" $WorkBook.SaveAs($dest) } $Excel.Quit() Stop-Process -processname EXCEL } Read-host -prompt "The Scan has completed. Press ENTER to close..." clear-host; 

你不需要这行:

 [void][reflection.assembly]::Loadwithpartialname("microsoft.office.excel") 

($ Excel = New-Object -ComObject Excel.Application就足够了)

我不认为你正在引用你的Excel文件的完整path。 尝试修改这一行:

 $WorkBook = $Excel.Workbooks.Open($file) 

修改为:

 $WorkBook = $Excel.Workbooks.Open($file.Fullname) 

此外,考虑添加一个filter到您的Get-ChildItem命令,如果有子目录或非Excel文件,它们将导致错误:

 $files = Get-ChildItem C:\Test -filter "*.xls"