Forum Discussion
sunny sunny
Oct 01, 2017Copper Contributor
Search and Replace in power shell
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
Sort By
- Jiri ReznicekCopper Contributor
How about this?
it will
- make temporary copy of the file (test.tmp)
- read the file line per line
- if the line starts with "variable2" (can contain whitespaces around), line content is updated with new content
- save the result lines back into test.txt
- 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
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-filter-format-and-output-to-a-file-stupid-question-251-255/