Trouble calling runbook when name is a variable

60 Views Asked by At

Facing some unexpected behavior in Azure Automation that I just can't figure out. I have a runbook called "Test2" with just 1 line in it, so I can see if it runs: Write-Output "this works" I have another runbook called Test1. I want to call Test2 from Test1.

This code works fine. It runs Test2 twice:

$test = 'Test2'
& .\Test2.ps1
& .\"$test".ps1

However, THIS code fails to run Test2:

$test = 'Test2'
#& .\Test2.ps1
& .\"$test".ps1

Only change is commenting out the first call. So if I call the runbook just using its name, I can subsequently call it with the variable. But if I don't, I can't.

The error message confirms that it evaluates the variable, but for some reason it just can't find the runbook? Any assistance would be appreciated. The error: & : The term '.\Test2.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program.

1

There are 1 best solutions below

0
Jahnavi On

Firstly, When I execute the script without commenting the & .\test2.ps1, it worked as expected.

$test = 'test2'
& .\test2.ps1
& .\"$test".ps1
write-output "call success"

Output:

enter image description here

Once its done, I tried running the same script as you (commented & .\test2.ps1) and the call from test to test2 runbook was successful as shown below.

enter image description here

enter image description here

Try checking the test2 file directory path once and re run the script.

If still the issue persists, as a workaround you can use Invoke-Expression command to take the call expression instead of substituting it in the variable.

$test = 'test2'
#& .\test2.ps1
Invoke-Expression "& .\$test.ps1"
write-output "call success"

Output:

enter image description here