Jump to content

Recommended Posts

Posted

Hi,

 

I have the following script:

 

$Basename = gci c:\Tools\reg | % {$_.BaseName}
#$Output = Set-Content -Value $Basename -Path C:\Tools\Powershell\Output.txt

(Get-Content C:\Tools\Powershell\file.txt) | 
   Foreach-Object {
       $_ # send the current line to output
       if ($_ -match "Insert") 
       {
           #Add Lines after the selected pattern 
           "$Basename"
       }
   } | Set-Content C:\Tools\Powershell\file.txt

 

The idea behind this is to basically get the filenames, minus the extension, of a folder's contents (c:\Tools\reg) and then add these names as separate lines to the file file.txt at a specific location matching the term "Insert"

 

This is working but it adds all the names on a single line at the specified location rather than on their own line. My understanding is that this is because this stored as an array? Also if run multiple times it'll append another line rather than replacing the existing one which I though was the point of Set-Content over Add-Content!?

 

As usual, any help greatly appreciated.

Posted

It would be helpful if you posted the files, Output.txt and file.txt then one could test it. Lacking that, I've not even tried to run the following code.

 

I think you may just need to add something to track matched instances and increment array pointer so :

 

$Basename = gci c:\Tools\reg | % {$_.BaseName}
#$Output = Set-Content -Value $Basename -Path C:\Tools\Powershell\Output.txt
iIdx = 1

(Get-Content C:\Tools\Powershell\file.txt) | 
   Foreach-Object {
       $_ # send the current line to output
       if ($_ -match "Insert") 
       {
           #Add Lines after the selected pattern 
           "$Basename[iIdx]"
           iIdx++
       }
   } | Set-Content C:\Tools\Powershell\file.txt


Posted

It was simply a folder that had any number of files present and the text file simply has a load of jibba-jabba in it but with the term "Insert" present in the middle of it for testing.

 

I've been having a further play and the following works:

 

$Basenames = gci c:\Tools\reg | % {$_.BaseName}
#$Output = Set-Content -Value $Basenames -Path C:\Tools\Powershell\Output.txt
foreach ($Basename in $Basenames)
{
$file = $Basename
   
   (Get-Content C:\Tools\Powershell\file.txt) | 
   Foreach-Object {
       $_ # send the current line to output
       if ($_ -match "Insert") 
       {
           #Add Lines after the selected pattern 
           "$file"
       }
   } | Set-Content C:\Tools\Powershell\file.txt
}

 

Now I simply need to remove the content from the file.txt if it already exists so it's not appended multiple times

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...