<meta property="og:description" content="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 = ::Create($string) Now here an example$remoteCommand =@'Import-Module ActiveDirectoryNew-ADOrganizationalUnit -name'@$scriptBlock = ::Create($remoteCommand)Invoke-Command -ComputerName AD01 -ScriptBlock $scriptBlockBasically you could create a function for that.function ConvertTo-Scriptblock {Param($string)$scriptBlock = ::Create($string)return $scriptBlock}"> <meta name="twitter:description" content="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 = ::Create($string) Now here an example$remoteCommand =@'Import-Module ActiveDirectoryNew-ADOrganizationalUnit -name'@$scriptBlock = ::Create($remoteCommand)Invoke-Command -ComputerName AD01 -ScriptBlock $scriptBlockBasically you could create a function for that.function ConvertTo-Scriptblock {Param($string)$scriptBlock = ::Create($string)return $scriptBlock}"> Powershell: Convert String to Scriptblock - Thomas Maurer

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 {
&lt;# Function to Convert a String into a Script Block #&gt;
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