【发布时间】:2015-05-20 00:13:49
【问题描述】:
我正在尝试编写一个 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;
【问题讨论】:
-
我猜没有名为
TestSheet的工作表,因为这是脚本真正执行任何操作的唯一条件 -
语法看起来正确吗?我正在寻找的工作表可能是“非常隐藏”的工作表。它还会被程序识别吗?感谢您的快速回复。
-
哈,看得很清楚,你刚刚回答了你自己的问题! Powershell中的比较测试使用
-eq而不是=,所以你需要:$WorkSheet.Name -eq "TestSheet" -
@acro444,感谢您的纠错!但是,它仍然坐在那里。我什至在我的逻辑中添加了
Else。请查看我更新的帖子,如果我只是想做一些愚蠢的事情,请告诉我......目录绝对正确,我正在从PS C:\>在powershell 中执行,所以不是那样的。
标签: excel powershell