嗨,我在 PowerShell 版本 2 中编写了以下代码。我正在利用 C#.NET 代码查询 Windows 搜索用户输入的特定文件夹中的 PDF 文件,对照 Excel 文件中的值。如果在其中一个 PDF 文件中找到该值,它会将 PDF 文件名输出到 excel 中,位于键旁边。
SerarchItemsInPDFs.ps1:
# Starting C# code
$Assem = (
"System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
)
$Source = @"
using System.Collections.Generic;
using System.Data.OleDb;
namespace Windows.Search
{
public class Tool2
{
public static List<string> Get(string Key, string Path)
{
using (OleDbConnection conn = new OleDbConnection("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';"))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT System.ItemPathDisplay FROM SYSTEMINDEX WHERE FREETEXT('" + Key + "') AND DIRECTORY = '" + Path + "'", conn);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
List<string> row = new List<string>();
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
row.Add(reader[i].ToString());
}
}
return row;
}
}
}
}
}
"@
Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
# End of C# code
# PoswerShell script begins
function IsData($variable) {if ($variable) {$true} else {$false}}
$ExcelPath = Read-Host "Enter the path to excel file"
$SheetName = "New Database"
$Excel = New-Object -ComObject "Excel.Application"
$Workbook = $Excel.workbooks.open($ExcelPath)
$Sheet = $Workbook.Worksheets.Item($SheetName)
$PDFsPath = Read-Host "Enter the path to PDFs folder"
$TotalUsedRows = $Sheet.usedRange.SpecialCells(11).row
"Starting rescue log file" | out-File "C:\Temp\output.txt"
for ($i=2; $i -le $TotalUsedRows; $i++)
{
$CellValue = $Sheet.Cells.Item($i,1).Text
If(!(IsData($CellValue))){continue}
$PDFsNames = [Windows.Search.Tool2]::Get($CellValue, $PDFsPath)
$records_found = 2
Write-Host $CellValue
foreach ($PDFName in $PDFsNames)
{
Write-Host $PDFName
$Sheet.Cells.Item($i, $records_found) = $PDFName
$CellValue + ";" + $PDFName + "," | out-File -Append "C:\Temp\output.txt"
$records_found++
}
}
$Workbook.SaveAs(“c:\Temp\results.xlsx”)
Write-Host "Job Done"
# End of PowerShell script
自 2.0 版以来,PowerShell 中引入了许多新的 cmdlet,有没有办法使用 POSH v4 摆脱 C# 代码部分?
考虑到我们正在使用产品的所有边缘版本(Windows 8.1、PowerShell 4 和 Office 2013),我们能否带来更多的语法优化?