3

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 Answers1

2

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
Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63
  • 2
    This works as expected and as of right now is the most optimal solution for us. I have tried my hand at programmatically working around this to avoid the need to change production code, however have been unsuccessful I have documented my attempts in an issue here: https://github.com/pester/Pester/issues/2015 – aolszowka Jun 25 '21 at 13:42