PowerTip: Create a PowerShell Script Block on the Fly

PowerTip: Create a PowerShell Script Block on the Fly

  • Comments 1
  • 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