首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PowerShell:将两个字符串放入哈希表并输出到.csv

PowerShell:将两个字符串放入哈希表并输出到.csv
EN

Stack Overflow用户
提问于 2016-04-28 00:07:29
回答 1查看 120关注 0票数 0

这里是PowerShell新手

我需要:

  1. 在具有公共字符串( students.txt )的递归本地目录中获取文本文件。
  2. 获取另一个字符串,即从#1设置的结果文件中的gc.student="name,name",并获取名称。
  3. 将#1中的文件名和#2中的名称(不是gc.student="") )放在哈希表中,其中文件名与其对应的名称名称匹配。
  4. 将哈希表输出到包含2列的Excel电子表格中:文件、名称

我在这里和其他地方搜索和学习了如何将#1输出到屏幕上,但不知道如何将其放在带有#2的哈希表中:

代码语言:javascript
运行
复制
$documentsfolder = "C:\records\"
foreach ($file in Get-ChildItem $documentsfolder -recurse | Select String -pattern "students.txt" ) {$file}

我正在考虑在#2中获得名称,我需要使用RegEx,因为有时可能只有一个名称。对于输出到Excel,如下所示:| Export-Csv -NoType output.csv

任何能让我继续前进的帮助都是非常感谢的。

EN

回答 1

Stack Overflow用户

发布于 2016-04-28 05:43:42

我觉得这应该能让你开始。解释在代码注释中。

代码语言:javascript
运行
复制
# 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36903031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档