Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reevalute here strings after I declare them?

I'm trying to use PowerShell for a small code generation task. I want the script to generate some java classes and interfaces.

In the script I want to declare a here string variable. For example:

$controllerContent = @"
package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Controller
@EnableWebMvc
public class $completeName {

}
"@

After the declaration I want to pass it to function where I calculate the variable $completeName. But I don't what is the proper way to replace the variable in my string. Do I have to use -replace? Or is there some other way?

like image 504
Patrick Avatar asked Feb 07 '23 04:02

Patrick


1 Answers

I usually use a format-string like the answer above, but you could also wrap it in scriptblock and invoke when needed. That wouldn't require any modification to he text itself. Ex:

$completeName = "HelloWorld"

$controllerContent = { @"
@Controller
@EnableWebMvc
public class $completeName {

}
"@ }

& $controllerContent
#Save the string:  $str = & $controlledContent

Output:

@Controller
@EnableWebMvc
public class HelloWorld {

}

Change the variable:

$completeName = "HelloNorway"

& $controllerContent

Output:

@Controller
@EnableWebMvc
public class HelloNorway {

}
like image 165
Frode F. Avatar answered Feb 23 '23 03:02

Frode F.