1

I would like to first find the file name (e.g XXX.txt) (which can be anything, BBB is just an example) stored in the .ps1 file and if found replace that by a value entered in the console. then I will update with a new one such as test.txt instead of xxx.txt

$DName = read-host -prompt "Please Enter File Name"

(Get-Content "C:\run.ps1") | 
Foreach-Object { $content = $_ -replace "$????","$DName" } | 
Set-Content "C:\run.ps1"

run.ps1 file:

$line = ''
Get-Content C:\bulk\XXX.txt | 
    Select-String -Pattern 'TEMP' |
        ForEach-Object {
        #blah blah
        }
3
  • Frame challenge: don't hard-code the file name. Pass it as an argument instead. Commented Mar 4, 2019 at 6:50
  • I am really not following you. This all seems very convoluted. You prompt the user for some random DBName, which you then try and look for in the results via a read call. You have no error checking for when that DBName does not exist. What is in $old, because you are not showing it. What is $line for? You are not using it anywhere. As for the -Pattern match. What are you trying to do with that? What is in Clients.txt and xxx.txt? Please up date your post. Commented Mar 4, 2019 at 6:51
  • @postanote sorry you are right. I have edited my question. Commented Mar 4, 2019 at 8:09

1 Answer 1

1

You may use

$_ -replace "(Get-Content\s+(['`"]?)C:\\bulk\\).*?(\.txt\2)", ('${1}' + $DName.replace('$','$$') + '$3')

See the regex demo

Details

  • (Get-Content\s+(['`"]?)C:\\bulk\\) - Group 1:
    • Get-Content\s+ - Get-Content and then 1+ whitespaces
    • (.*?) - Group 2: a ', " or empty string
    • C:\\bulk\\ - C:\bulk\ substring
  • .*? - 0 or more chars other than line break chars, as few as possible
  • (\.txt\2) - Group 2: .txt and the text captured in Group 2.

The replacement is the result of concatenating:

  • ${1} - Group 1 value (the braces are a must if BBB may actually start with a digit)
  • $DName.replace('$','$$') - the new file name with doubled $ chars (as these are special in .NET replacement patterns)
  • $3 - Group 3 value.
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer. But I have written only as example BBB. So this is dynamic. which can be anything, BBB is just an example.
@Arbelac I thought it was the simplest part (it is almost not related to regex), added to the answer.
@Arbelac I used the same variable names, does it work now?
I have been testing it. I will provide feedback to you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.