【问题标题】:Writing content to files with "foreach" loop in powershell在powershell中使用“foreach”循环将内容写入文件
【发布时间】:2021-04-26 19:57:00
【问题描述】:

任务: 需要用新信息更新目录中的所有文件。首先我们找到内容,然后在所有文件中替换它。

问题: 更新文件时,其他文件中的数据会附加到下一个文件中。

示例:

原文件内容:

文件1

net use /persistent:no

net use p: \\houfilesvr01\company

net use s: \\houfilesvr01\shared

文件2

net use /persistent:yes

net use T: "\\houfilesvr01\advanced pharmacy"

net use R: "\\houfilesvr01\Advanced Pharmacy\Account MGMT"

net use S: "\\houfilesvr01\Advanced Pharmacy\Implementation"

发布更新内容:

文件 1 和文件 2

net use /persistent:yes

net use T: "\\aps.local\advanced pharmacy"

net use R: "\\aps.local\Advanced Pharmacy\Account MGMT"

net use S: "\\aps.local\Advanced Pharmacy\Implementation"

net use /persistent:no

net use p: \\aps.local\company

net use s: \\aps.local\shared

正在进行所需的更改,但更改正在写入每个文件。我们不希望这样!


<# Variable Declaration  
$find - Values to replace
$replace - replacemtn values
$filepath - path of files
$content - content of existing files
$newcontent - updated content to write back to file 
#>
<# Variable Assignment #>
    $find = "houfilesvr01"
    $replace = "aps.local"
    $filepath = "C:\Users\jshabazz\Documents\Area51\logonscripttesting\Testfiles\*.*"
    
<# execution #>
    
    foreach($file in $filepath)
        {
             $content = get-content $file
             $newcontent = $content -replace 'houfilesvr01', 'aps.local'
             set-content -Path $filepath -value $newcontent
             
        }

【问题讨论】:

    标签: powershell foreach


    【解决方案1】:
    foreach($file in Get-ChildItem $filepath) {
      $content = get-content $file.FullName
      $newcontent = $content -replace 'houfilesvr01', 'aps.local'
      set-content -Path $file.FullName -value $newcontent           
    }
    

    注意:在Windows PowerShell 中使用.FullName 属性是安全的,其中System.IO.FileInfo 实例由Get-ChildItem 输出按情况字符串化为仅文件 names。在 PowerShell (Core) v7+ 中不再需要这样做,因为现在可以确保无条件的全路径字符串化。


    至于你尝试了什么

    • 由于$filepath 只是一个字符串foreach($file in $filepath) 不会枚举任何内容,它实际上只是将该字符串复制到变量$file

    • Get-Content 和 - 也许更令人惊讶的是 - 还有 Set-Content 直接接受通配符路径作为它们(位置上)隐含的 -Path 参数,在这种情况下它们读取/写入所有匹配的文件.

    【讨论】:

      猜你喜欢
      • 2018-10-28
      • 2017-08-22
      • 2012-08-20
      • 2013-07-09
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 2019-02-21
      • 2014-10-05
      相关资源
      最近更新 更多