Powershell Foreach-Object Foreach loop read string from several files and write to one
powershell
Solution
Assuming you've defined $FilePath, $user, and/or $computer elsewhere, try something like this.
$files = Get-ChildItem $FilePath\*.txt
foreach ($file in $files)
{
(Get-Content $file) |
Foreach-Object { $content = $_ -replace "User:", "User: $user" ; $content -replace "Computer:", "Computer: $computer" } |
Set-Content $file
}
You can use `;` to delimit additional commands in within the `Foreach-Object`, for example if you wanted to have separate commands for your user and computer name. If you don't enclose the Get-Content cmdlet with parenthesis you will get an error because that process will still have $file open when Set-Content tries to use it.
Also note that with Powershell, strings in double quotes will evaluate variables, so you can put $user in the string to do something like `"User: $user"` if you so desired.
Problem
I have trouble to use several commands in one Foreach or Foreach-Object loop My situation is - - I have many text files, about 100. So they are read `Get-ChildItem $FilePath -Include *.txt` Every file's structure is same only key information is different. Example User: Somerandomname Computer: Somerandomcomputer With `-Replace` command I remove "User:" and "Computer:" so `$User = Somerandomname` and `$computer = "Somerandomcomputer`. In each circle $user and $Computer with -Append should be written to one file. And then next file should be read. ``` foreach-object { $file = $_.fullname; ``` should be used, but I can not figure out the right syntax for it. Could someone help me with it?