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
        }
Arbelac
  • 1,698
  • 6
  • 37
  • 90
  • Frame challenge: don't hard-code the file name. Pass it [as an argument](https://stackoverflow.com/q/16426688/503046) instead. – vonPryz Mar 04 '19 at 06: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. – postanote Mar 04 '19 at 06:51
  • @postanote sorry you are right. I have edited my question. – Arbelac Mar 04 '19 at 08:09

1 Answers1

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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563