[英]PowerShell Get-Content and replace object in a specific line
I have a text file with the following content: 我有一个包含以下内容的文本文件:
Static Text MachineA MachineB MachineC
Just Another Line
The first line has two static words (Static Text) with a space between. 第一行有两个静态词(静态文本),其间有空格。 After those two words there are 0 or more computer names, also seperated with a space.
在这两个单词之后有0个或更多计算机名称,也用空格分隔。
I need to find a way to add text to the first line (second line does not change) if there are 0 computers but also if there is 1 or more computers. 如果有0台计算机,但是如果有1台或更多台计算机,我需要找到一种方法将文本添加到第一行(第二行不会更改)。 I need to replace all computer names with a new computer name.
我需要用新的计算机名替换所有计算机名。 So the script should edit the file to get something like this:
所以脚本应该编辑文件来得到这样的东西:
Static Text MachineX MachineY
Just Another Line
I've looked at the -replace function with Regex but can't figure out why it is not working. 我用Regex查看了-replace函数,但无法弄清楚它为什么不起作用。 This is the script I have:
这是我的脚本:
$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"
$content = Get-Content $OptionsFile
$content |
ForEach-Object {
if ($_.ReadCount -eq 1) {
$_ -replace '\w+', $NewComputers
} else {
$_
}
} |
Set-Content $OptionsFile
I hope someone can help me out with this. 我希望有人可以帮助我解决这个问题。
If Static Text
doesn't appear elsewhere in the file, you could simply do this: 如果
Static Text
没有出现在文件的其他位置,您只需执行以下操作:
$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"
(Get-Content $OptionsFile) -replace '^(Static Text) .*', "`$1 $NewComputers" |
Set-Content $OptionsFile
If Static Text
can appear elsewhere, and you only want to replace the first line, you could do something like this: 如果
Static Text
可以出现在其他地方,并且您只想替换第一行,则可以执行以下操作:
$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"
(Get-Content $OptionsFile) | % {
if ($_.ReadCount -eq 1) {
"Static Text $NewComputers"
} else {
$_
}
} | Set-Content $OptionsFile
If you only know that Static Text
consists of two words in the first line, but don't know which words exactly they'll be, something like this should work: 如果你只知道
Static Text
在第一行包含两个单词,但不知道它们究竟是哪个单词,那么这样的东西应该有效:
$OptionsFile = "C:\scripts\OptionsFile.txt"
$NewComputers = "MachineX MachineY"
(Get-Content $OptionsFile) | % {
if ($_.ReadCount -eq 1) {
$_ -replace '^(\w+ \w+) .*', "`$1 $NewComputers"
} else {
$_
}
} | Set-Content $OptionsFile
Check if a line is starting with a 'Static Text ' followed by a sequence of word characters and return your string in case there a match: 检查一行是以“静态文本”开头,后跟一系列单词字符,如果匹配则返回字符串:
Get-Content $OptionsFile | foreach {
if($_ -match '^Static Text\s+(\w+\s)+')
{
'Static Text MachineX MachineY'
}
else
{
$_
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.