Home > OS >  Parsing lines into a variable for later use
Parsing lines into a variable for later use

Time:12-22

I'm a newb w/ Powershell and I am trying to perform similar operations I did previously in bash in PS. I'm working w/ a "driver" file of 25 Snowflake accounts. Each line in the driver file holds key info about a Snowflake account, delimited by ',', w/ field 5 (or 4 starting from 0) being the account's URL.

My goal is to parse the file, grab field 5 and modify it a bit, storing all lines in a variable. The variable would be used dynamically for various ad-hoc duties.

I'm trying:

$ALLACCTS=(foreach ($LINE in Get-Content -Path "snowflake_acct_driver.txt" | Select-String -Pattern '^#' -notmatch) {((($LINE -split ',')[4]) -Replace 'https://', '') -Replace '\.snowflakecomputing\.com', ''})

and getting errors like:

At line:1 char:24 $STUFF=(foreach ($LINE in Get-Content -Path "$HHOME\data\snowflake_ac ... ...

The foreach command works fine on its own, without being part of a variable assignment and no surrounding parenthesis. Any clues what I'm doing wrong?

CodePudding user response:

Since you're using a foreach statement as part of a larger expression, replace (...) with $(...)

That is, instead of:

$ALLACCTS = (foreach ...) -replace ...

use:

$ALLACCTS = $(foreach ...) -replace ...

Perhaps surprisingly, language statements such as foreach, while, switch, do, and if:

See GitHub issue #6817 for a discussion.

  • Related