Read value of variable in CSV file that is be initialized in powershell script

How can i read value of variable in CSV file, which is initialized in my script.

My config.csv file:

FileName|Path
test.properties|.\Folder$custom

and Powershell script: test.ps1

$custom = “MA”

Import-Csv “C:\Users\MA\Desktop\config.csv” -delimiter “|” | ForEach-Object {
$fileName = $.FileName
$path = $
.Path
$relativeFilePath = Join-Path $path $fileName

}

$filePath = $relativeFilePath
$pathNew = “C:\Users\MA\Desktop”

$pathNewFile = (Resolve-Path (Join-Path $pathNew $filePath)).Path

After i run this code i get:

“C:\Users\MA\Desktop\Folder$custom\test.properties”

but i want get: “C:\Users\MA\Desktop\Folder\MA\test.properties”

 

You’re not going to be able to use it the way you’re trying. The best I can come up with at the moment is use a string and then Get-Variable to extract the value.

$csv = @'
FileName|Path
test.properties|custom
'@ | ConvertFrom-Csv -Delimiter '|'

$custom = 'MA'

$csv | ForEach-Object {
    $fileName = $_.FileName
    $path = (get-variable $_.path).value
    $relativeFilePath = Join-Path $path $fileName
}

$filePath = $relativeFilePath
$pathNew = "C:\Users\MA\Desktop"

$pathNewFile = (Resolve-Path (Join-Path $pathNew $filePath)).Path

OK here’s another way. You can use a hashtable to store/retrieve the value

$csv = @'
FileName|Path
test.properties|$custom
'@ | ConvertFrom-Csv -Delimiter '|'

$ht = @{
    '$custom' = 'MA'
}

$csv | ForEach-Object {
    $fileName = $_.FileName
    $path = $ht[$_.path]
    $relativeFilePath = Join-Path $path $fileName
}

$filePath = $relativeFilePath
$pathNew = "C:\Users\MA\Desktop"

$pathNewFile = (Resolve-Path (Join-Path $pathNew $filePath)).Path

Thanks alot, but i must have separated config.csv file.

Yeah? Nothing here says you can’t. I was just using that as an example…

Here’s the csv file…

$csvfile = New-TemporaryFile

@'
FileName|Path
test.properties|custom
'@ | Set-Content $csvfile -Encoding UTF8

And either of the methods shown work the same way…

$custom = 'MA'
 
Import-Csv $csvfile -Delimiter '|' | ForEach-Object {
    $fileName = $_.FileName
    $path = (get-variable $_.path).value
    $relativeFilePath = Join-Path $path $fileName
}
 
$filePath = $relativeFilePath
$pathNew = "C:\Users\MA\Desktop"
 
$pathNewFile = (Resolve-Path (Join-Path $pathNew $filePath)).Path

or

$ht = @{
    '$custom' = 'MA'
}

Import-Csv $csvfile -Delimiter '|' | ForEach-Object {
    $fileName = $_.FileName
    $path = $ht[$_.path]
    $relativeFilePath = Join-Path $path $fileName
}

$filePath = $relativeFilePath
$pathNew = "C:\Users\MA\Desktop"

$pathNewFile = (Resolve-Path (Join-Path $pathNew $filePath)).Path

Thanks alot. It works very well.