powershell - PowerShell 嵌套 ForEach 循环的问题

标签 powershell foreach nested

我正在收集有关电子邮件的数据并导出为 CSV。在这部分脚本中,我需要生成一个文本文件,其中包含 CSV 文件中的 2 列。文本文件中已经存在第一列(电子邮件主题行文本),我需要在文件的每一行中添加以下内容:一个井号标签加上文件名的一部分加上一个井号标签。 Hashtags 是 CSV 文件的分隔符。
在我的第一个 ForEach 循环中,我遍历文件夹以生成文件名列表,然后拆分为我需要的名称部分。这行得通。然后在第二个 ForEach 循环中,我尝试遍历文件夹中的文件并将适当的文件名部分添加到每一行。它不是仅附加一个相关的文件名部分,而是将所有文件名附加到每一行。
以下是文件“Inbox_Subject_Reports & Timekeeping.txt”中的当前数据示例:

Re: your weekly business reports Re: submission of timesheet


期望的输出:
Re: your weekly business reports#Reports & Timekeeping.txt#
Re: submission of timesheet#Reports & Timekeeping.txt#
但是同一个文件夹中还有其他文件,所以我得到了所有文件名,并且数据被复制了 4 次:
Re: your weekly business reports#Reports & Timekeeping.txt#Fourth Quarter Returns#
Re: submission of timesheet#Reports & Timekeeping.txt#Fourth Quarter Returns#

Re: your weekly business reports#Reports & Timekeeping.txt#Fourth Quarter Returns#
Re: submission of timesheet#Reports & Timekeeping.txt#Fourth Quarter Returns#

Re: your weekly business reports#Reports & Timekeeping.txt#Fourth Quarter Returns#
Re: submission of timesheet#Reports & Timekeeping.txt#Fourth Quarter Returns#

Re: your weekly business reports#Reports & Timekeeping.txt#Fourth Quarter Returns#
Re: submission of timesheet#Reports & Timekeeping.txt#Fourth Quarter Returns#
是我的 ForEach 循环的嵌套吗?我需要某种“中断”功能吗?我喜欢 PowerShell 并且已经能够用它做很多事情,但是我在这里的知识已经达到了极限。我宁愿学习如何正确地做到这一点,也不愿创建一个繁琐的解决方法。
这是脚本部分:
$dir = "$Filelocation\Inbox_Subfolders\"
$filelist = @(Get-ChildItem $dir)

ForEach ($file in $filelist){
$folder = $file.Name.Split("_")[2]
}
{
$TextToAdd = "#" + $folder + "#"
$output = @()
$fileContent = Get-Content "$Filelocation\Inbox_Subfolders\Inbox_Subject_*.txt"
}
ForEach ($line in $filecontent){
$output += $line + $TextToAdd
$output | Set-Content "$Filelocation\Inbox_Subfolders\Inbox_Subject_*.txt"
}
我花了几天时间试图找出嵌套的 ForEach 循环以及我哪里出错了。我对达到相同结果的不同方式持开放态度。任何帮助是极大的赞赏。

最佳答案

首先:使用适当的缩进。这将使您更容易查看嵌套代码块的开始和结束位置。
这是做你想做的吗?

$dir = "$Filelocation\Inbox_Subfolders"

Get-ChildItem $dir -Filter *.txt | foreach {
    $folder = $_.Name.Split("_")[2]
    $TextToAdd = "#" + $folder + "#"
    (Get-Content $_.FullName) | foreach {
        $_ + $TextToAdd
    } | Set-Content $_.FullName
}

关于powershell - PowerShell 嵌套 ForEach 循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64576729/

相关文章:

powershell - 这是 PowerShell 中的错误吗?

powershell - 如何从Docker传递参数给 “find”?

csv - 填充单元格时出错 "Unable to index into an object of type"

Node.js Sequelize 在 forEach 循环中创建新行

html - 嵌套的 Div\Grids 960 显示不正确

powershell - 重新提交挂起作业 (start-job)

php - 有什么方法可以将 foreach 与 AND 一起使用吗?

c# - 是否有 Lambda Else 条件?

html - 在 div 中创建表单并尝试将内容保留在其中

php - PHP 中是否有空条件运算符?