Import-Module with powershell from asp core website - azure

I´m currently trying to call an powershell application from my asp core application.
My first command is Import-Module to make sure that the correct module is loaded.
I tried several ways to do this:
using (PowerShell ps = PowerShell.Create())
{
ps.AddCommand("Import-Module AzureRm").Invoke();
}
This throws an CommandNotFoundException:
CommandNotFoundException
The term 'Import-Module AzureRm' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path
is correct and try again.
If I use AddScript instead I don´t get any feedback at all:
var result = ps.AddScript("Import-Module AzureRm").Invoke();
Result is always returned as an empty object.
Is is even possible to use Import-Module in an ASP core application?
How do I get an result from AddScript and not an empty object?

Related

What are "variants" in Azure permissions

In the examples on this https://learn.microsoft.com/en-us/powershell/microsoftgraph/find-mg-graph-command?view=graph-powershell-1.0, I see something called "variants", but I haven't found any explanation of "variants" when I search.
Specifically, I'm trying to work with our Azure team to set the proper permission for the email "markRead" function:
$graphApiPostUrl = "https://graph.microsoft.com/v1.0/admin/serviceAnnouncement/messages/markRead"
Find-MgGraphCommand -Uri $graphApiPostUrl | Format-Table -AutoSize
I requested ServiceMessageViewpoint.Write permisison, and they said they gave it to me, but I'm still gettting an "401 unauthorized" when I try it. I'm wondering if I need to request the variants as well? [I am able to list/enumerate the emails.]
My original question was here: Powershell - How to set token for GraphAPI to mark emails as read?
Variants don't have anything to do with Azure Permissions. In this case, they are a different word for Powershell parameter sets.
get-help Find-MgGraphCommand -Full
OUTPUTS
Microsoft.Graph.PowerShell.Authentication.Models.IGraphCommand with the following properties:
1. Command: Name of command.
2. Module: Module in which a command is defined.
3. Method: The HTTP method a command makes.
4. Uri: The Microsoft Graph API URI a command calls.
5. OutputType: The return type of a command.
6. Permissions: Permissions needed to use a command. This field can be empty if the permissions are not yet
available in Graph Explorer.
7. Variants: The parameter sets of a command.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parameter_sets?view=powershell-7.2
PowerShell uses parameter sets to enable you to write a single function that can do different actions for different scenarios. Parameter sets enable you to expose different parameters to the user. And, to return different information based on the parameters specified by the user. You can only use one parameter set at a time.
You are using the command correctly, there is rather an issue the call to graph API.

How to change PowerShell culture in an Azure Function

I have written a script where i use Swedish characters ("åäö"), it is deployed to an Azure function.
When the script runs it is supposed to output this text: "Förvaltning" but i get this instead: "Förvaltning".
I tried changing the culture of Powershell by including Set-Culture i the beginning of the script. But it doesn't change the culture.
Anyone know how to do this for a PowerShell Script running in an Azure Function?
This code runs to set the variable "prefixTitle".
This is then logged to the "Logs", when i write "Write-Output".
It has something to do with your browser side encoding in the sense how it is rendering utf-8, and not Function side. I ran my powershell sample function without setting anything in the function code. Both log output and http response looks ok as below.

Wrong publishsettings xml file structure for Import-AzurePublishSettingsFile command

I have a fresh publishsettings file obtained with use of command Get-AzurePublishSettingsFile
And when I run following command:
Import-AzurePublishSettingsFile -SubscriptionDataFile "path to publishsettings"
I'm getting this error:
Import-AzurePublishSettingsFile : Error in line 1 position 14. Expecting element 'ProfileData' from namespace 'http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.Comman
ds.Utilities.Common'.. Encountered 'Element' with name 'PublishData', namespace ''.
At line:1 char:1
+ Import-AzurePublishSettingsFile -SubscriptionDataFile "path to publishsettings ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Import-AzurePublishSettingsFile], SerializationException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.ImportAzurePublishSettingsCommand
Looks like powershell cmdlet expects to see a file with different structure, but I have no idea where I can get one.
Am I doing something wrong here or it's an issue with Azure Powershell?
Azure module version is 0.8.2
I don't have an answer to your specific question. But I may have a better option, and something you can try to resolve the original issue.
See ArgumentNullException - Get-AzureService.
That post describes the following two options:
Instead of using publish settings files for management API authentication you can use your normal management portal login credentials. This is generally a better option for using the Azure powershell cmdlets.
If that doesn't work for you then see the link above for how to clear out the cached subscription configuration files and see if that fixes the Import-AzurePublishSettingsFile issue you are seeing.
I ran into the same issue. It turned out that I had used the incorrect parameter switch to specify the settings file.
Double check that you are using -PublishSettingsFile argument and not -SubscriptionDataFile as shown in your examples.
See the excerpt from powershell help below, for an explanation of each parameter.
Parameters
-PublishSettingsFile <String>
Specifies the full path and filename for the .publishsettings file for the Windows Azure account.
Required? true
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters? false
-SubscriptionDataFile <String>
Specifies the path to a file where the subscription data is stored. This parameter is optional. If it is not provided, the subscription data is imported into a default file in the user's profile.
Required? false
Position? named
Default value
Accept pipeline input? false
Accept wildcard characters? false
I was able to make this work after several tries.
You need to start PowerShell as Administrator and clearly layout the path to the filename assigned the downloaded file to.
Once I did this it worked well.

Powershell Start-Website IIS

Problem/Question
I'm test running a script for redgate deployment. At the last step it starts a website:
import-module WebAdministration
$website = get-website | where-object { $_.name -eq $RedGateWebSiteName }
#(re)write HostName#
$binding = Get-WebBinding -Name $RedGateWebSiteName
Set-WebBinding -Name $RedGateWebSiteName -BindingInformation "*:80:*" -PropertyName HostHeader -Value $HostName
if ($website) {
Start-Website "$RedGateWebSiteName"
}
It always worked but now on one of the last days I get this error
At D:\inetpub\Timeblockr-RedGate\Api\PostDeploy.ps1:15 char:15
+ Start-Website <<<< "$RedGateWebSiteName"
+ CategoryInfo : InvalidOperation: (:) [Start-Website], COMException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.IIs.PowerShell.Provider.StartWebsiteCommand
IIS error
The World Wide Web Publishing Service (WWW Service) did not register the URL prefix http://*:80/ for site 3. The necessary network binding may already be in use. The site has been disabled. The data field contains the error number.
This SO question "Cannot create a file" error when running Start-Website command in Powershell gives a pretty good clue what it can be.
Edit:
After viewing my event log and checking out the answers I found out that when Redgate automaticly tries to install/start the website i'm getting this IIS error:
The World Wide Web Publishing Service (WWW Service) did not register the URL prefix http://*:80/ for site 3. The necessary network binding may already be in use. The site has been disabled. The data field contains the error number.
In this Serverfault : https://serverfault.com/questions/456217/the-world-wide-web-publishing-service-www-service-did-not-register-the-url someone its mentioning that the cause of that is that a IIS website gets created without hostheader. I'm adding the hostheader after I try to start the website. Lets find the solution
Edit 2:
I was adding the hostname after I tried to start the website. This caused that the website has e empty hostname and that conflicts in IIS. (or somewhere else).
I've changed my script to get the website, add the hostname and then start the website.
Also added "$RedgateWebsiteName" instead of $RedGateWebSiteName. Works perfectly now!
Edit 3:
After a run of tests I seem to end up the same error. The one deploy has no problems, the other deploy does has.
Edit 4:
I've updated the script / Error / Post.
I deleted my site from IIS after that I clicked on install. Perfectly installed - No problems, automatic start.
Second run exactly the same, third run I get the error above!
I'm guessing the $RedGateWebSiteName variable had not been assigned a value, assuming the log message replaces the variable with its' value. From googling around, it looks like the IIS "file already exists" message may be erroneous as it happens because of anything from a missing IP address binding to an invalid virtual directory folder.
Why do you need a script to start the website? If you are using Red Gate Deployment Manager, it starts the website after the deploying a web package (any package with a web.config file it).
It could be that the value substitution for $RedGateWebSiteName is not taking place and it probably needs double quotes:
Start-Website "$RedGateWebSiteName"
I say this because your error message says this:
Start-Website <<<< $RedGateWebSiteName
while the error message here displays the substituted value:
start-website <<<< "MyWebsite"
I had the exact same problem, when starting the website with:
Start-Website -Name MyWebSiteName
and it would not start. When I tried to start it manually in IIS Manager, it wouldn't start either and I got this error message:
The World Wide Web Publishing Service (W3SVC) is stopped. Websites cannot be started unless the World Wide Web Publishing Service (W3SVC) is running.
This is pretty clear that the service is not started and it turned out to be true.

Cannot query Active Directory using ServerBind on non-domain computer in Windows PE

I have a need to write a .NET application which will query Active Directory while running in Windows PE on a computer which is not yet a member of the domain.
We are running this during a Microsoft Deployment Toolkit task sequence (note that MDT 2012 has been configured to load support for .NET into the WinPE environment - the .NET application is starting without any problems).
I am using the code below to bind to the domain:
DirectoryEntry entry = new DirectoryEntry(
path,
username,
password,
AuthenticationTypes.ServerBind | AuthenticationTypes.Secure);
I have tried a path both of the form:
LDAP://domainServer/dc=domain,dc=name
And also without a domain controller name as
LDAP://dc=domain,dc=name
I have also tried using a username both of the form domain\username and also just username.
The DirectoryEntry object seems to be constructed okay, but when I try to execute Console.Writeline(entry.Name) to confirm a valid connection has been made, I get the following exception:
System.Runtime.InteropServices.COMException (0x80005000): Unknown
error (0x80005000) at
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind() at
System.DirectoryServices.DirectoryEntry.get_Name()
I have tried other variations on this code, trying to execute LDAP queries with various filters, trying to rewrite it in VBScript, etc... but the code posted above is the simplest example I could come up with which reproduces the problem.
From what I have read, in a scenario like this you would always need to use AuthenticationTypes.ServerBind and that is why I am trying to specify the code within the ADSI LDAP path. But what is wrong with the code above? To me, it looks like it is passing all needed information in the parameters to the DirectoryEntry constructor.
There is a way to get it work, but it's not supported by Microsoft. This post helped me a lot. It works, tested and approved for a deployment of new computers :)
Get the ADSIxXX.inf from the zip file to C:\ADSI
Copy the following files from a Windows/System32 to C:\ADSI. Carefull of Architecture
x86 x64 -
adsldp.dll
adsmsext.dll
adsnt.dll
mscoree.dll
mscorier.dll
mscories.dll
Mount the bootimage.wim
No need to load Package (Your WinPE is already configured to load .NET API), juste add ADSI driver:
Dism /Image:C:\Mount /Add-Driver /Driver:C:\ADSI\ADSIxXX.inf /forceunsigned
No need to load his script
Unmount the bootimage.wim
Then it's done, if your .NET application is well implement ;)
I'm not sur the PIPE | is supported as an argument too, just set to AuthenticationTypes.Secure -
DirectoryEntry entry = new DirectoryEntry(
path,
username,
password,
AuthenticationTypes.ServerBind | AuthenticationTypes.Secure);
Link: http://www.deploymentresearch.com/Research/tabid/62/EntryId/74/ADSI-plugin-for-WinPE-4-0.aspx#AddComment

Resources