Rakab Aman
Rakab Aman

Reputation: 1

Expanding Environmental Variable using CSV file into Powershell script

i am trying to create a backup script with csv file which will contain all the local (where backup will be stored) and backup (folder to backup) loaction and run robocopy to copy files from backup to local folder. i want to import environmental variable from csv file that are used for default folders (e.g. env:APPDATA) as location to be use for backing up some files and folders in user documents or pulbic documents. When i use the env variable directly or use full path address in the script the copy action works fine.

robocopy "&env:localappdata\steam" "$backup" 

but when import from csv, the script does not see it as env variable. robocopy shows the error because it picks up the locations like this

 Source : C:\WINDOWS\system32\$env:LOCALAPPDATA\steam\
     Dest : D:\backup\steam\

Below is the full code i am using.

$path = "$PSScriptRoot\backup\"
$locations = import-csv "$PSScriptRoot\backup\local.csv" -Delimiter "," -Header 'Local','Backup','Display' | Select-Object Local,Backup,display

foreach($location in $locations){
 
    $source = $location.Local
    $source = $source.ToString()

    $destination = $location.Backup
    $destination = $destination.tostring()
   
   
    $Name = $location.Display
    $Name = $name.tostring()

    Write-host "Copying $Name, please wait...." -foregroundColor Yellow
    robocopy "$destination" "$path$source" \s \e
}

And my CSV file looks like this

Steam, $env:LOCALAPPDATA\steam, Steam files Backup

Upvotes: 0

Views: 904

Answers (1)

Theo
Theo

Reputation: 61028

As you have added a path in the csv as $env:LOCALAPPDATA\steam, and knowing that whatever you read from file using Import-Csv is a string, you need to use regex to convert the $env:VARNAME into %VARNAME% in order to be able to resolve that environment variable into a path.

Instead of

$source = $source.ToString()

do this

$source = [Environment]::ExpandEnvironmentVariables(($source -replace '\$env:(\w+)', '%$1%'))

$source wil now have a valid path like C:\Users\Aman\AppData\Local\Steam

Do the same with $destination

Regex details:

\$             Match the character “$” literally
env:           Match the characters “env:” literally
(              Match the regular expression below and capture its match into backreference number 1
   \w          Match a single character that is a “word character” (letters, digits, etc.)
      +        Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)

P.S. Instead of combining a path with string concatenation like you do in "$path$source", it is much safer to use the Join-Path cmdlet for that

Upvotes: 0

Related Questions