I have a problem i have tried to debug all day now and unable to find a solution.
The Problem
I am trying to automate SQL server builds within a pipeline. I am trying to create and install MSA's. I can add the computer service accounts into AD with the first two commands but when i try to install it on the SQL server, this fails.
My Script so far:
[CmdletBinding()]
param (
[parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$MSA,
[parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$server,
[parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$agentaccount,
[parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
[string]$agentpass
)
# Create Creds
[string]$userName = $agentaccount
[string]$userPassword = $agentpass
[SecureString]$secureString = $userPassword | ConvertTo-SecureString -AsPlainText -Force
[PSCredential]$credentialObject = New-Object System.Management.Automation.PSCredential -ArgumentList $userName, $secureString
#Create SVS account and add it to the computer object
$SVS = $MSA + "SVS"
try {
New-ADServiceAccount -name $SVS -Enabled $true -RestrictToSingleComputer -Credential $credentialObject
Add-ADComputerServiceAccount -Identity $server -ServiceAccount $SVS -Credential $credentialObject
Write-Host "$SVS Created"
}
catch {
Write-Host "$SVS already exists"
}
...
#Add the new MSA accounts to the "SQL Server account permissions" group
Add-ADGroupMember "SQL Servers" ($SVS + '$') -Credential $credentialObject
#Create powershell script to install all service accounts onto the required server
#Script Block to run
Add-WindowsFeature RSAT-AD-PowerShell
Import-Module ActiveDirectory -Force
Install-ADServiceAccount -Identity $SVS
...
When i run Install-AdServiceAccount -Identity $SVS the Error output is:
install-adserviceaccount [serviceaccount]
install-adserviceaccount : Cannot install service account. Error Message: 'An unspecified error has occurred'.
At line:1 char:1
+ install-adserviceaccount [serviceaccount]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: ([serviceaccount]:String) [Install-ADServiceAccount], ADException
+ FullyQualifiedErrorId : InstallADServiceAccount:PerformOperation:InstallServiceAcccountFailure,Microsoft.ActiveD
irectory.Management.Commands.InstallADServiceAccount
Tried so far
Ran a powershell task within a Deployment group with the SQL server being a member
Ran a remote target powershell task via an agent to try an invoke the script as an admin.
Created the script locally on the SQL server and invoked the script via a remote target powershell task above too.
** Issue **
When i run this manually on the server when in an Administrator Powershell, the install-adserviceaccount works fine. I guess my question is, is there anyway i can get powershell running as an administrator user from within the pipeline?
Or does anyone have any idea how to solve this.
Thanks.
Related
Its and windows machine and trying to install Sql Server(unattended) using powershell
Write-Host "`nStarting the install of SQL Server" -ForegroundColor Green
[string]$userName = 'domain\username'
[string]$userPassword = 'xyz'
[securestring]$secStringPassword = ConvertTo-SecureString $userPassword -AsPlainText -Force
[pscredential]$credObject = New-Object System.Management.Automation.PSCredential ($userName, $secStringPassword)
Start-Process -Filepath "$driveLetter\setup.exe" -ArgumentList "/ConfigurationFile=`"$temp_file_location`"" -Credential $credObject -NoNewWindow -Wait -RedirectStandardOutput $standardOutputFile -RedirectStandardError $errorOutputFile
ERROR:
PS C:\Windows\system32> C:\Users\manish\Desktop\custommain.ps1
domain
eu-west-1
fetching the password from parameter stores
Cleaning the outputfile error
finding and replacing the domains and secrets
writting the content of ini into temp file C:\xyz-softwares\ms-sql-server\scripts\batch-files\temp_ConfigurationFile.ini
Mounting SQL Server Image
Getting Disk drive of the mounted image
Starting the install of SQL Server
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
At C:\xyz-softwares\ms-sql-server\scripts\powershell\ms-sqlserver-installation.ps1:65 char:2
+ Start-Process -Filepath "$driveLetter\setup.exe" -ArgumentList "/ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
SQL Installation Failed Installation with exit code
SQL Installation Failed Installation with exit code
At C:\xyz-softwares\ms-sql-server\scripts\powershell\ms-sqlserver-installation.ps1:72 char:9
+ throw $error_message
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (SQL Installatio... with exit code:String) [], RuntimeException
+ FullyQualifiedErrorId : SQL Installation Failed Installation with exit code
PS C:\Windows\system32>
I have tried with powershell with domain credentials.
Although i have exe file and windows machine is connected with domain
Tried to start process command with domain credetials.
I want to invoke a sql query/SP on sql job in a ssis server using a powershell script but I don't know how to do that. I've used powershell to run sql queries on sql database but not jobs on ssis. Here is what I have till now-
$ssisServer = New-Object -TypeName Microsoft.SQLServer.Management.Smo.Server($name_of_server)
$IntegrationServices = New-Object "Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices" $ssisServer
$catalog = $IntegrationServices.Catalogs[$catalog]
$folder = $catalog.Folders[$folder]
$project = $folder.Projects[$project]
$sqlJob = $ssisServer.JobServer.Jobs[$existing_job_name]
query= " some sql query "
if ($sqlJob) {
$sqlJob.CurrentRunStatus()
# here I need to run a query on the job
}
The query could be to get details of the job or perform some action on it. Also is this enough as we are just giving the server name here $sqlJob = $ssisServer.JobServer.Jobs[$existing_job_name] to get the job which in a particular folder->project->job? I couldn't try this yet and haven't found much resources on it. Please give me some help to work with.
I didn't work with the SSIS server. But the principle of running SQL queries from SQL is pretty simple.
You should have proper module or you can use snapin of SQL.
I will continue from the second one.
# If you have an SQL server on your server, so this is the possible path where they can be.
$PossiblePaths = 'C:\Program Files\Microsoft SQL Server','C:\Program Files (x86)\Microsoft SQL Server'
# Lets check where we have PSProvider.dll and PSSnapins.dll
$PossiblePaths | ForEach-Object {
Test-Path -Path $_
{
$SQLPSProvider = (Get-ChildItem -Filter "Microsoft.SqlServer.Management.PSProvider.dll" -Path $_ -Recurse).FullName
$SQLPSSnapIn = (Get-ChildItem -Filter "Microsoft.SqlServer.Management.PSSnapins.dll" -Path $_ -Recurse).FullName
}
}
# Lets find Install Utility to add them with it.
$InstallUtil = (Get-ChildItem -Filter "InstallUtil.exe" -Path "$env:windir\Microsoft.NET\Framework64\v2.0*" -Recurse).FullName
if (($null -eq $SQLPSProvider) -or ($null -eq $SQLPSSnapIn))
{
Write-Host "Sorry, SQL PowerShell SnapIn or PowerShell Provider not found." -ForegroundColor Red
}
else
{
# Adding them to our system.
Start-Process -FilePath $InstallUtil -ArgumentList "-i $SQLPSProvider"
Start-Process -FilePath $InstallUtil -ArgumentList "-i $SQLPSSnapIn"
}
# Now they should be in the system and we can add them to our PowerShell session.
Add-PSSnapin -Name SqlServerCmdletSnapin100
Add-PSSnapin -Name SqlServerProviderSnapin100
# Now we should have Invoke-Sqlcmd like if we had SQLServer module.
$SQLServer = "SQL2012"
$SQLInstance = "JustForExample"
$ServerInstance = $SQLServer + '\' + $SQLInstance
# So you typing query for example like attaching DB.
$Query = "CREATE DATABASE ExamleDB ON (FILENAME = `'C:\DBs\ExamleDB.mdf`'), (FILENAME = `'C:\DBs\ExamleDB_log.ldf`') FOR ATTACH"
# And then executing it with Invoke-Sqlcmd like that.
Invoke-Sqlcmd -ServerInstance $ServerInstance -Username 'sa' -Password 'Abcde12345' -Query "Query"
I'm trying to insert new row in my table storage by using Azure Cloud Shell but I'm facing below exception. So let me know any other command that we need to use to insert.
Blockquote
Add-AzTableRow: The term 'Add-AzTableRow' 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.
Blockquote
Below are the command:
$partitionKey1 = "partition1"
$partitionKey2 = "partition2"
Add-AzTableRow `
-table $cloudTable `
-partitionKey $partitionKey1 `
-rowKey ("CA") -property #{"username"="Chris";"userid"=1}
According to the error, it seems that you do not install the module AzTable. Please run the command Get-InstalledModule to check if you have installed the module.
If you have not installed the module, please run the command Install-Module -Name AzTable -Force to install it.
For example
Install-Module -Name AzTable -Force
Import-Module AzTable
$resourceGroup = "<your group name>"
$storageAccountName ="<your account name>"
$storageAccount=Get-AzStorageAccount -ResourceGroupName $resourceGroup -Name $storageAccountName
$ctx = $storageAccount.Context
$tableName = "<table name>"
$cloudTable = (Get-AzStorageTable –Name $tableName –Context $ctx).CloudTable
$partitionKey1 = "partition1"
Add-AzTableRow -table $cloudTable -partitionKey $partitionKey1 -rowKey ("CA") -property #{"username"="Chris";"userid"=1}
Running this powershell command
Enter-PSSession -ComputerName 192.168.1.184 -Credential Personal
command works fine. The username and password is accepted.
Again, running this command:
Invoke-Command -ComputerName 192.168.1.184 -ScriptBlock { Get-ChildItem C:\ } -credential Personal
Also works fine and it displays the folders in drive C. It also implies that i can login. When i run this command:
gwmi win32_service –credential Personal –computer 192.168.1.184
I get "gwmi : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
So does this:
Copy-Item -Path c:\d\test.txt -Destination \\192.168.1.184\c$\dep\test.txt
I've tried everything i could think of and i still fail. My goal is to copy files to target computers and execute these files. I have about 52 machines and i need to be able to install these programs.
Anyone knows why this isn't working?
I'm spinning up a SQL server ready for deployment. Using AWS userdata, everything is being configured to this stage using PowerShell. However, the database needs to have Filestream enabled at level 2, but I can't find a way to do this using PowerShell or any other command-line utility.
The script I've written for this part is this:
Import-Module SQLPS -DisableNameChecking
$instanceName = $env:COMPUTERNAME
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
$server.Configuration.FilestreamAccessLevel.ConfigValue = 2
$server.Alter()
Set-ExecutionPolicy RemoteSigned -force
Invoke-Sqlcmd "EXEC sp_configure filestream_access_level, 2"
Invoke-Sqlcmd "RECONFIGURE"
Get-Service -Name MSSQLSERVER | Restart-Service -force
$server.Properties | clip
$server.Configuration | clip
import-module SQLPS -DisableNameChecking
But it's not enabling Filestream.
Does anyone have any ideas on how I can get this working?
Posting this as an answer in case the blog goes offline.
This worked for me for SQL Server 2019:
# Enable FILESTREAM
$instance = "MSSQLSERVER"
$wmi = Get-WmiObject -Namespace "ROOT\Microsoft\SqlServer\ComputerManagement15" -Class FilestreamSettings | where {$_.InstanceName -eq $instance}
$wmi.EnableFilestream(3, $instance)
Get-Service -Name $instance | Restart-Service
Set-ExecutionPolicy RemoteSigned
Import-Module "sqlps" -DisableNameChecking
Invoke-Sqlcmd "EXEC sp_configure filestream_access_level, 2"
Invoke-Sqlcmd "RECONFIGURE"
Easiest way is to use DBATOOLS.
Install-Module dbatools -Scope CurrentUser
Enable-DbaFilestream -SqlInstance $env:COMPUTERNAME