Search and Replace in power shell

Copper Contributor

Hello,

 

I am new to power shell and i am trying to achive below. I have file test.txt with data as shown below.

i want the search for variable2 and update the value as below.

select * from table1 order by column

Can you please guide me on how to achive this?

 

cat test.txt

variable1=DB1

variable2=select * from table1;

 

 

2 Replies

Do you need to run it in powershell trough a txt file or can you run it in a script?

 

You could take a look at this article on how to query SQL from PowerShell:
http://irisclasson.com/2013/10/16/how-do-i-query-a-sql-server-db-using-powershell-and-how-do-i-filte...

How about this?

 

it will

  1. make temporary copy of the file (test.tmp)
  2. read the file line per line
  3. if the line starts with "variable2" (can contain whitespaces around), line content is updated with new content
  4. save the result lines back into test.txt
  5. removes temporary copy of the file
Copy-Item .\test.txt .\test.tmp; Get-Content test.tmp|ForEach-Object {if($_ -match '^ *variable2 *=') {
"variable2=select * from table1 order by column"} else {$_}} | Out-File .\test.txt; Remove-Item .\test.tmp