Bart Coninckx
Bart Coninckx

Reputation: 11

Extract a column from a variable in PowerShell

I put the output from a command in a variable in PowerShell. Its content looks like this:

 5 Reallocated_Sector_Ct   0x0033   100   100   010    Pre-fail  Always       -       0

I would like to extract any of the columns and put that in a new variable. I've found ways to that with text files but not with variables. Thanks for your suggestions!

BC

Upvotes: 0

Views: 435

Answers (1)

mklement0
mklement0

Reputation: 440347

I would like to extract any of the columns and put that in a new variable.

The simplest solution is to extract all whitespace-separated tokens from your variable value and store them in an array, using the unary form of the -split operator; you can then use indexing to retrieve a token of interest, such as [0] to get the first one:

$var = '5 Reallocated_Sector_Ct   0x0033   100   100   010    Pre-fail  Always       -'

# Split the string into tokens by any run of whitespace
# (ignoring leading and trailing whitespace, which aren't present here).
$tokens = -split $var

# Extract the 2nd token, for instance.
# To assign it to a separate variable, use something like:
#   $secondToken = $tokens[1]
$tokens[1] # -> 'Reallocated_Sector_Ct'

Upvotes: 2

Related Questions