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 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 {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With