I can't get my registration script to run in PowerShell (admin). It works in Powershell ISE, but then the script is stuck at "Connecting to the server..."
Am I doing something wrong?
This is the script:
$ErrorActionPreference="Stop";If(-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent() ).IsInRole( [Security.Principal.WindowsBuiltInRole] “Administrator”)){ throw "Run command in an administrator PowerShell prompt"};If($PSVersionTable.PSVersion -lt (New-Object System.Version("3.0"))){ throw "The minimum version of Windows PowerShell that is required by the script (3.0) does not match the currently running version of Windows PowerShell." };If(-NOT (Test-Path $env:SystemDrive\'azagent')){mkdir $env:SystemDrive\'azagent'}; cd $env:SystemDrive\'azagent'; for($i=1; $i -lt 100; $i++){$destFolder="A"+$i.ToString();if(-NOT (Test-Path ($destFolder))){mkdir $destFolder;cd $destFolder;break;}}; $agentZip="$PWD\agent.zip";$DefaultProxy=[System.Net.WebRequest]::DefaultWebProxy;$securityProtocol=#();$securityProtocol+=[Net.ServicePointManager]::SecurityProtocol;$securityProtocol+=[Net.SecurityProtocolType]::Tls12;[Net.ServicePointManager]::SecurityProtocol=$securityProtocol;$WebClient=New-Object Net.WebClient; $Uri='[url]';if($DefaultProxy -and (-not $DefaultProxy.IsBypassed($Uri))){$WebClient.Proxy= New-Object Net.WebProxy($DefaultProxy.GetProxy($Uri).OriginalString, $True);}; $WebClient.DownloadFile($Uri, $agentZip);Add-Type -AssemblyName System.IO.Compression.FileSystem;[System.IO.Compression.ZipFile]::ExtractToDirectory( $agentZip, "$PWD");.\config.cmd --deploymentgroup --deploymentgroupname "Production" --agent $env:COMPUTERNAME --runasservice --work '_work' --url '[devopsUrl]' --projectname 'Storms' --auth PAT --token [token]; Remove-Item $agentZip;
The quotation marks are the issue. There are multiple types of quotation marks and depending on your country of residence this can cause issues.
This can be solved by removing the quotation marks around "Administrator" and adding them back manualy.
You can see the difference here:
“Administrator” versus "administrator"
Notice the difference in the quotation marks? The first pair is american and the second is the european version.
To resolve the above issue we need to run the script on Windows PowerShell (Run as Administrator)
For more information Please refer the below links:
Blog:- DevOps Deployment Group script stuck on “Connecting to the server.
Blog:- Getting started with Azure DevOps -create a deployment group
Related
Some context: I have a PowerShell script that gets information about users and their licenses on Azure, and then saves that information to CSV file. It works locally. My goal is to have this script automatically run on Azure (I'm trying to do it in an Azure Function App) once a month, and then have the created CSV file be emailed to a specified email. However all I want to figure out right now is how to get the list of users so that the script can at least just run without errors.
I have very little experience with PowerShell and Azure Function Apps, so I'm stuck on a few errors I'm getting. I have spent the last few days troubleshooting to no luck.
Here is the beginning of the script that I can run from my local PowerShell:
Function main()
{
#Clean up session
Get-PSSession | Remove-PSSession
#Connect AzureAD from PowerShell
Connect-MsolService
#Set output file
$ExportCSV=".\DetailedO365UserLicenseReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
$ExportSimpleCSV=".\SimpleO365UserLicenseReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
#FriendlyName list for license plan and service - txt file on local computer
$FriendlyNameHash=Get-Content -Raw -Path .\LicenseFriendlyName.txt -ErrorAction Stop | ConvertFrom-StringData
#txt file on local computer
$ServiceArray=Get-Content -Path .\ServiceFriendlyName.txt -ErrorAction Stop
#Hash table declaration
$Result=""
$Results=#()
$output=""
$outputs=#()
$LicensedUserCount=0
#Get all licensed users
Get-MsolUser -All | where{$_.islicensed -eq "true"} | Foreach{
#this is another function that handles grabbing the user info and writing it to the CSV file
Get_UsersLicenseInfo
$LicensedUserCount++
}
. main
With this script above, it requires some user input for entering credentials. I want this script to be able to run automatically in Azure without any user input, so I've been trying to modify it to do that. I found out that any commands with 'Msol' in the name don't work in Azure Function Apps/Powershell Core, so I found a different module that apparently does work.
This is where I'm currently at with the script to be run in my Azure Function App:
Import-Module AzureAD
Function main()
{
#Clean up session
Get-PSSession | Remove-PSSession
$password = ConvertTo-SecureString "{my password here}" -AsPlainText -Force
$UserCredential = New-Object System.Management.Automation.PSCredential ("myusernamehere", $password)
Connect-AzureAD -Credential $UserCredential
#Set output file
$ExportCSV=".\DetailedO365UserLicenseReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
$ExportSimpleCSV=".\SimpleO365UserLicenseReport_$((Get-Date -format yyyy-MMM-dd-ddd` hh-mm` tt).ToString()).csv"
#FriendlyName list for license plan and service - hash table here
$FriendlyNameHash= #{AAD_BASIC = "Azure Active Directory Basic"; AAD_PREMIUM= "Azure Active Directory Premium"; AAD_PREMIUM_P1= "Azure Active Directory Premium P1"; AAD_PREMIUM_P2= "Azure Active Directory Premium P2" }
#array of strings, used when getting user info
$ServiceArray= "MCOEV", "Cloud PBX", "MCOPSTN2", "PSTN International", "mcomeetadv"
#Hash table declaration
$Result=""
$Results=#()
$output=""
$outputs=#()
$LicensedUserCount=0
Get-AzureADUser -All | where{$_.islicensed -eq "true"} | Foreach{
Get_UsersLicenseInfo
$LicensedUserCount++}
}
. main
First of all I'm not sure if I even need to authenticate if this script is running from within my Azure account. Second of all, and my main issue, is that when I try to run this script in my Azure Function App, I get this error:
snippet of the azure error
If the picture doesn't work, it says:
The Function app may be missing a module containing the 'Connect-AzureAD' command definition. If this command belongs to a module available on the PowerShell Gallery, add a reference to this module to requirements.psd1. Make sure this module is compatible with PowerShell 7. For more details, see https://aka.ms/functions-powershell-managed-dependency. If the module is installed but you are still getting this error, try to import the module explicitly by invoking Import-Module just before the command that produces the error: this will not fix the issue but will expose the root cause.
2021-06-08T16:48:00.377 [Error] ERROR: The term 'Connect-AzureAD' 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.Exception
I get that same error for the line with 'Get-AzureADUser' as well. I followed this guide: https://tech.nicolonsky.ch/azure-functions-powershell-modules/ to add the AzureAD module to my managed dependencies, but I still get that same error.
If anything needs clarification, let me know. Any help is appreciated!
Actually, AzureAD needs to be imported a bit differently - it's been a problem for a while per this github issue. This seemed to work for most people:
Setting the application to run as x64 bit: Function App>
Configuration > General Settings > Platform > 64 Bit
Setting the app to run on Powershell 7 instead of 6 on this thread
Use: Import-Module AzureAD -UseWindowsPowerShell
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"
I am trying to use an output variable from a powershell script. I'm using Devops online using the classic UI and tried both powershell 4.* and Powershell 5.* tasks in a release pipeline.
I am using a self-hosted agent that is working and doing lots of other build and release powershell stuff just fine. Azure Powershell modules version 3.5.0 (there is a reason for not using 4.x right now).
To simplify it, here is my test inline script in total...:
Write-Host '##vso[task.setvariable variable=MobileAppInsightsKey;isOutput=true;]thisisthekey'
Write-Host "This is host"
Write-Output '##vso[task.setvariable variable=MobileAppInsightsKey;isOutput=true;]thisisthekey'
Write-Output "This is output"
Here is the output from the Azure powershell task. (4.*)
2020-07-01T00:06:57.2970494Z ##[section]Starting: Azure PowerShell script: InlineScript
2020-07-01T00:06:57.3335882Z
==============================================================================
2020-07-01T00:06:57.3336692Z Task : Azure PowerShell
2020-07-01T00:06:57.3337292Z Description : Run a PowerShell script within an Azure environment
2020-07-01T00:06:57.3337566Z Version : 4.171.1
2020-07-01T00:06:57.3338039Z Author : Microsoft Corporation
2020-07-01T00:06:57.3338575Z Help : https://aka.ms/azurepowershelltroubleshooting
2020-07-01T00:06:57.3338930Z
==============================================================================
2020-07-01T00:06:58.5902105Z ## Validating Inputs
2020-07-01T00:06:58.5915067Z ## Validating Inputs Complete
2020-07-01T00:06:58.5924850Z ## Initializing Az module
2020-07-01T00:06:59.0747435Z ##[command]Import-Module -Name C:\Program
Files\WindowsPowerShell\Modules\Az.Accounts\1.9.0\Az.Accounts.psd1 -Global
2020-07-01T00:07:00.0802372Z ##[command]Clear-AzContext -Scope Process
2020-07-01T00:07:01.5597330Z ##[command]Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
2020-07-01T00:07:01.9691282Z ##[command]Connect-AzAccount -Identity #processScope
2020-07-01T00:07:03.1860248Z ##[command] Set-AzContext -SubscriptionId 5ec8ec06-XXXX-XXXX-XXXX- c0ff86c50e4 -TenantId ***
2020-07-01T00:07:03.9196710Z ## Az module initialization Complete
2020-07-01T00:07:03.9203692Z ## Beginning Script Execution
2020-07-01T00:07:03.9674782Z ##[command]& 'C:\DevOps\_work\_temp\1b1b130b-4306-448b-b4b2-e7daefc2382e.ps1'
2020-07-01T00:07:03.9974844Z This is host
2020-07-01T00:07:04.0101140Z This is output
2020-07-01T00:07:04.0517610Z ##[command]Disconnect-AzAccount -Scope Process -ErrorAction Stop
2020-07-01T00:07:04.4795714Z ##[command]Clear-AzContext -Scope Process -ErrorAction Stop
2020-07-01T00:07:04.9468120Z ## Script Execution Complete
2020-07-01T00:07:04.9857991Z ##[section]Finishing: Azure PowerShell script: InlineScript
Note that "This is Host" and "This is Output" both display but the "##vso[...." does not.
Also the MobileAppInsightsKey I am trying to read in a subsequent step is empty (uninitialized).
Hopefully someone can point me in the right direction.
Thanks, Mark.
And to make a clear description about this issue:
To define a job-scoped variable in your scenario, we don't need to add isOutput=true;
1.For job-scoped variable(Variable is only valid in current job):
Write-Host '##vso[task.setvariable variable=MobileAppInsightsKey]thisisthekey' is enough. And we can output its value via format $(MobileAppInsightsKey) in CMD task.
2.For multi-job output variable(Variable is valid in multi-job):
We should use Write-Host '##vso[task.setvariable variable=MobileAppInsightsKey;isOutput=true;]thisisthekey'.
In current job: You can use $(referencename.variablename) to get its value. (Support classic pipeline and yaml pipeline)
In subsequent jobs: Use below format to access the variable, and this format only supports yaml pipeline!!!
- job: B
dependsOn: A
pool:
vmImage: 'ubuntu-16.04'
variables:
myVarFromJobA: $[ dependencies.A.outputs['setvarStep.myOutputVar'] ] # map in the variable
# remember, expressions require single quotes
steps:
- script: echo $(myVarFromJobA)
name: echovar
So for your scenario in which you want to access the variable in same job, just remove the isOutput=true;(it's not necessary). Or use $(referencename.variablename) format if you add isOutput=true; in the statement. (Not necessary, not recommended, but it should also work for current job)
In addition:
Details about $(referencename.variablename) format.
For Classic pipeline:(Set name as Test in Powershell task)
$(Test.MobileAppInsightsKey) represents the value of the variable.
For yaml pipeline:
- powershell: echo "##vso[task.setvariable variable=myOutputVar;isOutput=true]this is the value"
name: Test
- script: echo $(Test.myOutputVar)
More messing around and I made it work. The answer goes against everything I have read both in docs and on SO.
If I don't use the
isOutput=true;
then it works.
I don't know why but happy to be educated.
Thx, Mark.
Currently I am using this Powershell script which runs before deployment script.
$Password=Convertto-SecureString -String ${bamboo.deploy.password} -AsPlainText -force
$Credentials=New-object System.Management.Automation.PSCredential ${bamboo.deploy.username},$Password
Enter-PSSession -ComputerName ${Server} -Credential $Credentials
Invoke-Command -ScriptBlock {start cmd;cd C:\Windows\System32\inetsrv;appcmd stop apppool /apppool.name:"${app_pool_name}"}
But it gives the following error:
The term 'appcmd' 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.
I have also tried using the Stop-WebAppPool cmdlet. It also gave an error saying Stop-WebAppPool is not recognized as the name of any cmdlet. I have also tried Import-Module WebAdministration before Stop-WebAppPool cmdlet. It also was not successful.
Edit: When I use the same script from my localhost, it works successfully. When I use this script on BAMBOO, it gives the above mentioned error. Is it possible that the WebAdministration Module is not installed on the agent's environment or Bamboo server?
Make sure you enabled IIS Management Scripts and Tools feature of iis.
you could try these steps:
1. Open Turn Windows features on or off.
Enable IIS Management Scripts and Tools under “Internet Information Services” => “Web Management Tools”.
We will see the appcmd.exe in C:\Windows\System32\inetsrv folder then.
Add C:\Windows\System32\inetsrv to PATH system 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!