Home > Software design >  Selection of words from the object
Selection of words from the object

Time:05-24

I have a variable that contains the following values $a

$a
Server Work TS,,login,A ,,,0,,Aplus,Z%@#$!dasgktP#&^zES&M,
Server Work TS,,login,DAK,,,0,,DAK,c@!@%SDJgPrNA69%#$!#e53V6f,
Server Work TS,,login,DAS,,,0,,DAS,!@$dJGH4Q!DFE3jhhd,
Server Work TS,,login,DAS,,,0,,DAS,$@L1A0aR*G3FsAGGCCnc,
Server Work TS,,login,Avdeev,,,0,,AvdeevI,gd@%^%$YFASCNHhdgas8P,
Server Work TS,,login,Andriyshik,,,0,,AndriychukS,ASFHRT$5546fgsdjmbvn,

then I need to extract the login and password and create a user

I do it that way

$username1 = $a[1] -split ',' | Select -Last 3 | select -SkipLast 2
$password1 = $a[1] -split ',' | Select -Last 2 | select -SkipLast 1 | ConvertTo-SecureString -AsPlainText -Force

Then I create a user and add them to the appropriate groups

New-LocalUser $username1 -Password $password1 -AccountNeverExpires -PasswordNeverExpires -UserMayNotChangePassword
net localgroup "Remote Desktop Users" "$username1" /ADD
net localgroup "Users" "$username1" /ADD

Next, I repeat the above selection with each line of the variable "a"

Can I loop this command, which will automatically go through each line and do it with each user as many times as it says "($a).count"? Because the number of lines in the variable "$a" can vary

CodePudding user response:

I'd strongly suggest using the ConvertFrom-Csv cmdlet to parse the data for you:

$users = $a |ConvertFrom-CSV -Header A,B,C,D,E,F,G,H,Username,Password,K |Select-Object Username,Password

foreach($user in $users){
    New-LocalUser -Username $user.Username -Password ($user.Password |ConvertTo-SecureString -AsPlainText -Force) ...
}

CodePudding user response:

What you have in variable $a is a CSV without headers. and you can simply convert that if you provide headers to the ConvertFrom-Csv cmdlet:

$a |  ConvertFrom-Csv -Header 'Server','Empty1','Login','NoIdea','Empty2','Empty3','Digit','Empty4','UserName','PassWord','Empty5' | ForEach-Object {
    $pw = $_.Password | ConvertTo-SecureString -AsPlainText -Force
    New-LocalUser -Username $_.Username -Password $pw ...
}

CodePudding user response:

You can simply use a loop:

foreach($line in $a){
$username1 = $line -split ',' | Select -Last 3 | select -SkipLast 2
$password1 = $line -split ',' | Select -Last 2 | select -SkipLast 1 | ConvertTo-SecureString -AsPlainText -Force
New-LocalUser $username -Password $password -AccountNeverExpires -PasswordNeverExpires -UserMayNotChangePassword
net localgroup "Remote Desktop Users" "$username" /ADD
net localgroup "Users" "$username" /ADD
}
  • Related