0
votes

I'm using a text file with a list of file and folder paths that I'd like to copy to some $destination. I'm trying to get powershell to interpret each line as a file path for copy-item. Here's what I'm working with:

$cfglist = Get-Content "${cfgPath}\ProgramConfigsList.txt"
    Foreach($item in $cfglist){
    #Copy-Item -Path $item -Destination $dst -Force -Recurse -Container:$true -Passthru -Whatif
}

ProgramConfigsList.txt looks like this:

"$env:programfiles\Tracker Software\PDF Editor\Dictionaries"
"${env:ProgramFiles(x86)}\Notepad++\plugins"
"$env:userprofile\AppData\Local\ATI"

and so on.

I get this error: Copy-Item : Cannot find drive. A drive with the name '"$env' does not exist.

Within the text file, I've tried using quotes, not using quotes, and de-commenting ":" with `. Within the PS script, I've $item, "$item", "${item}", and ${item}. I've also tried piping the $cfglist variable to a foreach-object script block with the same copy-item command. I've tried using variations of 'get-childitem', but that doesn't seem to work with entries inside a text file that need to be interpreted as file/folder paths. I also created an array from the entries within ProgramConfigsList.txt inside the ps1 script, but that ran into the same error.

Any suggestions?

2
You can pass each string object to Invoke-Expression and it will expand the string to the path. You better be sure with no doubts that the file will not be tampered with as anyone who can edit it can run PowerShell on your system.Persistent13
The command would be: Get-Content "${cfgPath}\ProgramConfigsList.txt" | ForEach-Object { Invoke-Expression $_ }Persistent13
While that will work in this instance, I would recommend not (ab)using Invoke-Expression for string expansion alone. What if someone puts something nasty in the file your reading? :-|Mathias R. Jessen
Never forget little Bobby Tables...xkcd.com/327EBGreen
I would recommend using %environmentvariablename% syntax in your input file; then you can simply use [Environment]::ExpandEnvironmentVariables in PowerShell and be done with it.Bill_Stewart

2 Answers

2
votes

You'll need to remove the containing quotes and then manually expand the variables:

$cfglist = Get-Content "${cfgPath}\ProgramConfigsList.txt" |ForEach-Object {
    $ExecutionContext.InvokeCommand.ExpandString($_.Trim("`"'"))
}
0
votes

Alternatively: Use %variablename% syntax in your input file and use the [Environment]::ExpandEnvironmentVariables static method. Example:

Get-Content "$cfgPath\ProgramConfigsList.txt" | ForEach-Object {
  [Environment]::ExpandEnvironmentVariables($_)
}