$APIkey
is being set after it is being used, which must be wrong. It probably works in the console because $APIkey
happens to already be set.
If you like (I think it's a good idea), you can add the following to the top of your scripts to catch errors like this one.
Set-StrictMode -Version Latest