Reputation: 11
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
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