如何读取包含需要读取PowerShell的其他文本文件的路径的文本文件



我正在尝试创建一个powershell脚本,该脚本将:

  1. 阅读包含路径(Path1,path2,..(的文本文件(paths.txt(。

  2. 对于每条路径,我想阅读其内容并查找特定文本(例如"在线"(。

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

    • 如果不是,请在文件和文件的内容(add.txt(

    • 中添加此特定文本("在线"(

从redd编辑:

正如所承诺的

评论中的当前代码:

$p = C:userpaths.txt 
$paths = get-content $p

重写:

$paths = Get-Content "C:userpaths.txt"

现在的目标是为每一行循环。在这里,您将使用一个for for for-loop。

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

所以您到目前为止都有。

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

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

还有其他方法可以完成此操作,但这是一种易于阅读的简单方法。对不起,我无法通过它来浏览它,因为我无法发表评论,因为我还没有足够的代表。但是我评论了下面的代码,希望您能看到我在做什么。如果这不是您要做的事情,或者您有任何疑问,请告诉我!

$paths = Get-Content "C:Userspaths.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
}

最新更新