Azure Functions - PowerShell - "The pwsh executable cannot be found at ..." - azure

When my PowerShell Azure Function runs using the Test/Run feature in the portal, I get this error in the connected console output.
The pwsh executable cannot be found at "C:\Program Files (x86)\SiteExtensions\Functions\3.3.1\workers\powershell\7\runtimes\win\lib\netcoreapp3.1\pwsh.exe"
Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios
My script looks something like below.
Note the invocation of the web request does indeed fail with an HTTP 500, triggering, I assume the catch block and the if.
try {
Invoke-WebRequest ...
}
catch {
$exc = $_;
}
if ($null -ne $exc) {
Writing-Warning "This failed when something blah.";
throw $exc;
}
This is the gyst. The real script actually makes a few web requests, any of which could fail. I want to ensure they all get executed, so I catch and then store the exception, and then only at the end the script can throw and fail, and my hope is at least one of the problems makes it out into logging or somewhere in the portal or something.
The actual message looks like this. It smells like an Azure problem to me.

I just ran it again and it fixed itself. Thanks for wasting my time, Azure.

Related

Binding Redirection in Azure Automation Account PowerShell Runbook

I'm in need of some help in setting up PowerShell binding redirection within an Azure Automation Account Runbook.
Essentially my Runbook calls a number of methods within two 3rd party .Net dlls, both provided by the same author. One of the dlls has a dependency on Newtonsoft.Json V12.0.1 and the other has a dependency on IdentityModel V4.0.0 which in turn has a dependency on Newtonsoft.Json V11.0.2. My Azure environment uses Windows PowerShell Desktop V5.1.15063.726. Before I do any work in my Runbook I call a function that loads all of the dlls in my imported module (the function calls the [System.Reflection.Assembly]::LoadFrom() method for each dll). I have verified that my imported dlls, including the Newtonsoft.Json.dll V12.0.1 have loaded successfully.
As expected, when Runbook execution hits a line that calls one of the 3rd party dll methods that needs the IdentityModel.dll an exception is thrown:
Exception calling "GetResult" with "0" argument(s): "Could not load file or assembly 'Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified." System.IO.FileNotFoundException.
This is a known issue and the consensus so far seems to be that I need to create and attach an event handler in PowerShell. One of the proposed solutions can be found here. My problem is with the line that attempts to attach the handler:
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolveEventHandler)
When my Runbook hits this line the following exception is thrown:
Cannot find an overload for "add_AssemblyResolve" and the argument count: "1". TargetSite: Void CheckActionPreference(System.Management.Automation.Language.FunctionContext, System.Exception) StackTrace: at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
I can confirm that very limited testing seems to prove the code works in Windows 8.1 using the PowerShell ISE. I have searched extensively to see if there is a difference between how this code should be written in Azure and Windows Desktop, but no luck. Can anyone see what I am doing wrong? Am I missing any DLLs or using statements from my PowerShell script? If it is not possible to redirect binding in this way can anyone help with an alternative technique?
A code extract showing the creation and attachment of the event handler follows:
# Intercept resolution of binaries
$onAssemblyResolveEventHandler = [System.ResolveEventHandler]
{
param($sender, $e)
Write-Host "ResolveEventHandler: Attempting FullName resolution of $($e.Name)"
foreach($assembly in [System.AppDomain]::CurrentDomain.GetAssemblies())
{
if ($assembly.FullName -eq $e.Name)
{
Write-Host "Successful FullName resolution of $($e.Name)"
return $assembly
}
}
Write-Host "ResolveEventHandler: Attempting name-only resolution of $($e.Name)"
foreach($assembly in [System.AppDomain]::CurrentDomain.GetAssemblies())
{
# Get just the name from the FullName (no version)
$assemblyName = $assembly.FullName.Substring(0, $assembly.FullName.IndexOf(", "))
if ($e.Name.StartsWith($($assemblyName + ",")))
{
Write-Host "Successful name-only (no version) resolution of $assemblyName"
return $assembly
}
}
Write-Host "Unable to resolve $($e.Name)"
return $null
}
# Attach event handler
# This is the line that fails.
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolveEventHandler)
I haven't been able to resolve the problem with getting binding redirection working in an Azure Automation Account - PowerShell runbook environment, but the author of the two 3rd party .Net dlls has kindly agreed to use NewtonSoft.Json version 11.0.2 for both dlls, so my problem disappears.

Why is my powershell DSC failing with the message "An item with the same key has already been added"

We have a powershell DSC that is being executed to bring a vmss to a desired state.
It was working until we added some more parameters, and then it broke.
I removed everything except the parameters from the script and it still doesn't work.
The full error is
The DSC Extension received an incorrect input: An error occurred while
executing script or module 'IISInstall.ps1': An item with the same
key has already been added..
Please correct the input and retry executing the extension.
We even added logging in the DSC to try to troubleshoot.
It doesn't even seem to make it into the body of the DSC.
What am I doing wrong?
The parameter was called $instanceName. We wanted to use it to add a custom header to IIS to track which instance a response came from.
Turns out if you use $instanceName that steps on the internals of DSC in some way and it will never deploy correctly!
As soon as you remove $instanceName from the parameter list, it will work.

Azure Function App in PowerShell generating host threshold exceeded errors

We just started getting this error yesterday but haven't changed anything in our app. Any ideas? If we restart the function app, it will run for a short time and then start giving us this error again. The function app is in PowerShell.
Host Error: Microsoft.Azure.WebJobs.Script: Host thresholds exceeded: [Connections]
This was recently added in the runtime to track running out of available connections on the VM
https://github.com/Azure/azure-webjobs-sdk-script/pull/2063
It should point to you running out of available connections. It could be wrong or correct, but I can't tell without looking at your functions themselves.
If you would like to discuss it, then you probably should use the repo above
I'm not sure if it is the above change that caused this but it is a coding issue on my side that is now being handled correctly by Azure Functions. I created this small repo and after I commented out the close, I received the error. My real code is more complex but clearly somewhere I'm not closing it out.
$Ports = #(21,22,23,53,69,71,80,98,110,139,111,389,443,445,1080,1433,2001,2049,3001,3128,5222,6667,6868,7777,7878,8080,1521,3306,3389,5801,5900,5555,5901)
for($i = 1; $i -le $ports.Count;$i++) {
$port = $Ports[($i-1)]
$client = New-Object System.Net.Sockets.TcpClient
$beginConnect = $client.BeginConnect("123.123.123.123",$port,$null,$null)
#$client.Close();
}

Why is my webjob terminating without throwing an exception?

My azure webjob appears to be terminating without throwing an exception and I'm lost.
My web job is run on-demand (or scheduled) and has a dependency on my web site DLL (and MVC app). It calls into it to do most of the work, which includes working with an entity frameworks database and making REST calls to several other sites. Most of the work is done asynchronously. Most of the code used to do this work is also called from other parts of the site without problem, and it goes without saying that the web job works flawlessly when run locally.
The web job terminates and doesn't seem to throw an exception when it does and it doesn't seem to be possible to debug a web that's not of the continuously run variety (?). Therefor, my debugging has mostly been of the Console.WriteLine variety. Because of that and the asynchronisity, I haven't been able to nail down exactly where it's crashing - I thought it was while accessing the database, but after mucking with it, the database access started working.. ugh. My next best guess it that it dies during an await or other async plumbing. It does, however, crash within two try/catch blocks that have finallys that log results to redis and azure storage. None of that happens. I can not figure out, or imagine, how this process is crashing without hitting any exception handlers.. ?
Anyone had this problem with an azure webjob? Any idea what I should be looking for or any tips for debugging this?
Thanks!
I figured it out! One of the many things happening asynchronously was the creation of a certificate. I traced it down to this:
signedCert = new X509Certificate2(cert, "notasecret", X509KeyStorageFlags.Exportable);
This code works fine when called from my azure website or my tests, but kills the webjob process completely without throwing an exception! For example, the WriteLine in the exception handler below never gets called:
X509Certificate2 signedCert;
try
{
signedCert = new X509Certificate2(cert, "notasecret", X509KeyStorageFlags.Exportable);
}
catch (Exception ex)
{
// We never get here! Argh!
Console.WriteLine("Exception converting cert: " + ex);
throw;
}
Extremely time consuming and frustrating. Unlike the diagnosis, the fix is simple:
signedCert = new X509Certificate2(
cert,
"notasecret",
X509KeyStorageFlags.Exportable |
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet);

program crashes when called by task scheduler

I have written a program in c# that includes a bit of file io and SystemEvents Switches.
The program runs fine if I run it from explorer, but when i call it at log on from task scheduler, it crashes. Any clues as to why this would be happening?
Have you tried opening task scheduler as Administrator - e.g. right-click run as Administrator.
It could be due to permissions. You can view the history of the task in the history tab to view this.
Make sure the correct permissions have been set for the exe, as you mentioned "Log in" from task scheduler - what permissions does this use and are they the same as when you run the exe manually?
try :
1 - try cactch block with some logging
try
{
// .. youre code
}
catch (Exception ex)
{
//TODO: logging
}
2 - does eventviewer give you a clue
[windows key] + [r] => eventvwr
Thanks for the try-catch suggestion, lordkain.
The error was thrown when trying to access an external icon file. The fix was as simple as adding the appropriate file path to the "Start In:" field in task scheduler.
Are you scheduling it from a different folder? Be sure to copy any DLLs over as well as the .exe. I've made this mistake before!

Resources