使用 excel 电子表格中的条目检查目录中的文件名;我究竟做错了什么?

Checking file names in a directory with entries in an excel spreadsheet; What am I doing wrong?

我正在尝试编写一个 PowerShell 脚本(这是我的第一个,所以要温和)来遍历目录中的所有文件名并检查它们是否存在于我拥有的 excel 电子表格中。如果两者都存在文件名,我想 move/copy 那个文件到一个新目录。

现在它运行没有错误,但实际上什么也没有发生。

到目前为止我有:

#open excel sheet
$objexcel=new-object -com excel.application
$workbook=$objexcel.workbooks.open("<spreadsheet location>")
#use Sheet2
$worksheet = $workbook.sheets.Item(2)

#outer loop: loop through each file in directory
foreach ($_file in (get-childitem -path "<directory to search>"))
{
    $filename = [system.IO.path]::GetFileNameWithoutExtension($_)

    #inner loop: check with every entry in excel sheet (if is equal)
    $intRowCount = ($worksheet.UsedRange.Rows).count
    for ($intRow = 2 ; $intRow -le $intRowCount ; $intRow++)
    {
        $excelname = $worksheet.cells.item($intRow,1).value2
        if ($excelname -eq $filename)
        { #move to separate folder
            Copy-Item -path $_file -Destination "<directory for files to be copied to>"
        }
        #else do nothing
    }
}
#close excel sheet
$workbook.close()
$objexcel.quit()

您正在尝试根据当前对象 ($_) 定义 $filename,但该变量未填充在 foreach 循环中:

$filename = [system.IO.path]::GetFileNameWithoutExtension($_)

因为 $filename 始终是 $null,因此永远不会等于 $excelname

如果您想使用 $_,请将 foreach 循环替换为 ForEach-Object 循环。我还建议将 Excel 单元格值读入该循环外的数组。这提高了性能并允许您在 -contains 过滤器中使用它的数组,这将首先消除对循环的需要。

$intRowCount = ($worksheet.UsedRange.Rows).count
$excelnames = for ($intRow = 2; $intRow -le $intRowCount; $intRow++) {
  $worksheet.cells.item($intRow,1).value2
}

Get-ChildItem -Path "<directory to search>" |
  Where-Object { $excelnames -contains $_.BaseName } |
  Copy-Item -Destination "<directory for files to be copied to>"

更一般的说明:您不应该使用以下划线开头的变量名。它们很容易与当前对象变量的属性混淆($_name$_.name)。