简体   繁体   中英

Assign value from filename and content of file to a template using Powershell

In my directory path\, I have many text files with name something like this

area1.txt
area2.txt
area3.txt

Each file contains lots of one liner string that looks like this

user1
user2
user3

How do I write a Powershell script to pass all of the filename and content of file to a template so it will look like this for every iteration or combining all result in single file.

area "filename"
user "user1"
realname "user1"

Managed to write a script but it does not produce the desired outcome. Somehow it only produce last value of filename in loop and empty string after user and realname template.

foreach($file in Get-ChildItem path\ -Filter *.txt){
$result = @"
area $($file.BaseName)
area {0} 
realname {0} 
"@
}

foreach($file in Get-ChildItem path\ -Filter *.txt){
    foreach ($line in $file |Get-Content){
        $result -f $_
    }
  }

Need your help to point out the error in my script and help me to fix it. I really appreciate it if anyone can help.

You only need a single set of (nested) loops for this, then reference $line and $file appropriately inside the inner loop:

foreach($file in Get-ChildItem path\ -Filter *.txt){
    foreach ($line in $file |Get-Content){
        @"
area {1}
user {0} 
realname {0}
"@ -f $line,$file.BaseName
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM