Strings and Scriptblocks

Hello again,

This will be another short article. I ran into an issue this week where I was trying to cast a string to a scriptblock and it absolutely wouldn’t work.  Looks like this is covered in a bunch of places, I’ve got one example here.

So without a lot of talking here’s how you do it:

You use the scriptblock class accelerator and the static method, create, to convert a string to a scriptblock.

Just a quick tip, don’t actually add the curly braces, {}, to your scriptblock.

[scriptblock]::Create(" Some arbitrary code, I can ever add a $Variable ")

I hope that’s useful to some people. Go ahead and ping me here or on twitter @rjasonmorgan if you have any questions.

A handy article on Scriptblocks in general courtesy of Rob Campbell, @Mjolinor

This entry was posted in PowerShell and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s