0

I have a CSV file that contains lines like this:

"Title","Path"
"News","/somepath/news.json/$variable1$variable2"
"Boards","/somepath/$year/$variable3/boardfile.json"

I set all these variables in the script and then import data using Import-Csv cmdlet. As a result, I get object with Title and Path properties and that's what I need. But the problem is that the variables in the CSV file are not getting replaced with actual values during import. I know there is a solution with Get-Content and ExpandVariable, but it produces an array of strings, and I would rather have an object (or maybe a hashtable?) with properties similar to what Import-Csv produces. Is there a way to replace variables with values while still using Import-Csv and get a full-featured object as a result?

1 Answer 1

1

Import-Csv doesn't expand variables in imported data, so the values in your CSV behave as if they were in single quoted strings. You need something like this to get the variables expanded after import:

Import-Csv 'C:\path\to\your.csv' | Select-Object Title,
    @{n='Path';e={$ExecutionContext.InvokeCommand.ExpandString($_.Path)}}
Sign up to request clarification or add additional context in comments.

5 Comments

Could you please explain what's being done in this part? @{n='Name';e={$ExecutionContext.InvokeCommand.ExpandString($_.Path)}}
Why can't we just use ForEach-Object, perform ExpandString($_.Path) on each record and assign new values back?
I didn't say you can't. The above is just one (and IMO in this case more convenient) way to achieve what you want.
Calculated property really solves my task. 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.