Can't Pass Pester Test because of local variable variable error

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

Upvotes: 3

Views: 761

Answers (1)

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

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

Upvotes: 2

Related Questions