2

I have a requirement like:

Have a text file containing the following in the following pattern

172.26.xxy.zxy:Administrator:Password
172.26.xxy.yyx:Administrator:Password
172.26.xxy.yyy:Administrator:Password
172.26.xxy.yxy:Administrator:Password

I need my powershell script to read each word and use that word whereever required. For example,

foreach(something)
{
 I want the IP's(172.26.---.---) to read and store the value as a variable.
 I want to store the two words after **:** in seperate variables.
}

How can this be done? I know to read an entire file or get some specific string. But I need the same to be done on each line.Any help would be really appreciated.

3 Answers 3

3

Something like this? You can just split on the : and then store your variables based on the index

$contents = Get-Content C:\your\file.txt

foreach($line in $contents) {
  $s = $line -split ':'
  $ip = $s[0]
  $user = $s[1]
  $pass = $s[2]
  write-host $ip $user $pass
}

minor edit: "t" missing in content.

Sign up to request clarification or add additional context in comments.

6 Comments

can I use these IP values in another script that I invoke from this file? basically I will be connecting to each IP one by one and I need this IP to use there. Can this be done?
Yes, you just need the script to accept arguments and then call it from within the loop.
Thanks, how can I use the username and password as credentials. I tried $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $uname,$pass but error is new-object : Cannot find an overload for "PSCredential" and the argument count: "2". Can you help me on this?
You need to ask a new question as this is a separate issue.
No, ask a new question. You're having a different issue to the one you originally asked about
|
0

You can write a regular expression to replace to remove the parts you do not need

$ip_address= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$1'
$user= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$2'
$pwd= '172.26.xxy.zxy:Administrator:Password' -replace '^(.+):(.+):(.+)$','$3'

Comments

0

I think the more generic and pure Powershell way would be something like this:

Select-String "(.*):(.*):(.*)" c:\file.txt |
 Select @{Name="IP"; Expression = {$_.Matches.Groups[1]}},
  @{Name="User"; Expression = {$_.Matches.Groups[2]}},
  @{Name="Password"; Expression = {$_.Matches.Groups[3]}}

The Output would be then an array of objects each having three properties IP, User and Password. So you can now use them for your purposes, or just add more commands at the end of the pipe.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.