I'm a bit stuck trying to use param values in a string, imported from within a CSV.
I've tried a few methods, and can't seem to enumerate the parameter within the string.
First of all I have a csv text file:
Name,Value
XcomEnemyWithin,C:\Users\karee\OneDrive\Documents\my games\XCOM - Enemy Within
Valheim,C:\Users\${env:UserName}\AppData\LocalLow\IronGate\Valheim
And I have a script that runs to import this CSV and backup the dir:
$backup_list = Import-Csv C:\backup_list.txt | Sort-Object -Property Name
foreach ($backup_job in $backup_list.GetEnumerator()) {
$this_job_name = $($backup_job.Name)
$this_job_dir = $($backup_job.Value)
Copy-Item -Path "$this_job_dir\" -Destination "C:\mybackups\$this_job_name" -Force -Recurse
}
The first job runs fine but the second job fails every time because the "Value" string used for the directory path, includes the "${env:UserName}" value within the string, but I am struggling with how I can enumerate that value for use with "Copy-Item".
Is there somewhere I can enumerate this string in this workflow that makes sense?
Thanks.
Edit: apparently this question has been flagged as duplicate, but I searched for a long time (nearly an hour) for a solution, apparently the solution answer is "Evaluate a string" which completely honestly is not something that comes up in searching unless you know exactly what you're looking for, and if you know what you're looking for, I think you're likely not searching for it. In my opinion, my question is valid and in good faith that I genuinely searched for nearly an hour but did not search for "evaluate" or "expand". I hope my question would help people who may not be fully-experienced developers. Thanks.
To expand a variable inside a string, you can use the $ExecutionContext.InvokeCommand.ExpandString()
method.
In your case, read the destination path as
$this_job_dir = $ExecutionContext.InvokeCommand.ExpandString($backup_job.Value)