PowerTip: Create a PowerShell Script Block on the Fly

PowerTip: Create a PowerShell Script Block on the Fly

  • Comments 3
  • Likes

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..

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Or just use a scriptblock ;-)

    {"This is a string"} | gm

  • @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"

  • @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