exclbr5
exclbr5

Reputation: 35

How to pass string from text file to another template file using powershell?

Let say I have text file contains the following strings.

user1
user2
user3
user4

How do I pass all those data to another template file contains the following ..

UserCreate 'string here' /GROUP:none /REALNAME:none /NOTE:none
UserNTLMSet 'string here' /ALIAS:none

So at the end it will produce output like this

UserCreate user1 /GROUP:none /REALNAME:none /NOTE:none
UserNTLMSet user1 /ALIAS:none
UserCreate user2 /GROUP:none /REALNAME:none /NOTE:none
UserNTLMSet user2 /ALIAS:none
.....................

Thank you in advance!!

Upvotes: 0

Views: 501

Answers (2)

Theo
Theo

Reputation: 61068

Really easy:

# create the template as Here-String
$template = @"
UserCreate {0} /GROUP:none /REALNAME:none /NOTE:none
UserNTLMSet {0} /ALIAS:none
"@

# read the text file as string array
Get-Content -Path 'D:\TheUsersFile.txt' | ForEach-Object {
    $template -f $_
}

Output:

UserCreate user1 /GROUP:none /REALNAME:none /NOTE:none
UserNTLMSet user1 /ALIAS:none
UserCreate user2 /GROUP:none /REALNAME:none /NOTE:none
UserNTLMSet user2 /ALIAS:none
UserCreate user3 /GROUP:none /REALNAME:none /NOTE:none
UserNTLMSet user3 /ALIAS:none
UserCreate user4 /GROUP:none /REALNAME:none /NOTE:none
UserNTLMSet user4 /ALIAS:none

The -f Format operator replaces all numbered placeholders in a string like {0} with the value(s) on the right-hand side. You can have more than one placehlder of course. For instance

"This {0} gets filled in with your name: {1}" -f 'string', $env:USERNAME

Upvotes: 1

Ivan Mirchev
Ivan Mirchev

Reputation: 839

You may try the following:

foreach ($user in (Get-Content -Path C:\TEMP\users.txt)){
    UserCreate 'string here' /GROUP:none /REALNAME:none /NOTE:none
    UserNTLMSet 'string here' /ALIAS:none
}

Upvotes: 1

Related Questions