您好我在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),我们能否带来更多语法优化?