3
votes

I have a hard time creating a pester for a specific Powershell function using invoke-command and having a $using variable on a script block. It would always return an error whenever i run my test. Sample function and test below:

Function:

Function Execute-Function {
.
.
.
$Name = "Computer_Name"

$ScriptBlock = {
    Import-Module "Activedirectory"
    Get-Computer -Name $Using:Name
}

Invoke-Command -Session $Session -ScriptBlock $ScriptBlock
}

Test:

Describe 'Execute-Function' {
.
.
.
.
mock Import-Module {} -verifiable

mock Get-Computer {} -verifiable

mock Invoke-Command {
 param($Scriptblock)
 . $Scriptblock
} -verifiable


$result = Execute-Function

it 'should call all verifiable mocks'{
 Assert-verifiablemocks
}
}

Error of my test would return A using variable cannot be retrieved. A using variable can be used only with Invoke-Command.... I can not understand this error even though I mocked the Get-Computer to return nothing? or do I need to change how I mock Get-Computer for my test to pass?

Thank You in Advance

1
A potential workaround is using the old method of including a param block to your script block to pass arguments to Invoke-Command with an argument list. - Maximilian Burszley
Hi @TheIncorrigible1 thanks for replying. Does this mean I have to edit the function itself? Sorry I do not have enough knowledge for this yet. - Alexander Andro Jae Diaz
Yes, it would require re-writing any calls to Invoke-Command to utilize a param block. Invoke-Command { param($myparam) ... } -ArgumentList ... - Maximilian Burszley
Wow, thanks @TheIncorrigible1 my test now passes and also I can achieve a 100% code coverage. You really helped me a lot. Thank you very much. - Alexander Andro Jae Diaz
Great, I'll post it as an answer then. - Maximilian Burszley

1 Answers

2
votes

I'm not sure you can emulate the $using: scope with Pester. You can, however, utilize the pre-$using:-scope way of doing things:

Invoke-Command -ScriptBlock {
    Param(
        [Parameter(Position = 0)]
        [String] $Name
    )

    <# ... #>

} -ArgumentList $Name