Trey Nuckolls
Trey Nuckolls

Reputation: 591

Dynamic replacement of strings from import-csv

I have a csv file that contains fields with values that begin with "$" that are representative of variables in different powershell scripts. I am attempting to import the csv and then replace the string version of the variable (ex. '$var1') with the actual variable in the script. I have been able to isolate the appropriate strings from the input but I'm having difficulty turning the corner on modifying the value.

Example:

CSV input file -

In Server,Out Server
\\$var1\in_Company1,\\$var2\in_Company1
\\$var1\in_Company2,\\$var2\in_Company2

Script (so far) -

$Import=import-csv "C:\temp\test1.csv"
$Var1="\\server1"
$Var2="\\server2"
$matchstring="(?=\$)(.*?)(?=\\)"
$Import| %{$_ | gm -MemberType NoteProperty | 
%{[regex]::matches($Import.$($_.name),"$matchstring")[0].value}}

Any thoughts as to how to accomplish this?

Upvotes: 0

Views: 709

Answers (2)

Matt
Matt

Reputation: 46710

The simplest way to address this that I could think of was with variable expansion as supposed to replacement. You have the variables set in the CSV so lets just expand them to their respective values in the script.

#  If you dont have PowerShell 3.0 -raw will not work use this instead
#  $Import=Get-Content $path | Out-String

$path = "C:\temp\test1.csv"
$Import = Get-Content $path -Raw
$Var1="\\server1"
$Var2="\\server2"
$ExecutionContext.InvokeCommand.ExpandString($Import) | Set-Content $path

This will net the following output in $path

In Server,Out Server
\\\\server1\in_Company1,\\\\server2\in_Company1
\\\\server1\in_Company2,\\\\server2\in_Company2

If the slashes are doubled up here and you do not want them to be then just change the respective variable values in your script of the data in the CSV.

Caveat

This has the potential to execute malicious code you did not mean too. Have a look at this thread for more on Expanding variables in file contents. If you are comfortable with the risks then this solution as presented should be fine.

Upvotes: 2

CB.
CB.

Reputation: 60918

Maybe I misunderstood, but do you need this?

$Import=import-csv "C:\temp\test1.cvs"
$Var1="\\server1"
$Var2="\\server2" 

Foreach ($row in $Import )
{
    $row.'In Server' = ($row.'In Server' -replace '\\\\\$var1', "$var1")
    $row.'Out Server' = ($row.'Out Server' -replace '\\\\\$var2', "$var2")    
}

$import | set-content $path

Upvotes: 1

Related Questions