How to run string block as powershell code

I have some code within string block (see below)

$string = @'
$processes= get-process
$store = get-services
'@

When I run this this script block above as a code, I should be able to use variables $processes & $store later in a script.

Anyone knows how to accomplish this?

First, Get-Services is not a valid cmdlet. Second, you don’t have a scriptblock, you have a here-string. A scriptblock would look like this

$string = {
$processes= get-process
$store = get-service
}

However you can turn the here-string into a scriptblock like this.

$script = [scriptblock]::Create($string)

Once it’s a scriptblock, either the example I gave or the created $script, you can run it like this.

. $string

You could also use & to run the scriptblock but if you do actually want the variables $processes and $store to exist in the calling session you use the period. It’s essentially dot sourcing it, pulling it into the current session while executing it.

Hey Doug. Thank you for your reply.

I mentioned string block not scriptblock :slight_smile: and this is just an example of code, not a real one.

Just to mention, that $string in my example will change during the script execution (I may add another string) and then executed at the end of the script. That is why I need ‘string block’ or whatever it is called.

I tried what you provided but nothing is happening and not sure if that solution works in my situation.

Converting the string text to scriptblock is the best way to do it. Otherwise you will have to Use Invoke-Expression which is not recommended much.
You can literally converting any string to script block to invoke it using $scriptBlock.Invoke($Parameter). You can pass parameters too.

I’m not one to argue, so I’ll stick to the facts.

Fact 1. Your mention string in your title and initially in your post but you literally say “script block” as quoted below. I wanted to make sure you understood it’s not a scriptblock as you show it.

Fact 2. Taking your here-string and running it as suggested does exactly what you said you were trying to do as shown in this screenshot.

screenshot

What do you mean by nothing is happening? What are you expecting to happen?

Oh, it was a typo. Tested it again and it works great. I was testing the same before I posted it here but I didn’t know about the ‘.’ :). Perfect and thank you Doug for your help.

Thank you kvprasoon for your reply as well.