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?
I usually use a format string for such tasks. All you need to do is to replace $completeName
with {0}
and you can format the string any time:
$controllerContent = @"
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Controller
@EnableWebMvc
public class {0} {{
}}
"@
Now you can rename the class using:
$controllerContent -f 'MyController'
Note: The only downsite to this is, that you need to escape the curly brackets as shown in my example. So its your choice whether you use a format string or -replace
.