Run PowerShell from Azure DevOps - sharepoint

I have a task: to install solution (wsp) on remote machine using Azure DevOps Pipelines.
I have folder with *.wsp. And I have a PS-script. If I do it manually on this machine it works fine. No errors.
But when I use Azure DevOps I have a message:
Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 5.
At C:\Windows\SysWOW64\WindowsPowerShell\v1.0\profile.ps1:1 char:1
+ Add-PSSnapin "Microsoft.SharePoint.Powershell"
At the very beginning of my PS script I have this:
Add-PSSnapin "Microsoft.SharePoint.Powershell"
I need it, because I use Uninstall-SPSolution, Remove-SPSolution, Add-SPSolution and Install-SPSolution cmdlets inside script.
I've tried to add
Add-PSSnapin "Microsoft.SharePoint.Powershell"
to "profile.ps1", I've tried to run powershell inside powershell. Again and again error is the same. I don't understand how to fix it.
https://i.stack.imgur.com/UNM7R.png
https://i.stack.imgur.com/NTiWs.png
https://i.stack.imgur.com/sA6tU.png
https://i.stack.imgur.com/bK9kq.png

Try preceding your command with Get-PSSnapIn:
if (Get-PSSnapin "Microsoft.SharePoint.Powershell") {
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 5.
At C:\Windows\SysWOW64\WindowsPowerShell\v1.0\profile.ps1:1 char:1
Based on the error message, when the powershell execute the ps file, it get the error.
In Auzre Devops Powershell task, it will use the powershell.exe from C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.
The exe path you use to execute the powershell file is different from the default.
You could run the following command in azure devops:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe Get-PSSnapin -Registered
and
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe Get-PSSnapin -Registered
You can check if the Microsoft.SharePoint.Powershell exists.
Then you could use the correct powershell.exe path to execute the ps file.
For example:
C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe "path/xx.ps"

Related

How to run PowerShell cmdlets from custom PS modules when deploying a new Azure VM?

Is it possible to install a custom PowerShell module in Azure VM post-deployment task and run PS cmdlets from that module in this task?
I have a Bicep template that deploys a new Windows Azure VM. The template has a Microsoft.Compute/virtualMachines/extensions#2020-12-01 post-deployment resource that takes these steps:
Installs an MSI-packaged application (with a new custom PowerShell module) using Start-Process (OK)
Creates several folders via PowerShell (OK)
Runs several cmdlets installed at step 1 (NOT OK)
Running a cmdlet from the custom module in the post-deployment script shows the following error in the "Extensions + applications" log:
... is not recognized as the name of a cmdlet ...
When I change the post-deployment step to Import-Module MODULENAME, I see another message:
Import-Module : The specified module 'MODULENAME' was not loaded because no valid module file was found in any module \r\ndirectory.
When I run Get-Module in the post-deployment task, I see only these two modules listsd:
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Manifest 3.1.0.0 Microsoft.PowerShell.Management {Add-Computer, Add-Content, Checkpoint-Computer, Clear-Con...
Manifest 3.1.0.0 Microsoft.PowerShell.Utility {Add-Member, Add-Type, Clear-Variable, Compare-Object...}
So the module is not getting loaded.
But when I remote to the deployed VM, I run the cmdlets from the custom PowerShell module without any errors.
I think that my scenario is supported, but I don't quite understand how to troubleshoot this further.
I resolved the problem with these two steps:
I've added -Wait to Start-Process and this has resolved the problem.
I've added a path to the module into PSModulePath and ran $Env:PSModulePath = $Env:PSModulePath+";PATH-TO-MODULE"
Import-Module MODULENAME -Force. Normally, the installed does this step for me. But it appears that I need to run these commands manually because all this is done in a single PowerShell session.
It appears that the problem was with my customScript.ps1 script. The very first line of the script installs an MSI-packaged application that adds the required PowerShell module:
Start-Process -FilePath msiexec.exe -ArgumentList #('/i', 'msi-installer-name.msi', '/qb')
PowerShell starts the installation using Start-Process and continues. So when I'm running these commands, the installation hasn't yet finished:
$env:PSModulePath | Out-File C:\Temp\psmodulepath.txt
Get-Module -ListAvailable | Out-File C:\Temp\getmodulelistavailable.txt

Azure DevOps - Set-Azcontext - The term 'Set-Azcontext' is not recognized

I have created one Azure DevOps pipeline.
99% of this pipeline calls PowerShell scripts (PowerShell Core script type).
Within the Power Shell scripts are calls to the AZ module - this all works fine.
I now have to add a new step within the DevOps pipeline to set the 'VulnerabilityAssessment' on an SQL server - however this time I need to call module 'Set-Azcontext' as part of the PowerShell script which is shown below...
[CmdletBinding()]
param(
$prgname,
$psqlservername,
$psaname,
$pnotificationmmail = 'john.doe#hotmail.com',
$psubscriptionname = 'ABC'
)
#debug
#Get-Module -Name AZ -ListAvailable
# working in powershell and need to set the correct subscription in powershell (ABC)
Set-Azcontext -Subscription "ABC"
#Enable-AzSqlServerAdvancedDataSecurity -ResourceGroupName $prgname -ServerName $pservername -DoNotConfigureVulnerabilityAssessment
# https://learn.microsoft.com/en-us/powershell/module/az.sql/update-
azsqlservervulnerabilityassessmentsetting?view=azps-7.5.0
#Update-AzSqlServerVulnerabilityAssessmentSetting -ResourceGroupName $prgname -ServerName $pservername -StorageAccountName $psaname -ScanResultsContainerName "vulnerability-assessment" -RecurringScansInterval Weekly -EmailAdmins $true -NotificationEmail #pnotificationmmail
When the Azure devOps pipeline runs it fails on step...Set-Azcontext -Subscription "ABC"
update-vulnerability-assessment.ps1 : The term 'Set-Azcontext' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
The devOps process is running on a Azure agent. It looks like a module is not available or loaded.
Maybe I need to install/load the module containing 'Set-Azcontext' as part of the powershell script ? (if so how do I do this)
OR
Install a new capibility of the agent to have the module containing 'Set-Azcontext' installed?(if so how do I do this)
Going to instead via an ARM template in the Azure pipeline for setting the vulneratibilty of Azure SQL server

Error when run Az powershell create Runbook

I create new runbook by ansible-playbook like that
name: Connect azure account
command: pwsh -Command "(Connect-AzAccount -Identity).context"
name: Create runbook
command: pwsh -Command "New-AzAutomationRunbook -AutomationAccountName 'Testing' -Name 'Runbook02' -ResourceGroupName 'hoadtn_ansible_rg' -Type Python3"g
But when I run , it show error
how to resolve this error ?
thanks
For the above error please make sure that you have updated Ansible version which is 2.9 or above.
Then run the command az login once successfully run the command then run the following command to create runbook in your azure automation .
We have tried the same and works fine :
For more information please refer the below links:-
Ansible Installation guide
SO THREAD: Ansible install all required Azure modules

Calling a PowerShell script from Azure batch custom activity using PowerShell and application environment variable

I've been slowly working out how to call a PowerShell script to transform IIS logs using LogParser 2.2. I've settled on using Azure Data Factory Batch Service Custom Activity to run the PowerShell script. I've been able to figure out how to address many of the file path issues that arise in running PowerShell from within Azure Custom Batch Activity, but I can't figure this one out.
Currently I'm just trying to print via Write-Host the environment variable AZ_BATCH_APP_PACKAGE_powershellscripts#1.0 I've been able to print other environment variables, but I believe the #1.0 at the end of this one is causing all my grief. BTW the 1.0 is the version of the application loaded into the batch framework in Azure.
All of the following attempts have failed:
powershell powershell Write-Host "$AZ_BATCH_APP_PACKAGE_powershellscripts#1.0"
powershell Write-Host "$AZ_BATCH_APP_PACKAGE_powershellscripts#1.0"
powershell Write-Host "$env:AZ_BATCH_APP_PACKAGE_powershellscripts#1.0"
powershell powershell Write-Host "$env:AZ_BATCH_APP_PACKAGE_powershellscripts\#1.0"
powershell powershell Write-Host "$env:AZ_BATCH_APP_PACKAGE_powershellscripts/#1.0"
powershell powershell Write-Host "$env:AZ_BATCH_APP_PACKAGE_powershellscripts"
powershell powershell Write-Host "$env:AZ_BATCH_APP_PACKAGE_powershellscripts`#1.0"
powershell powershell Write-Host "$env:AZ_BATCH_APP_PACKAGE_powershellscripts`#1`.0"
powershell powershell Write-Host "$env:AZ_BATCH_APP_PACKAGE_powershellscripts\`#1.0"
powershell powershell Write-Host "$AZ_BATCH_APP_PACKAGE_powershellscripts`#1.0"
These works, but are either cmd window or not the variable I want:
powershell powershell Write-Host "$env:AZ_BATCH_TASK_DIR"
powershell powershell Write-Host "$env:AZ_BATCH_ACCOUNT_URL"
cmd /c echo %AZ_BATCH_APP_PACKAGE_powershellscripts#1.0%
So what is the secret syntax sugar to getting this to work in Azure?
Sure, you can do this:
powershell powershell Write-Host "$((Get-Variable -Name 'AZ_BATCH_APP_PACKAGE_powershellscripts#1.0').Value)"
Or this:
powershell powershell Write-Host (Get-Variable -Name "AZ_BATCH_APP_PACKAGE_powershellscripts#1.0").Value
I went through close to 50 tries before getting this to work like so:
powershell powershell Write-Host (Get-ChildItem Env:AZ_BATCH_TASK_DIR).Value
powershell powershell Write-Host (Get-ChildItem Env:AZ_BATCH_APP_PACKAGE_powershellscripts#1.0).Value
Now this was just a stepping stone to running a PowerShell script stored in an attached application to the Azure Batch module. I'm hopeful Microsoft will add a Databrick or better way to run a PowerShell script in Azure Data Factory, but until then this is the only method I found to run a powershell script:
powershell powershell -command ("(Get-ChildItem Env:AZ_BATCH_APP_PACKAGE_powershellscripts#1.0).Value" + '\Powershell\processWebLogsFromAzure.ps1')
This should work for anyone just trying to run from the Batch Task Dir:
powershell powershell -command ("$env:AZ_BATCH_TASK_DIR" + '\wd\processWebLogsFromAzure.ps1')
Hope it helps someone!

Azure runbook automation - Invoke-AzureRmVMRunCommand error

I have an Azure runbook that runs on schedule. Its in powershell and this runbook starts a VM and executes a script on the VM started. How I achieve this is
1) Store the script to be run on the VM in a storage account
2) Run powershell runbook
3) Powershell runbook uses wget command to copy the script from step 1
4) Invoke-AzureRmVMRunCommand in the Azure automation powershell commands as shown below
wget "https://utilitystorageaccnt.blob.core.windows.net/utilitycontainer/token" -outfile ((Get-Location).path + "\Reporting Copy.ps1") -UseBasicParsing
Invoke-AzureRmVMRunCommand -ResourceGroupName $ResourceGroupName -VMName $VmName -CommandId 'RunPowerShellScript' -ScriptPath ((Get-Location).path + '\Reporting Copy.ps1') -ErrorVariable result
Please not that the above two commands are in the powershell runbook script and not the actual script that is run on the VM.
Facing two issues
1) When this script Reporting Copy.ps1 runs standalone on the VM, then it works properly and it has no issues. When it is run using the runbook, I get these errors in the log file on the target vm.
"New-AzStorageContext : The term 'New-AzStorageContext' 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."
2) Even after this error occurs, it doesnt terminate and runs in loops. This script does a copy operation and it keeps looping until all the copy is complete. I can handle code to terminate but I would like to know how to force terminate a runbook. I tried to stop the VM for even a hour and it resumes the copy operation. The runbook status in Azure shows as completed. There are two python processes that show in explorer and terminating them doesn't work either.
Any help or hint is appreciated.
Thanks.
Look like you did not imported Az PowerShell module into our Automation Account.
Please, follow this tutorial : Az module support in Azure Automation
Try to use only Az module and not AzureRM
The issue was because I had not installed the AZ module for all users like this.
Install-Module -Name Az -AllowClobber -Scope AllUsers
Instead I had used
Install-Module -Name Az -AllowClobber -Scope CurrentUser
and since the automation runs on a different user, the issue occurred. Thanks for your help.

Resources