Forum Discussion
Powershell script in C# code under azure web job error
You shoudl try to set $env:PSModulePath it looks like your modules aren't being found. Did you publish the modules to your Azure environment?
Thanks
- May 03, 2017
Hi KJS,
I'm having to make some assumptions. But if your module files are in Azure then you migth find that they aren't in the location where you expect them to be.
In general I first get the path where I'm running my scripts form:
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
Then I set my module path
if ($env:PSModulePath -notlike "*$path\Modules\MyModules\Modules*") { $env:PSModulePath += ";$path\Modules\MyModules\Modules" }you might find that when you build abnd publish your project the module files are found in (and therefore published to) the bin/debug folder.
- KJSMay 03, 2017Brass Contributor
Thanks for the reply
I tried refrencing the path in the c# code but it did not worked
InitialSessionState initialSession = InitialSessionState.CreateDefault(); initialSession.ImportPSModule(new string[] { "D:\\home\\site\\wwwroot\\app_data\\jobs\\triggered\\NMLSiteStorage\\Microsoft.Online.SharePoint.PowerShell" });this is the path in azure web job where all dll's are and it also has the code dll
D:\\home\\site\\wwwroot\\app_data\\jobs\\triggered\\NMLSiteStorage\\
Can you please tell do you want me to add it before the script with the above path
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
if ($env:PSModulePath -notlike "*$path\Modules\MyModules\Modules*") { $env:PSModulePath += ";$path\Modules\MyModules\Modules" }
const string connectScript = "Import-Module Microsoft.Online.SharePoint.PowerShell \r\n $AdminUrl = \"https://tenant-admin.sharepoint.com\" \r\n $UserName = \"user@tenant.onmicrosoft.com\" \r\n $Password = \"password\" \r\n $SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force \r\n $Credentials = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $SecurePassword \r\n Connect-SPOService -Url $AdminUrl -Credential $Credentials \r\n Get-SPOSite -Detailed -Limit All | select * ";
Thanks- May 03, 2017
You will need to replace \Modules\MyModules\Modules with the actual path where your modules live. Ensure that the fodler stucture is correct too. It is important that the Modules include a folder with the name of the actual module and then the module files need to exist in that folder.
I would set $path and $env:$PSModulePath inside your script (this is something that you can probably test by running it locally on your PC.)
Once the $env:PSModulePath is set correctly you will find that the modules are imported correctly ( assuming that the module files are located in the corrct place.
A few years ago I wrote some posts about PowerShell Modules:
https://veenstra.me.uk/2015/03/03/powershell-modules/