0

I am editing a function which it will invoke a command directly on the VM. The issue I keep running into is if someone passes a function declaration as a scriptblock, I get and error when calling create, because params() is not at the top of the scriptblock.

Trying to figure out how I can still set-fulllanguage first then execute a function with params.

function Invoke-DirectOnVM
{
    [CmdletBinding()]
    Param (
    [Parameter(Mandatory = $true)]
    [CloudEngine.Configurations.EceInterfaceParameters]
    $Parameters,

    [Parameter(Mandatory = $true)]
    [String[]]$VMNames,

    [Parameter(Mandatory = $true)]
    [Object]$VMCredential,

    [Parameter(Mandatory = $true)]
    [ScriptBlock]$ScriptBlock,

    [Object[]]$ArgumentList = $null
)
{
    Invoke-Command -VMName $localVMs -Credential $using:VMCredential -ScriptBlock ([ScriptBlock]::Create($("Import-Module OpenUpSession; Set-FullLanguage; `r`n" + $using:ScriptBlock)))
}
Saeed
  • 5,413
  • 3
  • 26
  • 40
Mark
  • 11
  • 1
  • 3
  • Don't force the scriptblock... `-ScriptBlock {Import-Module OpenUpSession; Set-FullLanguage; $using:ScriptBlock.Invoke($using:ArgumentList)}` – TheMadTechnician Apr 26 '18 at 16:33
  • Tried this out. Got the Error: + ... -FullLanguage; $using:scriptBlock.Invoke($using:argumentList)} -Argum ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Expression is not allowed in a Using expression. – Mark Apr 26 '18 at 19:33
  • You didn't use what I put, I can see `} -Argum` in your error, but that is not in either your code, or my code. Please make the code you post an accurate representation of the code you're working with. – TheMadTechnician Apr 26 '18 at 20:02
  • Fair enough. I removed the bit of code but the result is the same. Error seems to be with $using:ScriptBlock and .Invoke – Mark Apr 26 '18 at 20:10
  • That can be fixed... `-ScriptBlock {Param($ScriptBlock,$ArgumentList);Import-Module OpenUpSession; Set-FullLanguage; $ScriptBlock.Invoke($ArgumentList)} -ArgumentList $ScriptBlock, $ArgumentList` – TheMadTechnician Apr 26 '18 at 20:55

1 Answers1

0

Remove the $using: from the scriptblock and it should work properly. I took the liberty of cleaning up the code a bit. The result looks like:

function Invoke-DirectOnVM
{
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory)]
        [CloudEngine.Configurations.EceInterfaceParameters]
            $Parameters,

        [Parameter(Mandatory)]
        [String[]]
            $VMNames,

        [Parameter(Mandatory)]
            $VMCredential,

        [Parameter(Mandatory)]
        [ScriptBlock]
            $ScriptBlock,

        [Parameter()]
        [Object[]]
            $ArgumentList = $null
    )

    $PSBoundParameters.Remove("ScriptBlock")

    Invoke-Command @PSBoundParameters -ScriptBlock ([ScriptBlock]::Create( "Import-Module OpenUpSession; Set-FullLanguage; `r`n" + $ScriptBlock ))
}
Bruce Payette
  • 2,511
  • 10
  • 8