Written by 6:49 pm Microsoft, PowerShell • 19 Comments

Powershell: Convert String to Scriptblock

If you use PowerShell remoting in some scripts, you will ses you cannot use a string to send it with the Invoke-Command cmdlet.

So you can simple convert a String to a Scriptblock

 $scriptBlock = [Scriptblock]::Create($string)

Now here an example

$remoteCommand =
@"
Import-Module ActiveDirectory
New-ADOrganizationalUnit -name
"@
 
$scriptBlock = [Scriptblock]::Create($remoteCommand)
 
Invoke-Command -ComputerName AD01 -ScriptBlock $scriptBlock

Basically you could create a function for that.

function ConvertTo-Scriptblock {
<# Function to Convert a String into a Script Block #>
Param(
[Parameter(
Mandatory = $true,
ParameterSetName = '',
ValueFromPipeline = $true)]
[string]$string
)
$scriptBlock = [scriptblock]::Create($string)
return $scriptBlock
}

Tags: , , , , , , , Last modified: January 7, 2019
Close Search Window
Close