Powershell Foreach-Object Foreach loop reads a line from several files and writes to one

I'm having trouble using multiple commands in the same Foreach or Foreach-Object loop

My situation is

  • I have many text files, about 100. Therefore they are read Get-ChildItem $FilePath -Include *.txt
  • Each file structure is the same, only key information is different. Example

    User: Somerandomname

    Computer: Somerandomcomputer

With the -Replace command -Replace I delete "User:" and "Computer:" so $User = Somerandomname and $computer = "Somerandomcomputer . In each circle, $ user and $ Computer with -Append must be written to one file. And then the next file should to be read.

 foreach-object { $file = $_.fullname; 

but I cannot determine the correct syntax for it. Can anyone help me with this?

+4
source share
3 answers

Assuming you have defined $ FilePath, $ user and / or a 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 distinguish between additional commands inside the Foreach-Object , for example, if you want to have separate commands for your username and computer. If you do not attach the Get-Content cmdlet with a parenthesis, you will receive an error message because this process will still have the $ file when Set-Content tries to use it.

Also note that using Powershell, double-quoted strings will evaluate variables, so you can put $ user in a string to do something like "User: $user" if you wish.

+5
source

Try the following:

 gci $FilePath -Include *.txt | % { gc $_.FullName | ? { $_ -match '^(?:User|Computer): (.*)' } | % { $matches[1] } } | Out-File 'C:\path\to\output.txt' 
0
source

If User and Computer are on separate lines, you need to read the lines two at a time. The ReadCount Get-Content parameter allows you to do this.

 Get-ChildItem $FilePath -Include *.txt ` | Get-Content -ReadCount 2 ` | %{ $user = $_[0] -replace '^User: ', ''; $computer = $_[1] -replace '^Computer: ', ''; "$user $computer" } ` | Out-File outputfile.txt 

This makes the assumption that each file contains only exact-form lines.

 User: someuser Computer: somecomputer User: someotheruser Computer: someothercomputer ... 

If this is not the case, you need to specify which file format.

0
source

Source: https://habr.com/ru/post/1496826/


All Articles