Quantcast
Channel: SQLServerCentral » Programming » Powershell » Latest topics
Viewing all 467 articles
Browse latest View live

Deleting reports and un used data sources by powershell

$
0
0
Hi Friends,I have a task to delete reports in share point. I get the information of those reports that needs to be deleted in a file and I have to delete them all. And also I have to delete all the un used data sources in the share point. I heard from one of my colleague that it s possible through powershell script. Can some one please help me on this?Any suggestions would be appreciated. Please help me , friends

connect to sql server with AD user object

$
0
0
Is there some way I can connect to a SQL Server using an Active Directory user object? Something along the lines of this pseudocode:$User = get-aduser "domain\Some_user_that_isn't_me"$Connection = new-object sqlserver.connection $User$Connection.ConnectionString = "server=myserver; integratedsecuriry=$True"$Connection.Connect()Thanks!

Get-ADGroup with wildcards

$
0
0
Using the Quest AD cmdlets, this easily returns all groups with underscores around the $Code.Get-QADGroup "*`_$Code`_*" How can this be done with Get-ADGroup (ie, not using the Quest cmdlets, which not everyone has).The -Filter parm only accepts the * wildcard. Help says to use LDAPFilter parm, but I can't seem to get it right:Get-ADGroup -LDAPFilter {(name="*_$Code_*")} is not workingThanks!

SQL Agent Job - Powerhell Script With Parameters Failing

$
0
0
I have a PS script that has three parameters: -ConfigurationGroup "$ConfigurationGroup" -PolicyCategoryFilter "$PolicyCategoryFilter" -EvalMode "$EvalMode".Some of these values can have spaces in them hence the quotes around the params.When I run this in PS ISE it completes successfully.However when I then try and run it via a SQL Agent job either using Type: Powershell or Operating System (CmdExec) it fails with:Cannot convert the "DBA - DB Config" value of type "System.String" to type "System.Management.Automation.ParameterAttribute".It seems it can handle the spaces in ISE but not SQL Agent job.Any ideas? Do I have to use a different syntax?

powershell WMI error: "Could not obtain SQL Server Service information. An attempt to connect to WMI ... failed with the following error: access is denied."

$
0
0
I get the following error when I launch powershell from SSMS, after right-clicking on a remote SQL instance and choosing "Start powershell":[quote]Warning: Could not obtain SQL Server Service information. An attempt to connect to WMI on server1 failed with the following error: access is denied.[/quote]How can I fix this?

Determining if a server is clustered or stand-alone

$
0
0
I'm in the process of writing a powershell script to inventory my SQL Server environment. In collecting the server information, I'd like to grab the physical hostnames that make up any clustered environments. I know I can use $nodes=get-clusternode -Cluster SERVERNAME |select nameto get the physical servers in the cluster, but if I run that on a non-clustered server, I get an error, obviously. So, can someone recommend a good way to determine whether the SERVERNAME I've connected to is a cluster resource group or a physical stand-alone server?

Need help to get file count from remote server directory using powershell

$
0
0
Hi, I need help to get file count from the directory "T:/System Volume information" from a remoter serverI'm trying to run below PSEXEC command but its failing.[code="plain"]psexec \\MYSERVER28 -S cmd DIR "T:\System Volume Information" /b/a-d | find /v /c "::"[/code]how can i achieve the file count on remote server.

Code not working

$
0
0
This used to work for me (with my own servers and dbs, and some other customizations) in PowerGUI.Now, the TransferData() method throws "Exception calling "TransferData" with "0" argument(s): "Object reference not set to an instance of an object."." This happens with the exact code below.When this same script is run from my SQL Servers as a CmdExec job, it succeeds.What am I missing?My local machine is running Powershell v4.Thanks![code="other"]#Connect to the local, default instance of SQL Server.#Get a server object which corresponds to the default instance$srv = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Server#Reference the AdventureWorks2012 database.$db = $srv.Databases["AdventureWorks2012"]#Create a database to hold the copy of AdventureWorks$dbCopy = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Database -argumentlist $srv, "AdventureWorksCopy"$dbCopy.Create()#Define a Transfer object and set the required options and properties.$xfr = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Transfer -argumentlist $db#Set this objects properties$xfr.CopyAllTables = $true$xfr.Options.WithDependencies = $true$xfr.Options.ContinueScriptingOnError = $true$xfr.DestinationDatabase = "AdventureWorksCopy"$xfr.DestinationServer = $srv.Name$xfr.DestinationLoginSecure = $true$xfr.CopySchema = $true"Scripting Data Transfer"#Script the transfer. Alternatively perform immediate data transfer with TransferData method.#$xfr.ScriptTransfer()$xfr.TransferData()[/code]

Using PS to configure SSRS 2012

$
0
0
Hello,I have had a look around the forums for an existing thread on this subject but have not come across one. I have been tasked with writing a Powershell script to automate the configuration of SSRS 2012, I need to automate it as I will need to run the script multiple times on a lot of servers for the foreseeable future. SSRS 2012 will be installed already, but not configured, or configured in native mode with defaults, I will need to change the URL's of the report server and the reports, I will need to change the service account, the execution account, create a folder for the encryption key backup, then actually back the key up. And anything else that can be configured. At the moment I believe I do not have to worry about setting it up Sharepoint mode.At first I thought I'd be looking at functions, but I think I will need to enter the information as parameters for the scripts. So a bit like a stored procedure with a few parameters that follow.So here is the thing, I don't know any Powershell yet, this is my first of many adventures with it, what I need is someone to just tell me what it is I'll need to use, then point me in the direction of a place I can learn what I need to use to get the job done. I have about 2/3 weeks. I am looking at the SQL server Central Stairway series, which I will complete, but I think it will take me too long to get to where I need to be, and I'll run out of time.I have to say I am really looking forward to learning Powershell.Of course, if anyone has any other handy tidbits of advice, I'd love to hear from them.Thank you for any help. Much appreciated.Regards,D.

Powershell Permissions

$
0
0
I am attempting to run a Powershell step through SQL Agent.The owner of the job can execute Powershell from outside SQL Agent. I have created a credential and given it proxies for Powershell, SSIS Package Execution, and CmdExeI'm still getting the following error[b]Executed as user: [RedactedAccount]. The process could not be created for step 4 of job 0x6F48FE630C999B4081180F07C7D2C843 (reason: A required privilege is not held by the client). The step failed.[/b]What am I doing wrong?

SqlBulkCopy.WriteToServer not able to convert empty values to null in destination column

$
0
0
[u][b]Background:[/b][/u]I am trying to insert csv data into sql table using Powershell script(Import-CSVtoSQL.ps1) given on following web page:https://gallery.technet.microsoft.com/scriptcenter/Import-Large-CSVs-into-SQL-216223d9[u][b]Issue:[/b][/u]This script is failing when I try to import null values (The null value is represented as blank in CSV file) from CSV file to datetime type column in a sql table. it's throwing following error:[b][u]Error Message:[/u][/b] System.InvalidOperationException: The given value of type String from the data source cannot be converted to type datetime of the specified target column. ---> System.FormatException: Failed to convert parameter value from a String to a DateTime. ---> System.FormatException: String was not recognized as a valid DateTime. at System.DateTime.Parse(String s, IFormatProvider provider) at System.Convert.ToDateTime(String value, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming) --- End of inner exception stack trace --- at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming) at System.Data.SqlClient.SqlBulkCopy.ConvertValue(Object value, _SqlMetaData metadata, Boolean isNull, Boolean& isSqlType, Boolean& coercedToDataFeed) --- End of inner exception stack trace ---

move files not working using Powershell in SQL Agent Job

$
0
0
I have this simple move files command that works fine in powershell prompt. However, if I schedule a SQL Agent job (on SQL Server 2014), the job fails to copy the files (the job itself did completed, not failed). The message is "Cannot move the item because the source and destination paths did not resolve to the same provider". I am pretty sure the job has the correct credential that can write to the remote path and I use "PowerShell" as the job type. move-item c:\temp\*.txt "\\www.abc.com\daily report"Any ideas? Thanks.

Loop thru SQL files, second file doesnt run when results are aliased

$
0
0
I have a script that loops through *.sql files in a folder. It's OK if I do not alias the column result but will only run the first SQL file if I do use aliases.[code="plain"]#Loop through the .sql files and run themforeach ($filename in get-childitem -path $FolderPath -filter "*.sql" |sort-object) { invoke-sqlcmd –ServerInstance $SQLServer -InputFile $filename.fullname } [/code]Two files are currently in the folder. The results of ALIASES:[code="plain"]You------- Hello World[/code]The first SQL file:[code="plain"]select 'Hello World' as [You][/code]The second:[code="plain"]select 'Hello You' as [Me][/code]This is SUCCESSFUL when columns [b]not[/b] aliased:[code="plain"]Column1 ------- Hello World Hello You [/code]The first SQL file:[code="plain"]select 'Hello World'[/code]The second:[code="plain"]select 'Hello You'[/code]

Need help to run a Powershell from SQL Server

$
0
0
Hi All,I have a requirement to kick off a[b] Powershell script[/b] and pass a [b].txt[/b] file with it.it works fine in [b]Powershell ISE[/b] but I'm not able to run in from [b]SQL Server[/b].[code="xml"]Get-Content D:\Temp\ServerList.txt | D:\Temp\StopDisableWindowsUpdateService.ps1[/code]

Cant work out why this bit of PS isnt working

$
0
0
hello,I am following an online tutorial to help me learn powershell. It's pretty good but I have a piece of code from it, and although typed exactly correct, is not working and I cant figure out why, would love to know...$instance = $args[0][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null$ServerInstance = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $instanceWrite-Host "Name: " $ServerInstance.NameWrite-Host "Edition: " $ServerInstance.EditionWrite-Host "Version: " $ServerInstance.VersionWrite-Host "ProductLevel: " $ServerInstance.ProductLevel...It returns the name, but nothing else.Thank you.Regards,D.PS: Does anybody know of a good resource that will teach me to create SQL connection strings to SQL from a powershell console that can be used in a script, please? Thank you.

POwershell script

$
0
0
I have this powershell script as step 1 in a sql job.[System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources()It creates a text extract with 4 columns as below.ServerName InstanceName IsClustered Version ---------- ------------ ----------- ------- ABCDEFGHI No 10.0.4000.0 ABCDEFGHI MSSQLSERVER2012 No 11.0.3000.0 SFVSDVSDV No 11.0.5058.0 HDDBHDGHH No 10.50.1600.1 I have this powershell script as step 2 in a sql job which is failing to an error stating sysntax issues.$SQL = [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() | ' foreach {"INSERT INTO dbo.FoundSQLServers VALUES ('$($_.ServerName)', '$($_.InstanceName)', '$($_.IsClustered)', '$($_.Version)')" ' >> E:\ServersList.txt }[i]Error message:Date 11/21/2015 1:52:58 AMLog Job History (fgdfb)Step ID 2Server fffffffffJob Name ffffffStep Name ffffDuration 00:00:00MessageUnable to start execution of step 2 (reason: line(2): Syntax error). The step failed.[/i]The above script i supposed to extract data from E:\ServersList.txt and insert into this SQL tableCREATE TABLE [dbo].[FoundSQLServers]( [ServerName] [varchar](128) NULL, [InstanceName] [varchar](128) NULL, [IsClustered] [varchar](3) NULL, [VersionNumber] [varchar](64) NULL)Can someone please help figure this.Thanks

Case Sensitive DB Name problem

$
0
0
I have a powershell script that scales up a SQL Azure database. It uses the cmdlet Get-AzureSqlDatabase.Users can pass in parameters to specify things like DatabaseName.Unfortunately, this parameter is case sensitive and we don't have a consistent naming pattern for our databases.Is there any way to make this case insensitive?[code="other"]$ddw = Get-AzureSqlDatabase -ResourceGroupName $Group -ServerName $ServerName -DatabaseName $DBName[/code]$DBName should be able to be "MyDatabase" or "MYDATABASE" or "Mydatabase" and still retrieve the db information.

servers list in a domain

$
0
0
When I run this script in a SQL job and have the output to a text extract.Script:[System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSourcesThis is what I see as underneath in the text extract.1.How can I not have the 1 empty line in the text extract2.ServerName is the column name..I dont want to show an column name in the text extract3.----------------- <----I do not want this line in the text extractAnd I find empty space after each servername (ABCD,EFGH...)on each line.I do not want this.Empty line---->1ServerName---->2 ---------- ---->3 ABCD empty space EFGH empty space IJKL empty space MNOP empty space QRST empty space My text extract should be a simple text file without the first 3 lines as above.Only the servername should show with no trailing empty spaces after the servernames.ABCDEFGHIJKLMNOPQRSTResponses are appreciated.Thanks

capture invalid connection

$
0
0
Hi How to capture invalid connection with powershell?$conn = "MyServer\InstanceThatDoesNotExist"try { $serverInstance = New-Object Microsoft.SqlServer.Management.Smo.Server ($conn) ; $serverInstance.Databases.Count;}catch { $err = $Error[0].Exception ; write-host "Error caught: " $err.Message ; continue ; } ; I want to capture standard error "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 "

Scripting CDC objects with powershell

$
0
0
For a Long time we have been using the following script to create a Schema only copy of our database for testing [code="other"]$Filepath='C:\Temp\' # local directory to save build-scripts to$DataSource='ServerName' # server name and instance$Database='DatabaseName'# the database to copy from# set "Option Explicit" to catch subtle errorsset-psdebug -strict$ErrorActionPreference = "stop" # you can opt to stagger on, bleeding, if an error occurs# Load SMO assembly, and if we're running SQL 2008 DLLs load the SMOExtended and SQLWMIManagement libraries$ms='Microsoft.SqlServer'$v = [System.Reflection.Assembly]::LoadWithPartialName( "$ms.SMO")if ((($v.FullName.Split(','))[1].Split('='))[1].Split('.')[0] -ne '9') {[System.Reflection.Assembly]::LoadWithPartialName("$ms.SMOExtended") | out-null }$My="$ms.Management.Smo" #$s = new-object ("$My.Server") $DataSourceif ($s.Version -eq $null ){Throw "Can't find the instance $Datasource"}$db= $s.Databases[$Database] if ($db.name -ne $Database){Throw "Can't find the database '$Database' in $Datasource"};$transfer = new-object ("$My.Transfer") $db$CreationScriptOptions = new-object ("$My.ScriptingOptions") $CreationScriptOptions.ExtendedProperties= $true # yes, we want these$CreationScriptOptions.DRIAll= $true # and all the constraints $CreationScriptOptions.Indexes= $true # Yup, these would be nice$CreationScriptOptions.Triggers= $true # This should be included when scripting a database$CreationScriptOptions.ScriptBatchTerminator = $true # this only goes to the file$CreationScriptOptions.IncludeHeaders = $true; # of course$CreationScriptOptions.ToFileOnly = $true #no need of string output as well$CreationScriptOptions.IncludeIfNotExists = $true # not necessary but it means the script can be more versatile$CreationScriptOptions.Filename = "$($FilePath)\$($Database)_Build.sql"; $transfer = new-object ("$My.Transfer") $s.Databases[$Database]$transfer.options=$CreationScriptOptions # tell the transfer object of our preferences$transfer.ScriptTransfer()"All done"[/code]which we copied from [url]https://www.simple-talk.com/sql/database-administration/automated-script-generation-with-powershell-and-smo/[/url]all went very well until we introduced CDC and built some views that look at the CDC tables.The powershell script will create the script for the view, but ignores the CDC table it Looks at. (I'm guessing because it thinks they are sys.table and handled by the database).My question isCan CDC tables be scripted through powershell / smo?Many thanks in advanceIan
Viewing all 467 articles
Browse latest View live