Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 738
Alexander Andro Jae Diaz Avatar asked Feb 11 '26 19:02

Alexander Andro Jae Diaz


1 Answers

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
like image 86
Maximilian Burszley Avatar answered Feb 13 '26 18:02

Maximilian Burszley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!