0
Get-ChildItem 'C:\Users\Zac\Downloads\script test\script test\*.txt' -Recurse | ForEach {(Get-Content $_ | ForEach { $_ -replace '1000', $fileNameOnly}) | Set-Content $_ }

I have been trying to use a simple PowerShell script to replace the 1000 value in my documents with the goal of replacing the value with the name of the .nc1/.txt file it is editing.

For example a file that is called BM3333.nc1 has a line value of 1000 which needs to replace it with BM3333 so on, so forth. This will be used in batch editing.

What is the variable that I use for replacing the 1000 with the file name? So far, I can get this to run but it doesn't replace the 1000 value, it removes it.

Compo
  • 36,585
  • 5
  • 27
  • 39
  • `$fileNameOnly` has never been defined in your code so it makes sense the word `1000` is being removed then – Santiago Squarzon Sep 24 '22 at 02:53
  • `Get-Content` has an optional parameter `-Raw` that returns the whole file as a single string. This allows you to issue a single `.Replace('1000', $fileNameOnly`) for each file, then write it out at once. – Instantiation Sep 24 '22 at 02:56

1 Answers1

0

Your problem is that inside the ScriptBlock of a ForEach-Object invocation, the variable is $_ (also known as $PSItem). There is no name for the inner script to get the value from the outer script.

You need to create a unique name in the outer script beforehand. The ScriptBlock argument to ForEach-Object does not need to be a single expression. You can either use multiple lines or a ;.

1..3 | ForEach-Object { $a = $_; 100..105 | ForEach-Object { $_ * $a } }

For your use case, you need this variable to be the name of the file. The values in the outer ScriptBlock are System.IO.FileSystemInfo, which were returned by Get-ChildInfo.

PowerShell makes iterating on work like this very easy; try seeing which properties are available:

Get-ChildItem 'C:\Users\Zac\Downloads\script test\script test\*.txt' -Recurse | Select-Object -First 1 | Format-List *

Instantiation
  • 303
  • 2
  • 7