How to enable SQL Filestream using Powershell - sql

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

Related

Cannot Install a Managed Service Account via DevOps

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.

Using sql query on ssis server sql job using powershell

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"

Add-AzTableRow command is not available in Azure Cloud Shell

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}

Run SQL by Powershell if exist file in folder

Good day
Iam looking way how to run sql command only if exist file/s in specific folder ? I read lot of staff but i cant not fit my skript . I do not want do make SSIS I want do to in Powershell.
Then I will put into MSQL Job Agent powershell script wchich will run every hour . If this Job find .csv file /s then will start other Job.
Thank you for opinion.
$SourceFile = "C:\Import\FOLDER\report\Old\test\*.csv"
Action = "Invoke-Sqlcmd -ServerInstance "100.000.000.001" -Query "USE msdb ; EXEC dbo.sp_start_job N'MSSQLJOBNAME' ;"
if(Test-Path -Path $SourceFile)
{
"Invoke-Sqlcmd -ServerInstance "100.000.000.001" -Query "USE msdb ; EXEC dbo.sp_start_job N'MSSQLJOBNAME' ;"
}
specifying the folder and *.csv in a variable is not enough; you have to get the filelist.
for running the sql command in the database msdb I added the parameter -Database
$SourceFilesArray = Get-ChildItem -Path "C:\Import\FOLDER\report\Old\test\" -Filter "*.csv"
if($SourceFilesArray) {
# $SourceFilesArray is not empty/contains list of specified files
Invoke-Sqlcmd -ServerInstance "100.000.000.001" -Database "msdb" -Query "EXEC dbo.sp_start_job 'MSSQLJOBNAME'"
} else {
# run this if $SourceFilesArray is empty/no files found
Invoke-Sqlcmd -ServerInstance "100.000.000.001" -Database "msdb" -Query "EXEC dbo.sp_start_job 'MSSQLJOBNAME'"
}

Get-Content -Raw parameter error

I have a PowerShell script that would recursively loop a dir and subdir and run all SQL files inside of it and log the execution in .log files 1 for success and 1 for exceptions. The PowerShell script does what its supposed to do but in the cmd window, I see this error:
Get-Content : A parameter cannot be found that matches parameter name 'Raw'
from this line
$query = Get-Content -Path $_.FullName -Raw
This statement runs within a loop, so FullName changes per iteration. This is the version I use.
Name : Windows PowerShell ISE Host
Version : 5.0.10586.117
Sample script goes below:
Get-ChildItem $ScriptFolder -Recurse -Exclude "*Archive*" -Filter *.sql |
sort Directory |
ForEach-Object {
$query = Get-Content -Path $_.FullName -Raw
$result = SQLCMD -S $FullDBServer -E -I -Q $query -d $Database
Any thoughts?
The -Raw parameter of Get-Content was introduced in PS3.
To get file contents in one string there are several methods.
The fastest method that works in any PS version:
$text = [IO.File]::ReadAllText('c:\path\file.ext')
The 2 times slower method for PS3+:
$text = Get-Content 'c:\path\file.ext' -Raw
The 100 times slower PS2-compatible alternative:
$text = Get-Content 'c:\path\file.ext' | Out-String
The 30 times slower PS2-compatible alternative:
$text = Get-Content 'c:\path\file.ext' -ReadCount 1000 | Out-String
I've experienced this error in ps v 5 when the -path parameter wasn't actually a path.
Try adding Write-Host $_.fullname above the line throwing the error to make sure $_.fullname is actually what you think it is.
You're using PowerShell v2 or earlier. The parameter -Raw was introduced with PowerShell v3. Either upgrade PowerShell or pipe the output of Get-Content through Out-String:
$query = Get-Content -Path $_.FullName | Out-String
You should also be able to run the files directly with sqlcmd (i.e. without reading their content and passing that to the command):
$result = SQLCMD -S $FullDBServer -E -I -i $_.FullName -d $Database