【发布时间】: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