Forum Discussion
John_Dodo
Oct 26, 2022Brass Contributor
Powershell : interprete string as variable name
Hello,
I want to importe values from a csv file. Some column have this sort of values : $myvar.
So it would be like this :
log_message;server;scriptfolder;scriptname;action
blabla;myserver;$scriptfolder;$scriptname;letsdance
Now let say I want to do something like this :
$scriptname = script.ps1
$references = import-csv .\mycsv -delimiter ";"
foreach ($ref in $references){
write-host "$($ref.log_message) - $($ref.scriptname)
}
If I run something like this I get :
blabla - $scriptname
Is it possible to ask powershell to interprete the value of $scriptname instead of sending the string value $scriptname ?
I tried
get-variable($reference.scriptname)
but I get this
get-variable : Cannot find a variable with the name '$scriptname'.
though
write-host $scriptname
script.ps1
Thank you.
- LainRobertsonSilver Contributor
There's a number of ways to do this - none of them particularly pretty.
I've gone with a basic example that makes use of Invoke-Expression:
Get-Content -Path D:\Data\Temp\forum.csv | ForEach-Object { if (-not $Header -and -not [string]::IsNullOrWhiteSpace($_)) { $Header = $_.Split(';'); } elseif ($Header) { ConvertFrom-Csv -InputObject (Invoke-Expression -Command "`"$_`"") -Delimiter ';' -Header $Header; } }
Here's what the example looks like in action.
Cheers,
Lain