2016-04-28 13 views
0

PowerShell的新手在这里,PowerShell的:获得2串到一个Hashtable和出为.csv

我需要:

  1. 获取具有相同的字符串,学生递归本地目录中的文本文件。 txt在其中。
  2. 获得另一个字符串,gc.student = “#1设置生成的文件中,并得到了(S)。
  3. 把文件名从#1,只是名称从#2(不gc.student =“”)入其中的文件名与其相对应名称成对的散列表名字
  4. 将散列表输出到包含2列的Excel电子表格中:文件名称

我已经想通了,已经搜索并了解到这里和其他地方,如何输出#1到屏幕上,而不是如何把它变成一个哈希表与#2:

$documentsfolder = "C:\records\" 
foreach ($file in Get-ChildItem $documentsfolder -recurse | Select String -pattern "students.txt") {$file} 

我想要在#2中获得名称我需要使用正则表达式,因为有时候可能只有1 名称。 而对于输出到Excel,这个:| Export-Csv -NoType output.csv

任何帮助让我感动。

回答

0

我认为这应该让你开始。解释在代码注释中。

# base directory 
$documentsfolder = 'C:\records\' 

# get files with names ending with students.txt 
$files = Get-ChildItem $documentsfolder -recurse | Where-Object {$_.Name -like "*students.txt"} 

# process each of the files 
foreach ($file in $files) 
{ 
    $fileContents = Get-Content $file 
    $fileName = $file.Name 

    #series of matches to clean up different parts of the content 
    #first find the gc.... pattern 
    $fileContents = ($fileContents | Select-String -Pattern 'gc.student=".*"').Matches.Value 
    # then select the string with double quotes 
    $fileContents = ($fileContents | Select-String '".*"').Matches.Value 
    # then remove the leading and trailing double quotes 
    $fileContents = $fileContents -replace '^"','' -replace '"$','' 

    # drop the objects to the pipeline so that you can pipe it to export-csv 
    # I am creating custom objects so that your CSV headers will nave nice column names 
    Write-Output [pscustomobject]@{file=$fileName;name=$fileContents} 
} | Export-Csv -NoType output.csv