簡體   English   中英

PowerShell 嵌套 ForEach 循環的問題

[英]Problem with PowerShell nested ForEach Loop

我正在收集有關電子郵件的數據並導出到 CSV。 在腳本的這一部分中,我需要生成一個文本文件,其中包含 CSV 文件中的 2 列。 第一列(電子郵件主題行文本)已存在於文本文件中,我需要將以下內容添加到文件的每一行:散列標簽加上文件名的一部分加上散列標簽。 Hashtags 是我的 CSV 文件的分隔符。

在我的第一個 ForEach 循環中,我遍歷文件夾以生成文件名列表,然后拆分為我需要的名稱部分。 這有效。 然后在第二個 ForEach 循環中,我嘗試遍歷文件夾中的文件並將適當的文件名部分添加到每一行。 它不是僅附加一個相關的文件名部分,而是將所有文件名附加到每一行。

以下是文件“Inbox_Subject_Reports & Timekeeping.txt”中的當前數據示例:

回復:您的每周業務報告 回復:提交時間表

期望的輸出:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM