PowerShell Tip – Convert Script Block to string or string to Script Block


It is very simple. You just need to create a new instance of System.Management.Automation.ScriptBlock and use Create() method.

PowerShell code

$scriptBlock1 =
{
    Get-ChildItem
}

Write-Verbose -Message $scriptBlock1.GetType().FullName -Verbose

$scriptBlockString = $scriptBlock.ToString()

Write-Verbose -Message $scriptBlockString.GetType().FullName -Verbose

$scriptBlock2 = [ScriptBlock]::Create($scriptBlockString)

Write-Verbose -Message $scriptBlock2.GetType().FullName -Verbose

# Execute
& $scriptBlock2

Output

VERBOSE: System.Management.Automation.ScriptBlock
VERBOSE: System.String
VERBOSE: System.Management.Automation.ScriptBlock

Leave a Reply

Your email address will not be published. Required fields are marked *

Active Directory Advanced function AlwaysOn Availability Groups AlwaysOn Failover Cluster Instances Building Cloud Cloud Cluster Cmdlet Database Deployment Design DFS Domain Controller DSC Fabric Failover Clustering File Server Group Policy Hardware Profile Host Hyper-V Installation Library Library Asset Library Server Network Operations Manager Orchestrator PowerShell PowerShell User Group PowerShell Workflow Security Service Manager SQL Server Storage System Center Template Time Time Synchronization Tips Virtual Machine Virtual Machine Manager VM Network VM Template Windows Server 2012 R2