PowerTip: Create a PowerShell Script Block on the Fly

Summary: Create a Windows PowerShell script block on the fly.

Hey, Scripting Guy! Question How can I convert a string into a Windows PowerShell script block?

Hey, Scripting Guy! Answer Use the static Create method from the [scriptblock] class:

PS C:> [scriptblock]::Create(“this is a string”) | gm

   TypeName: System.Management.Automation.ScriptBlock


Name                    MemberType Definition

—-                    ———- ———-

CheckRestrictedLanguage Method     void CheckRestrictedLanguage(System.Collection..

Equals                  Method     bool Equals(System.Object obj)

GetHashCode             Method     int GetHashCode()

GetNewClosure           Method     scriptblock GetNewClosure()

GetObjectData           Method     void GetObjectData(System.Runtime.Serializatio..

GetPowerShell           Method     powershell GetPowerShell(Params System.Object[..

GetSteppablePipeline    Method     System.Management.Automation.SteppablePipeline..

GetType                 Method     type GetType()

Invoke                  Method     System.Collections.ObjectModel.Collection[psob..

InvokeReturnAsIs        Method     System.Object InvokeReturnAsIs(Params System.O..

ToString                Method     string ToString()

Ast                     Property   System.Management.Automation.Language.Ast Ast ..

Attributes              Property   System.Collections.Generic.List[System.Attribu..

File                    Property   string File {get;}

IsFilter                Property   bool IsFilter {get;set;}

Module                  Property   psmoduleinfo Module {get;}

StartPosition           Property   System.Management.Automation.PSToken StartPosi..

Comments (3)

  1. Or just use a scriptblock 😉

    {"This is a string"} | gm

  2. Dave E says:

    @Stefan Stranger

    Late reply… but just in case anyone else comes across this…

    [ScriptBlock]::Create("This is a string") is the same as
    { This is a string }

    {"This is a string"} is the same as, well, {"This is a string"}.

    They’re totally different things. One is a script block whose script is This is a string, the other is a script block
    whose script is "This is a string", i.e., the first isn’t going to be valid PowerShell in this example case, whereas the second is; it’s a script that simply returns the string "This is a string"

  3. Carlos Nunez says:

    @Stefan: Using ScriptBlock.Create is better for when you need to expand variables in a scriptblock that’s being remoted somewhere using something like Invoke-Command