【问题标题】:How to read a text file that contains paths to other text files that need read powershell如何读取包含需要读取powershell的其他文本文件的路径的文本文件
【发布时间】:2019-11-14 03:43:04
【问题描述】:

我正在尝试创建一个 PowerShell 脚本,它将:

  1. 读取包含路径(path1、path2、..)的文本文件(Paths.txt)。

  2. 对于每条路径,我想阅读其内容并查找特定文本(例如“UNDER LINE”)。

    • 如果找到,在此区域下添加另一个文件(Add.txt)的内容。

    • 如果没有,则将此特定文本(“UNDER LINE”)添加到文件和文件内容(Add.txt)


从 Redd 编辑:

正如我们所承诺的那样,我们将共同解决这个问题。

来自 cmets 的当前代码:

$p = C:\user\paths.txt 
$paths = get-content $p

重写:

$paths = Get-Content "C:\user\paths.txt"

现在的目标是循环每一行。在这里,您将使用 ForEach-Loop。

ForEach($path in $paths){
    Write-Host $path
}

【问题讨论】:

  • 到目前为止你做了什么?
  • 我没有尝试过使用 get-content 来获取 paths.txt 的内容,但就在该文本文件中打开这些路径并打开 path1.txt path2.txt 还没有想到找出最好的方法来做到这一点,所以它不会将它们组合成一行。
  • 好吧,让我们一起解决这个问题,直到我们有第一部分代码要发布或者?因此,我们首先使用Get-Content 读取paths.txt 的内容,然后我们想要遍历每一行(line -eq 路径)并在上面使用Get-conten 还是?
  • 我们要使用 foreach($line in $paths) 吗?我有这个 $p = C:\user\paths.txt $paths = get-content $p
  • @DevinLathsaw 我在上面添加了你的代码。请使用@符号,因为我没有看到您的评论^^

标签: powershell file text


【解决方案1】:

所以到目前为止你有这个..

$paths = Get-Content "C:\user\paths.txt"
ForEach($path in $paths){
    Write-Host $path
}

接下来,您需要在第一个 ForEach 循环中使用 Get-Content $path,然后通过在第一个循环中使用另一个 ForEach 循环来循环该文件的内容。然后添加If 语句以检查该行中是否有“UNDER LINE”。

还有其他方法可以完成此操作,但这是一种易于阅读的简单方法。抱歉,我无法引导您完成它,因为我还没有足够的代表,所以我无法发表评论。但我评论了下面的代码,希望你能看到我在做什么。如果这不是您想要做的,或者如果您有任何问题,请告诉我!

$paths = Get-Content "C:\Users\paths.txt"
# Loop through paths.txt for each path

ForEach($path in $paths){
    # Store the content of $path
    $OriginalFile = Get-Content $path

    # List for creating the new updated/modified file
    [String[]]$ModifiedFile = @()

    # Loop through each line of the Original file
    ForEach($line in $OriginalFile){

        # Check the line if "UNDER LINE" is on that line
        if($line -like "*UNDER LINE*"){

            # Add the current line from the Original file to the new file
            $ModifiedFile += $line

            # Add the content of Add.txt (Update the path for the Add.txt)
            $ModifiedFile += Get-Content ".\Add.txt"
        }
        # If the line from the Original file doesn't contain "UNDER LINE"
        else {

            # Add "UNDER LINE" to the new file
            $ModifiedFile += "UNDER LINE"

            # Add the content of Add.txt (Update the path for the Add.txt)
            $ModifiedFile += Get-Content ".\Add.txt"
        }
    }

    # This will overwrite $path file with the modified version.
    # For testing purposes change $path to a new file name to verify output txt file is correct.
    Set-Content $path $ModifiedFile
}

【讨论】:

    猜你喜欢
    • 2013-11-21
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-29
    相关资源
    最近更新 更多