How do i prevent root-site deployments in bamboo from failing when IIS is already stopped - bamboo

I am deploying root-site deployments and it keeps failing whenever it seems that IIS is stopped. Below is the error i am getting from the failed log in bamboo.
VERBOSE: Performing action iisreset /Stop on web4.testweb.******.com
C:\bambooscripts\ClusterAwareDeploy-RootSiteAndComDependencies.v2.ps1 : Aborting due to an error!
At D:\AtlassianData\bamboo-agent2-home\temp\4489217-4554753-124649565-ScriptBuildTask-17453259024217579627.ps1:23 char:6
+ "# | c:\bambooscripts\ClusterAwareDeploy-RootSiteAndComDependencies.v ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,ClusterAwareDeploy-RootSiteAndComDependencies.v2.ps1
ErrorDetails :
Exception : System.Management.Automation.RemoteException: The Windows Process Activation Service service is not started.
FullyQualifiedErrorId : NativeCommandError
InvocationInfo : System.Management.Automation.InvocationInfo
PipelineIterationInfo : {}
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
TargetObject : The Windows Process Activation Service service is not started.
Category : NotSpecified
Activity :
Reason : RemoteException
TargetName : The Windows Process Activation Service service is not started.
TargetType : String
The Windows Process Activation Service service is not started.
At C:\bambooscripts\IISFunctions.ps1:319 char:22
+ ... 'Stop' { $result = Invoke-Command -ComputerName $hostName -ErrorAc ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (The Windows Pro...is not started.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : p********db.******.lan
Failing task since return code of [powershell -NonInteractive -ExecutionPolicy bypass -Command D:\AtlassianData\bamboo-agent2-home\temp\4489217-4554753-124649565-ScriptBuildTask-17453259024217579627.ps1] was 1 while expected 0

Related

Unable to connect to SQL server via PowerShell using secure password

I'm trying to connect to SQL server via PowerShell using the below (I'm new to this). I always get the error "login failed" when I use secure password (from Get-Credential or password stored in file). But if I pass the password as plaintext instead of secure string, it connects successfully. Could any one please suggest a method to pass secure password, ideally stored in an external file.
The code I ran and the error is below:
$cred = Get-Credential
$pwd = $cred.Password
$uid = $cred.UserName
$SQLServer = "."
$SQLDBName = "TestDB"
#Initialize connection string
$connString = "Data Source=$SQLServer;Database=$SQLDBName;User ID=$uid;Password=$pwd"
#Create a SQL connection object
$conn = New-Object System.Data.SqlClient.SqlConnection $connString
#Attempt to open the connection
$conn.Open()
if($conn.State -eq "Open")
{
# We have a successful connection here
# Notify of successful connection
Write-Host "Test connection successful"
$conn.Close()
}
Exception calling "Open" with "0" argument(s): "Login failed for user 'TestUser'."
At line:18 char:1
+ $conn.Open()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Further details of error from SQL server:
Login failed for user 'TestUser'. Reason: Password did not match that for the login provided. [CLIENT: <local machine>]
Change this
$pwd = $cred.Password
to this
$pwd = $cred.GetNetworkCredential().Password
However, I would advise against storing a plain text password in memory like this. Your method requires it to--at best--be passed as a parameter in plain text, so you need a better method.
Try using this sqlserver module which supports the -Credential parameter in the Invoke-Sqlcmd function.
I was able to pass secure string as password by adding Integrated Security = True; parameter in connection string.
Thank you.

Errors using Get-AzUserAssignedIdentity on module 0.7.3 and 0.7.2 "Extended 'versions' can't be converted to a boolean"

The following commands were previously working from a local PS session using module Az.ManagedServiceIdentity version 0.7.2, but broke once I updated to 0.7.3, now can't get it to work again even after downgrading the module version. I'd like to use this module from cloud shell ideally but get the same error.
*$uamiRg = (Get-AzResourceGroup -Name *identity*).ResourceGroupName
$uami = Get-AzUserAssignedIdentity -ResourceGroupName $uamiRg -Name "my-uami"*
This used to grab the ID, RG, Name, Location, TenantId, etc. needed to use the User Assigned Managed Identity for assigning Azure Blueprints. Now the 2nd command throws this error:
*Get-AzUserAssignedIdentity : Extended 'versions' can't be converted to a boolean
At line:1 char:1
+ Get-AzUserAssignedIdentity -ResourceGroupName $uamiRg -Verbose -Error ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Get-AzUserAssignedIdentity], CloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ManagedServiceIdentity.UserAssignedIdentities.GetAzureRmUserAssignedIdentityCmdlet*
Debug results:
DEBUG: 5:51:44 AM - GetAzureRmUserAssignedIdentityCmdlet begin processing with ParameterSet 'ResourceGroupParameterSet'.
DEBUG: 5:51:44 AM - using account id ''...
DEBUG: [Common.Authentication]: Authenticating using Account: '', environment: 'AzureCloud', tenant: '***'
DEBUG: [HttpClientOperations]: Adding Header 'Metadata'
DEBUG: Checking Cache request http://localhost:50342/oauth2/token?resource=https%3A%2F%2Fmanagement.core.windows.net%2F&api-version=2018-02-01
DEBUG: Cache Hit
DEBUG: ============================ HTTP REQUEST ============================
HTTP Method:
GET
Absolute Uri:
https://management.azure.com/subscriptions/***/resourceGroups/***Identity-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/my-uami?api-version=2015-08-31-preview
Headers:
x-ms-client-request-id : f0c521dd-5e24-400c-acc5-b47e9f1e75f2
Accept-Language : en-US
Body:
DEBUG: ============================ HTTP RESPONSE ============================
Status Code:
BadRequest
Headers:
Cache-Control : no-cache
Pragma : no-cache
Strict-Transport-Security : max-age=31536000; includeSubDomains
Server : Microsoft-HTTPAPI/2.0
x-ms-ratelimit-remaining-subscription-reads: 11997
x-ms-request-id : 8164b0a7-a810-4cb0-b5c1-29484e924c3f
x-ms-correlation-request-id : 8164b0a7-a810-4cb0-b5c1-29484e924c3f
x-ms-routing-request-id : EASTUS:20200405T055145Z:8164b0a7-a810-4cb0-b5c1-29484e924c3f
X-Content-Type-Options : nosniff
Date : Sun, 05 Apr 2020 05:51:44 GMT
Body:
{
"error": {
"code": "BadRequest",
"message": "Extended 'versions' can't be converted to a boolean"
}
}
Get-AzUserAssignedIdentity: Extended 'versions' can't be converted to a boolean
DEBUG: AzureQoSEvent: CommandName - Get-AzUserAssignedIdentity; IsSuccess - False; Duration - 00:00:00.2875296;; Exception - Microsoft.Rest.Azure.CloudException: Extended 'versions' can't be converted to a boolean
at Microsoft.Azure.Management.ManagedServiceIdentity.UserAssignedIdentitiesOperations.GetWithHttpMessagesAsync(String resourceGroupName, String resourceName, Dictionary2 customHeaders, CancellationToken cancellationToken)
at Microsoft.Azure.Commands.ManagedServiceIdentity.UserAssignedIdentities.GetAzureRmUserAssignedIdentityCmdlet.ExecuteCmdlet()
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.<>c__31.b__3_0(T c)
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet, Action`1 executor)
at Microsoft.WindowsAzure.Commands.Utilities.Common.CmdletExtensions.ExecuteSynchronouslyOrAsJob[T](T cmdlet)
at Microsoft.WindowsAzure.Commands.Utilities.Common.AzurePSCmdlet.ProcessRecord();
DEBUG: Finish sending metric.
DEBUG: 5:51:45 AM - GetAzureRmUserAssignedIdentityCmdlet end processing.
Not sure what caused the issue, but it is not a bug, the 0.7.3 works on my side.
It also works in cloud shell:
To fix the issue, try to update the Az module, then install the Az.ManagedServiceIdentity module.
Update-Module -Name Az -Force
Install-Module -Name Az.ManagedServiceIdentity -RequiredVersion 0.7.3

Diagnose SQL running from Power Shell

I am trying to run a SQL from Power Shell(which is on my windows 7 64 bit desktop) and the remote database host is MS SQL Server 2012.
The code is:
$Server= ".\DB_HOST_NAME"
$Database = "master"
$UserSqlQuery= $("select count(*) from [master].[sys].[some_table]")
# executes a query and populates the $datatable with the data
function ExecuteSqlQuery ($Server, $Database, $SQLQuery) {
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
$Datatable.Load($Reader)
$Connection.Close()
$Datatable
return $Datatable
}
# declaration not necessary, but good practice
$resultsDataTable = New-Object System.Data.DataTable
$resultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery
Write-Host "Statistic: " $resultsDataTable
Write-Host "Message: Transaction Delay is " $resultsDataTable.Rows.Count
When I run this from Windows PowerShell, I get following errors:
Exception calling "Open" with "0" argument(s): "A network-related or
instance-specific error occurred while establishing a connection to
SQL Server. The server was not found or was not accessible. Verify
that the instance name is correct and that SQL Server is configured to
allow remote connections. (provider: SQL Network Interfaces, error: 26
- Error Locating Server/Instance Specified)" At H:\test2.ps1:11 char:5
+ $Connection.Open()
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Exception calling "ExecuteReader" with "0" argument(s): "ExecuteReader
requires an open and available Connection. The connection's current
state is closed." At H:\test2.ps1:15 char:5
+ $Reader = $Command.ExecuteReader()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : InvalidOperationException
Exception calling "Load" with "1" argument(s): "Value cannot be null.
Parameter name: dataReader" At H:\test2.ps1:16 char:5
+ $Datatable.Load($Reader)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
So the first error is at $Connection.Open() but I don't know anything about power shell to figure out what is wrong. I have tried running the same SQL on the same DB host and it does return a number.
Can I get some help to know what am I doing wrong here?
This code:
$Server= ".\DB_HOST_NAME"
should be:
$Server= "DB_HOST_NAME"
The specification ".\DB_HOST_NAME" is interpreted as a named instance (DB_HOST_NAME) running on your local box.

powershell https://outlook.office365.com/api/v1.0/me/messages

I had the below Powershell working perfectly until last November the 1st.
$url = "https://outlook.office365.com/api/v1.0/me/messages"
$date = Get-Date -Format "yyyy-MM-d"
## Get all messages that have attachments where received date is greater than $date
$messageQuery = "" + $url + "?`$select=Id&`$filter=HasAttachments eq true and DateTimeReceived ge " + $date
$messages = Invoke-RestMethod $messageQuery -Credential $cred
I get the below error:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At G:\Powell\AutoetForO.ps1:23 char:13
+ $messages = Invoke-RestMethod $messageQuery -Credential $cred
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Per my investigation; I know its not credential issues; I think they changed their API.
Running the same script with Fiddler capturing traffic I found the body of the error response was:
92
{"error":{"code":"RequestBroker-ParseUri","message":"Syntax error at position 54 in 'HasAttachments eq true and DateTimeReceived ge 2017-01-5'."}}
0
The date looked like the problem. Changing your second line to the following fixed the problem:
$date = Get-Date -Format "yyyy-MM-dd"

SETSPN Error: Ldap Error(0x1 -- Operations Error): ldap_get_next_page_s

I am getting an error and I don't understand why? I have googled and looked as much as I can and still do not have a clear answer. Here is what I am fast with.
Checking domain DC=corp,DC=local
Ldap Error(0x1 -- Operations Error): ldap_get_next_page_s
+ CategoryInfo : NotSpecified: (Ldap Error(0x1 ...get_next_page_s:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : computer01.corp.local
Error occured when searching for existing SPN: 0x00000001
Checking domain DC=corp,DC=local
Ldap Error(0x1 -- Operations Error): ldap_get_next_page_s
+ CategoryInfo : NotSpecified: (Ldap Error(0x1 ...get_next_page_s:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : computer01.corp.local
Error occured when searching for existing SPN: 0x00000001
This is the command I am running
$comp = "computer01.corp.local"
Invoke-Command -ComputerName $comp -ScriptBlock {
Invoke-Expression "SETSPN -S MSSQLSvc/$comp:1433 CORP\user.name"
Invoke-Expression "SETSPN -S MSSQLSvc/$comp CORP\user.name"
}
The variable $comp does not exist in your remote session, ie it is $null inside your -ScriptBlock{..} statement. Try this:
$comp = "computer01.corp.local"
Invoke-Command -ComputerName $comp -ScriptBlock {
param($comp)
Invoke-Expression "SETSPN -S MSSQLSvc/$comp:1433 CORP\user.name"
Invoke-Expression "SETSPN -S MSSQLSvc/$comp CORP\user.name"
} -ArgumentList $comp
You can add Write-Host "Working on computer:$comp" below param($comp) to verify you passed variable $comp correctly.