Oct 26 2022 05:29 AM
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.
Oct 26 2022 04:54 PM
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