Here-Strings - How to Extrapolate variables names and keeping format

I have a string in a script that I would like to have two types of things with them . The here-string in my code block is quite long so I will use another smaller example to highlight my question.

So here is the here-string example -

$computername = 'server1'

$herestring = @"
   $variable1 = get-wmiobject -computername $computername -classname win32_services
"@

This here-string will be outputted to a file using out-file.

So what I would like is to have in the text file:

 $variable1 = get-wmiobject -computername server1 -classname win32_services

instead what I get is:

 = get-wmiobject -computername server1 -classname win32_services

In my here-string its more fully featured. In the function I have created it will out-file the file. Copy that to the remote machine location. And then register a scheduled task to run it to evaluate an activity on that machine I am running.

Is there a way to do what i want to do what I want to do in the here-string…or based on my current example is there a better way to perform that task?

Any help most appreciated.

If you use double quotes the variables in your here string will be replaced by their “content”. If you don’t have content yet it’s empty. If you don’t like the variables to be “replaced” you will have to escape the dollar sign with a backtick.

$computername = ‘server1’

$herestring = @"
`$variable1 = get-wmiobject -computername $computername -classname win32_services
"@