user17033631
user17033631

Reputation:

How to get 2 variables from a file PowerShell

I'm trying to make an script that take numbers from a file and then do some maths with them, but I don't know how to take from a single line 2 variables. The file it must be something like this:

3 5

What I need is that one variable is for example $a be 3 and other $b be 5

$a=3
$b=5 

The problem is that I found this

$Contents = Get-Content ".\file.txt"

$a = $Contents[0] -split(" ")[1]
$b = $Contents[1] -split(" ")[1]

but it doesen´t work with the second number, how can I do this?

Upvotes: 0

Views: 303

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174545

To refer to the first line in the file, you want $Contents[0] ($Contents[1] would refer to the second line).

$a,$b = -split $Contents[0] -as [int[]]

Using -split in unary mode will make PowerShell split on any sequence of consecutive whitespace characters, and throw away any empty parts (this way it works when the iput has leading or trailing whitespace, like " 3 5 ").

The -as [int[]] operation will force PowerShell to attempt to convert the resulting string values to [int] values, so now you can meaningfully do integer arithmetic with them:

PS ~> $a + $b
8

Upvotes: 1

Related Questions