0

I have a file (config.cfg) which has three strings like this: host:user:pass

In my Unix code, I do this to get and assign the value into three different variables:

  $FTP_HOST=$( cut -f1 -d: config.cfg )
  $FTP_USER=$( cut -f2 -d: config.cfg )
  $FTP_PASS=$( cut -f3 -d: config.cfg )

How can I do this in PowerShell 3.0? I have tried with Foreach-Object but couldn't find a way to assign into three variables.

2 Answers 2

2

PowerShell learned from Perl and Python, so you can do this:

$FTP_HOST, $FTP_USER, $FTP_PASS = (Get-Content .\config.cfg) -split ':'
Sign up to request clarification or add additional context in comments.

1 Comment

Great! I do prefer single-line stuff. Thank you!
1

You can split the data by colon and assign each element:

$config = Get-Content config.cfg
$FTP_HOST = ($config -split ":")[0]
$FTP_USER = ($config -split ":")[1]
$FTP_PASS = ($config -split ":")[2]

Or pre-split the data into an array and then assign the array elements:

$config = Get-Content config.cfg
$carry = $config -split ":"
$FTP_HOST = $carry[0]
#etc...

1 Comment

Works nice and smooth. Thank you!

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.