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

Powershell drop down list for parameter values.

$
0
0
Hello,I am looking to right a function that will add a sql login to a role. Thing is, when the parameter is entered, I don't want anyone typing anything is because typos are a pain. I have done some research, but they are all form-based.At this stage I'm just wondering if this can be done outside forms?I did write some code, and although it did not raise any errors, I have no idea how to use it, that's if it actually works!![Array]$AddToDBRole = "db_datareader","db_datawriter", "db_owner"Function Return-DropDown {$Script:Choice = $DropDown.SelectedItem.ToString()$Form.Close()}I don't think I'm calling it correctly to get it to actually do anything, or the code is just rubbish. I'd appreciate any pointers. Thank you.Regards,D.

Error in Downloading Report from Local SSRS Server

$
0
0
I am executing this attached code "SampleScript.ps1" to access my SSRS report in my local server and download the report in pdf format in local drive.The error which I am getting is as follows,Exception calling "SetParameters" with "1" argument(s): "The attempt to connect to the report server failed. Checkyour connection information and that the report server is a compatible version."At D:\SalesReport\SampleScript.ps1:61 char:1+ $rv.ServerReport.SetParameters($params)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : MissingEndpointExceptionException calling "Render" with "7" argument(s): "The attempt to connect to the report server failed. Check yourconnection information and that the report server is a compatible version."At D:\SalesReport\SampleScript.ps1:79 char:1+ $bytes = $rv.ServerReport.Render("PDF",+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : MissingEndpointExceptionException calling "Write" with "3" argument(s): "Buffer cannot be null.Parameter name: array"At D:\SalesReport\SampleScript.ps1:92 char:1+ $fileStream.Write($bytes, 0, $bytes.Length)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentNullExceptionCan any one please help me in this. Following is the version that I am using,Powershell: 4.0SQLServer: 2014Thanks in Advance !

Acces Denied

$
0
0
Good day Experts,I am new to powershell and please help me.Where i work we use powershell script in sql server agent job to retrieve information that is hostname and disk drives size and free space from remote computers.All other sites are fine but now i have three sites sitting on a different domain and when i run the job in sql server agent it returns error 'Access denied'Part of the script is as followsGet-WMIObject Win32_LogicalDisk -filter "DriveType=3" -computer $hostname.I was told to try create a credential object by a friend but i am not sure as he is not working with powershell.Thanks in advance!!

Errors while trying to copy files to UNC path using Powershell

$
0
0
Hello experts,I found the promising script below at the following link:[b][url=https://sqlactions.com/2015/03/30/powershell-script-to-manipulate-sql-server-backup-files/]https://sqlactions.com/2015/03/30/powershell-script-to-manipulate-sql-server-backup-files/[/url][u][/u][/b]The purpose of the script is to allow copy of backup files from one SQL Server to another assuming the backups are made by the Ola Hallengren backup tool. The script text below is a little different from what is at the link above because I've been attempting to troubleshoot it for my system. However, I ran into the 3 errors here and was wondering if anyone can help me decipher and fix them:[code](1)The job script encountered the following errors. These errors did not stop the script:A job step received an error at line 45 in a PowerShell script. The corresponding line is ' New-Item -ItemType Dir -Path $PathToCopy -Force'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'SQL Server PowerShell provider error: Object does not support this operation.'(2)A job step received an error at line 48 in a PowerShell script. The corresponding line is ' Copy-Item $FileToCopy $PathToCopy'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'SQL Server PowerShell provider error: Copy-Item is not supported.'(3)A job step received an error at line 52 in a PowerShell script. The corresponding line is ' $RenamedFile = ($DestinationFile.substring(0,$DestinationFile.length-20))+'.bak''. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Exception calling "Substring" with "2" argument(s): "Length cannot be less than zero.Parameter name: length"'[/code][code="other"]<################################################################################# Script Name: CopyLatestBackupandRename.ps1 Author : Prashant Kumar Date : March 29th, 2015 Description: The script is useful for those using Ola Hallengren's backup solution. This script takes SQL Server full backup parent folder as an input, a remote UNC path as another input and copies the latest backup file for each database, renames the backup file to the remote UNC path. This Sample Code is provided for the purpose of illustration only and is notintended to be used in a production environment. THIS SAMPLE CODE AND ANYRELATED INFORMATION ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHEREXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OFMERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.##################################################################################> #Specify Parent folder where Full backup files are originally being taken$SourcePath = 'D:\SQLBackup\InstanceName' #Specify UNC path ot network share where backup files has to be copied$UNCpath = '\\RemoteServer\UNCBackup' #Browse thru subfolders (identical to database names) inside $SourcePath$SubDirs = dir $SourcePath -Recurse | Where-Object {$_.PSIsContainer} | ForEach-Object -Process {$_.FullName} #Browse through each sub-drorectory inside parent folderForEach ($Dirs in $SubDirs) { #List recent file (only one) within sub-directories $RecentFile = dir $Dirs | Where-Object {!$_.PSIsContainer} | Sort-Object {$_.LastWriteTime} -Descending | Select-Object -First 1 #Perform operation on each file (listed above) one-by-one ForEach ($File in $RecentFile) { $FilePath = $File.DirectoryName $FileName = $File.Name $FileToCopy=$FilePath+'\'+$FileName $PathToCopy=($filepath -replace [regex]::Escape($SourcePath), $UNCpath)+'\' #Forecfully create the desired directory structure at destination if one doesn't exist New-Item -ItemType Dir -Path $PathToCopy -Force #Copy the backup file Copy-Item $FileToCopy $PathToCopy #Trim the date time from the copied file name, store in a variable $DestinationFile = $PathToCopy+$FileName $RenamedFile = ($DestinationFile.substring(0,$DestinationFile.length–20))+'.bak' #Rename the copied file Rename-Item $DestinationFile $RenamedFile } }[/code]Thanks for any help!!- webrunner

Extract output from central management servers into a table

$
0
0
This one has my head spinning. I would like to run a query on all of the servers registered in the central management server and then write the output to a table on our management server. I can get the output and also load it into the database but what is loaded is not right. Server Name and Node Name don't go into a table correctly. I've been reading a bunch of examples from Google but really don't understand them. Somehow I need to split the output into two parts so one column can go into ServerName and one into NodeName.Any help would be greatly appreciated.[code="plain"]#Get list of servers in CMS$instanceNameList = invoke-Sqlcmd -query "SELECT [server_name] as NameFROM [msdb].[dbo].[sysmanagement_shared_registered_servers_internal] SSRSIjoin [msdb].[dbo].[sysmanagement_shared_server_groups_internal] SSSGIon SSRSI.server_group_id = SSSGI.server_group_idwhere SSRSI.server_group_id = '11'" -serverinstance "TESTSRV2"#Collect server name and node node from each into a variableforeach($instanceName in $instanceNameList){$results += Invoke-Sqlcmd -Query "SELECT @@SERVERNAME as ServerName, SERVERPROPERTY('ComputerNamePhysicalNetBIOS') as NodeName" -ServerInstance $instanceName.Name}#Insert the results into the STG_Results table in the DBA database$Connection = New-Object System.Data.SQLClient.SQLConnection$Connection.ConnectionString = "server='TESTSRV2';database='DBA';trusted_connection=true;"$Connection.Open()$Command = New-Object System.Data.SQLClient.SQLCommand$Command.Connection = $Connectionforeach($node in $results){ $sql = "insert into STG_Results (ServerName,NodeName) select '$node.ServerName','$node.NodeName'" $Command.CommandText = $sql $Command.ExecuteNonQuery()}$Connection.Close()[/code]

Get Visual Studio 2014 Path

$
0
0
Hi,If I run the below path I get the path as : "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\"....but I need the below path :'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE' as an output as the tf.exe is located to the above path.I tried to change the below string as below, but no luck -$vsEnvVars = (dir Env:).Name -match "VS[0-9]{1,3}COMNIDE"[code="sql"]clear$vsEnvVars = (dir Env:).Name -match "VS[0-9]{1,3}COMNTOOL"$latestVs = $vsEnvVars | Sort-Object | Select -Last 1$latestVs$vsPath = Get-Content Env:\$latestVs$vsPath[/code]

Error scripting database objects (view/table) that have a trigger

$
0
0
I'm getting an error using the script i've added a link to below as well, in case the forum doinks up some of the code.this script, in a larger context, scripts all the objects out in a given database...it scripts each object out to a folder by object type and individual file per object.i have an issue if the table or view has a trigger on it.[img]http://www.sqlservercentral.com/Forums/Attachment19042.aspx[/img]I thought that by making sure $ScriptOptions.Triggers = $true; was in my options, i'd be fine, but whether i toggle that to true or false, i cannot get tables or views, featuring a trigger, to script yet.the error is on the line $scrp.Script($URNCollection), so it's probably an overlooked option that is incompatible with my "default" options, maybe? i'm kinda stuck and need a bit of peer review.I KNOW it's triggers, because I've got a verbose statement that echos out exactly what object is being scripted at the moment.the error specifically is [quote][color="#FF0000"]Exception calling "Script" with "1" argument(s): "Script failed for Server 'HOL-WKS-444'. "At C:\Users\lizaguirre\Documents\ScriptOneDatabase.ps1:60 char:24+ $scrp.Script <<<< ($URNCollection) + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException[/color][/quote][b][url=http://www.stormrage.com/SQLStuff/ScriptOneDatabase.ps1.txt]ScriptOneDatabase.ps1.txt[/url][/b][code]##################################################################################################### Function Declarations###################################################################################################function get-databaseobjectscripts($db) {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null#$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.Databases | Where-Object {$_.name -eq $db} | foreach-object{$_.name | Out-Null $database = $_ $databaseName = $_.name write-verbose -Message "scripting [$databasename] in [$sqlserver]" -verbose $ScriptOptions = new-object ("Microsoft.SqlServer.Management.Smo.ScriptingOptions") $ScriptOptions.ExtendedProperties = $true # yes, we want these $ScriptOptions.DRIAll= $true # and all the constraints $ScriptOptions.ClusteredIndexes = $true; $ScriptOptions.NonClusteredIndexes = $true; $ScriptOptions.Indexes= $true # Yup, these would be nice $ScriptOptions.ScriptBatchTerminator = $true # this only goes to the file $ScriptOptions.IncludeHeaders = $true; # of course $ScriptOptions.ToFileOnly = $true # no need of string output as well $ScriptOptions.IncludeIfNotExists = $true # not necessary but makes script more versatile $ScriptOptions.Triggers = $true; $scrp=new-object ("Microsoft.SqlServer.Management.Smo.Scripter") ($Database.parent) $scrp.options=$ScriptOptions $database.EnumObjects([long]0x1FFFFFFF -band [Microsoft.SqlServer.Management.Smo.DatabaseObjectTypes]::all) | ` Where-Object {('sys','information_schema') -notcontains $_.Schema} | Foreach-Object { $urn= [Microsoft.SqlServer.Management.Sdk.Sfc.Urn] $_.URN write-verbose -Message "scripting $urn.name $urn.type" -verbose if(('StoredProcedure','View','UserDefinedFunction') -contains $urn.type -and $urn.IsEncrypted -eq $true){ $fullPath="$currentPath\$($urn.type)" $fileName = "$fullPath\$($urn.GetAttribute('Schema')-replace '[\\\/\:\.]','-')-$($urn.GetAttribute('Name') -replace '[\\\/\:\.]','-')(encrypted).sql" New-Item fileName -type file #save a file } else { if (('ExtendedStoredProcedure','ServiceBroker') -notcontains $urn.type) { $currentPath="$directoryname\$($ServerName -replace '[\\\/\:\.]','-' )\$($urn.GetAttribute('Name','Database') -replace '[\\\/\:\.]','-')" if ( $ServiceBrokerTypes -contains $urn.type) {$fullPath="$currentPath\ServiceBroker\$($urn.type)"} else {$fullPath="$currentPath\$($urn.type)"} if (!(Test-Path -path $fullPath )) { Try { New-Item $fullPath -type directory | out-null } Catch [system.exception]{ Write-Error "error while creating '$fullPath' " return } } $scrp.options.FileName = "$fullPath\$($urn.GetAttribute('Schema')-replace '[\\\/\:\.]','-')-$($urn.GetAttribute('Name') -replace '[\\\/\:\.]','-').sql" $UrnCollection = new-object ('Microsoft.SqlServer.Management.Smo.urnCollection') $URNCollection.add($urn) write-verbose "writing script to $($scrp.options.FileName)" [highlight="#ffff11"]$scrp.Script($URNCollection)[/highlight] } } } }}##################################################################################################### Execution Space is Below#####################################################################################################$servers = get-content C:\Data\PowerShell\computers.txt$servers = "HOL-WKS-444"$databaseToScript = "DBA_Utilities"$directoryname = "C:\Data\PowerShell\"#make sure our prime directory existsif (!(Test-Path -path $directoryname)) {New-Item $directoryname -type directory}#make sure our sub directory existsif ($sqlserver.Trim() -ne "") { if($sqlserver.IndexOf("\") -gt 0) { $directoryname = "C:\Data\PowerShell" + "\" + $sqlserver.Replace("\","(") + ")\" $position =$sqlserver.IndexOf("\") $server = $sqlserver.SubString(0,$position) $serverfilename = $sqlserver.Replace("\","(") + ")" } else { $directoryname = "C:\Data\PowerShell" + "\" + $sqlserver + "\" $server = $sqlserver $serverfilename = $server } if (!(Test-Path -path $directoryname)) { New-Item $directoryname -type directory }} get-databaseobjectscripts $databaseToScript[/code]

Connection options using SMO

$
0
0
I'm trying to set the following for a single connection (so that I can create a Unique Constraint on a computed varbinary column)I want to do this in PoSh using SMO, rather than executing T-SQL -- if possible.So, is this under Server.UserOptions? I don't want to permanently change server settings; it's just so I can create the constraint.SET NUMERIC_ROUNDABORT OFFGOSET ANSI_NULLS ONGOSET ANSI_PADDING ONGOSET ANSI_WARNINGS ONGOSET ARITHABORT ONGOSET CONCAT_NULL_YIELDS_NULL ONGOSET QUOTED_IDENTIFIER ONGOThanks!

Powershell Slower based on Runtime account

$
0
0
So I have a powershell script that goes out and grabs some database properties on approximately 30 servers. It returns data on a couple hundred databases in under 1minute, however when it gathers data on the instance the job is running from it takes almost 30minutes to return the info on the final 10 databases. When I run it using the SQLAgent Service account it returns almost instantly however when I use the proxy is when it takes 30minutes.I'm a little stumped how the account it runs under would be slower just for that one server.

Powershell for network path

$
0
0
I am totally new to powershell(just 2 days) so please bear my ignorance.Here is the code I am trying to execute as a sql agent job that basically deletes files over 2 days old.[code]function LoopFolders([string]$path,[string]$logpath) { $fs = new-object -com scripting.filesystemobject $folder = $fs.getfolder($path) $today = get-date -uformat "%Y_%m_%d" $log = $logpath + "Deleted_" + $today + ".log" foreach ($i in $folder.files) { if($folder.path -contains "Master" -or $folder.path -contains "Model" -or $folder.path -contains "Certificates") {break} else { $dt = ((Get-Date) - $i.DateLastModified).Days if ($dt -gt 2 -and $i.PsISContainer -ne $True ) { $deleted = "Deleting - " + $i.path + " - Last Write Time - " + $i.DateLastModified add-content $log -value $deleted remove-item $i.path } } } foreach ($i in $folder.subfolders) { LoopFolders($i.path) }}LoopFolders "C:\DatabaseBackUps" "C:\DatabaseBackUps\BackUpDeleteLogs"LoopFolders "\\10.1.1.10\DatabaseBackups" "\\10.1.1.10\Database\BackUpDeleteLogs"[/code]The problem here is that the code works fine for local path but errors out for network path with the following message.[code="plain"]The corresponding line is 'remove-item $i.path'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Invalid Path: '\\10.1.1.10\database\LogBackUp\PRODUCTION_ALLIED\PRODUCTION_ALLIED_backup_2012_06_01_093000_6722391.trn'. '. Process Exit Code -1. The step failed.[/code]The same question has been asked herehttp://social.technet.microsoft.com/Forums/da-DK/winserverpowershell/thread/a1a1ba21-0bd5-4b53-8838-5930f9599024

Remove newline in CSV field

$
0
0
Hi all,I'm trying to replace text in a CSV.The CSV line looks something like this:[code="other"]"Field One","Field Two","FieldThree","Field Four"[/code]So I tried something like:[code="vb"](Get-Content $csvfile) -replace "Field`n", "Field" | Set-Content $csvfile[/code]But this didn't work.

PowerShell Reference

$
0
0
What's a good PowerShell reference book for someone with limited experience with PowerShell (meaning my experience is looking for scripts written by others that do something similar to what I want and tweaking them until they do what I want)?My primary interest will be scripts that work with SQL 2012/2014 and associated file system tasks to replace manual processes.Call me old fashioned but I prefer flipping through a well-written reference book preferable to googling for sites written with varying degrees of skill that assume varying degrees of existing knowledge.

Get smo object from sql database item name

$
0
0
Hi all,Is there a way to get an smo object (stored proc, UDF, etc...) from an items' name and a database object?that is, without knowing what type of object xyz is, with the string "xyz" and a database object, can I get an smo object?$object = $objSrcDB.EnumObjects() | ?{$_.Name -eq $objName} gives me a System.Data.DataRow.If possible, I'd like to do it without getting into if ($Object.DatabaseObjectTypes -eq "StoredProcedure") {...}else if ($Object.DatabaseObjectTypes -eq "UDF") {...}... Thanks in advance,P

DBEngine Access check

$
0
0
The below powershell code checks if we can access to a server and separates the good list from the bad list.How can also check and add to the same above code to check if wehave access to the database engines of these respective servers and add them into 2 more tables ConnDBEngines and NotConnDbEngines.$Server = "ServerA"$Database = "DatabaseA"$con = "server=$Server;database=$Database;Integrated Security=sspi"$cmd = "SELECT DISTINCT ServerName FROM dbo.Servers" $da = new-object System.Data.SqlClient.SqlDataAdapter ($cmd, $con) $dt = new-object System.Data.DataTable $da.fill($dt) | out-null foreach ($srv in $dt) { $ServerName = $srv.ServerName try { $ping = new-object System.Net.NetworkInformation.Ping $Reply = $ping.send($ServerName) $sql = "INSERT INTO dbo.ConnServers(ServerName) SELECT '$ServerName'" Invoke-SQLcmd -serverinstance $Server -database $Database -query $sql Write-Output "ping success $ServerName" } catch { $sql1 = "INSERT INTO NotConnServers(ServerName) SELECT '$ServerName'" Invoke-SQLcmd -serverinstance $Server -database $Database -query $sql1 Write-Output "can't connect to $servername" } }Thanks

Problem trying to create a database+datafile in a specific directory.

$
0
0
Hello,I am trying to create a script that will create a database, a datafile with a particular naming convention, and place it in a directory that is created, also using a naming convention, and put it all in the primary filegroup. But I am having difficulties, I feel like I am almost there but I'm missing something or other and have hit a dead end. Looking for some advice or ideas on where I am going wrong.---------------------------------------------------------------Import-Module "SqlPs" -DisableNameChecking $DatafileName = $DBName +"_D1.mdf"$LogFileName = $DBName +"_L1.ldf"$InstanceName="MyInstanceName"$DBServerName="DBServerName"$DrvLetter = "E"+':\'$InstanceName = "InstanceName"$AppID = "ABC"$AppName = "Connect4"$DBName="TESTDB"$DataFile = New-Item -ItemType Directory -path ("$DrvLetter"+'SQLDATA\MSSQL$'+"$InstanceName"+'\'+"$AppID"+'\'+"$AppName"+'\'+"$DBName"+'\'+"$DatafileName") $LogFile = New-Item -ItemType Directory -path "$DrvLetter"+'SQLLOGS\MSSQL$'+"$InstanceName"+'\'+"$AppID"+'\'+"$AppName"+'\'+"$DBName"+'\'+"$LogfileName")$BakFile = New-Item -ItemType Directory -path ("$DrvLetter"+'SQLBAK\MSSQL$'+"$InstanceName"+'\'+"$AppID")$Server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList "$DBServerName\$InstanceName"#Create The Database$DB = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database ($Server, $DBName)#$Server.Databases[$DBName] ####I thought this line would tell Powershell what database I wanted to work with, but I think it just gives out info on that database.$fg = New-Object -TypeName Microsoft.SqlServer.Management.Smo.FileGroup ($DB, 'PRIMARY')$SqlData.FileName = ("$DrvLetter"+'SQLDATA\MSSQL$'+"$InstanceName"+'\'+"$AppID"+'\'+"$AppName"+'\'+"$DBName"+'\'+"$DatafileName")$SqlData = New-Object -TypeName Microsoft.SqlServer.Management.Smo.DataFile -ArgumentList ($fg, $DatafileName)$SqlData.Create()$DB.Create()$Error[0]|Format-List -Force----------------------------------------------------The error I am currently getting is...Exception : System.Management.Automation.MethodInvocationException: Exception calling "Create" with "0" argument(s): "Create failed for DataFile 'TESTDB_D1.mdf'. " ---> Microsoft.SqlServer.Management.Smo.FailedOperationException: Create failed for DataFile 'TESTDB_D1.mdf'. ---> Microsoft.SqlServer.Management.Smo.FailedOperationException: Cannot create DataFile '[TESTDB_D1.mdf]' if parent is not yet created. at Microsoft.SqlServer.Management.Smo.SqlSmoObject.GetParentObject() at Microsoft.SqlServer.Management.Smo.SqlSmoObject.CreateImplInit(StringCollection& createQuery, ScriptingPreferences& sp) at Microsoft.SqlServer.Management.Smo.SqlSmoObject.CreateImpl() --- End of inner exception stack trace --- at Microsoft.SqlServer.Management.Smo.SqlSmoObject.CreateImpl() at CallSite.Target(Closure , CallSite , Object ) --- End of inner exception stack trace --- at System.Management.Automation.ExceptionHandlingOps.ConvertToMethodInvocationException(Exception exception, Type typeToThrow, String methodName, Int32 numArgs, MemberInfo memberInfo) at CallSite.Target(Closure , CallSite , Object ) at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0) at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame) at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)TargetObject : CategoryInfo : NotSpecified: (:) [], MethodInvocationExceptionFullyQualifiedErrorId : FailedOperationExceptionErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfoScriptStackTrace : at <ScriptBlock>, C:\Users\MyName\Documents\TrialNError2.ps1: line 28PipelineIterationInfo : {}PSMessageDetails : ...The line ' Cannot create DataFile '[TESTDB_D1.mdf]' if parent is not yet created.', but I'm not sure how to deal with this and Google is being a bit shy. The database still gets created, but using the SQL server default file locations.

Comparing file name and view column in Powershell

$
0
0
Hello experts,I'm learning Powershell to try to accomplish a task. I say "learning" as a disclaimer - so if the code below is as ugly as I think it is, by all means let me know of a more elegant way!1. I am trying to use Powershell to query a view I have of database names. 2. For each database in the view, I want to copy the latest backup file from production to staging. "DBSERVER" is production and "DBSERVERSTAGING" is staging.3. If a database name is not in the view, I do NOT want to copy that backup file.At the moment, I can get a list of databases parsed from the directory folders. I can also use Powershell to return a list of names from the view (see snippet below). I also have the code working to carry out the copy of the latest backup file from production to staging, using the code here as a starting point, since I use the Ola Hallengren backup solution:[url=https://sqlactions.com/2015/03/30/powershell-script-to-manipulate-sql-server-backup-files/][b]https://sqlactions.com/2015/03/30/powershell-script-to-manipulate-sql-server-backup-files/[u][/u][/b][/url]But when I try to combine the two, the Powershell script copies ALL the database backups from production, not just the subset in the view. I have commented out the copy line #Copy-Item $FileToCopy $DestinationPath -Include *.bak which is where I want the correct backup file copy to happen. And I am trying to filter out .trn files and use full .bak files only.So my basic question is: What is the most efficient way to use a database query/view as a basis (a loop I assume) for comparing the query/view values to the values parsed from a directory listing? Specifically, I have heard of Powershell arrays, so is there a way to output the query results into an array that I can then provide to the Copy-Item command in a loop?[code]# Get database name from the file path. If ($FileToCopy.Length -gt 0 -And $FileToCopy.IndexOf("\FULL\") -gt 0){$DatabaseName = $FileToCopy.SubString(($FileToCopy.IndexOf("\DBSERVER\") + 7),($FileToCopy.IndexOf("\FULL\") - $FileToCopy.IndexOf("\DBSERVER\") - 7)) $DbDetails = "select name from dbo.db_list where name = '{0}'" -f $DatabaseName Invoke-Sqlcmd –ServerInstance DBSERVERSTAGING –Database dba –Query $DbDetails#Copy-Item $FileToCopy $DestinationPath -Include *.bak}[/code]Thanks for any help!- webrunner

Autoalert if SQLAgent stops

$
0
0
I have this piece of powershell code which sends out an email when executed in a SQL job or run in powershell mode but does not work in this below situation.Attached is a screenshot of the Recovery tab under SQLAgent services.I have run this command in powershell before stopping SQLAgent but I did not get any email alert that the SQLAgent has been stopped.set-executionpolicy remotesignedCan anyone help fix this?Thanks#variables$emailFrom = "defg@kjid.org"$emailTo = "abcd@def.org"$subject = "Powershell Function calling an SMTP server"$body = "Send an email through SMTP in Powershell"$smtpServer = "smtp.abcdefgh.org"#create a functionFunction sendEmail([string]$emailFrom, [string]$emailTo, [string]$subject,[string]$body,[string]$smtpServer){$smtp = new-object Net.Mail.SmtpClient($smtpServer)$smtp.Send($emailFrom,$emailTo,$subject,$body)}sendEmail $emailFrom $emailTo $subject $body $smtpServer

Invoke-ASCMD - Passing values to the XMLA file not working

$
0
0
I need to create a cmd file to backup Analysis Service Database. Because my SQL Server 2014 does not have ascmd.exe, I thought I would use powershell 'Invoke-ASCMD' but I am having problems passing parameters to the XMLA file. Dbname and Backupfile parameters are not recognized in the XMLA file but when I hardcode values in their place, the script runs successfully. Please help! Command File : set DBNAME=ANALYSIS_DBset SCRIPTPATH=E:\cube_backup.xmlaset SRC=ServerName\ServerInstanceset BACKUPPATH=G:\Cube_BackupFolder\For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c%%a%%b)for /F "tokens=1-3 delims=:. " %%A in ('time/T') do (set var=%%A%%B%%C%) echo %mydate%_%var% set BACKUPFILE="%BACKUPPATH%\%DBNAME%_cube_%mydate%_%var%.abf"powershell.exe -command Invoke-ASCmd -InputFile %SCRIPTPATH% -server %SRC% --------------------------------------------------------SCRIPTPATH (XMLA code) :<Backup xmlns="http://schemas.microsoft.com/analysisservices/2003/engine"> <Object> <DatabaseID>$dbname</DatabaseID> </Object> <File>$backupfile</File> <AllowOverwrite>false</AllowOverwrite> </Backup>

Easy piece of code just doesnt bloody work.

$
0
0
Sounds like a headline from the onion.All I want to do is add a new database role to a database and its not working. I understand the error, but I don't know why I'm getting it. It (the code) matches all the various examples I have found on the internet to compare with, so I'm just stuck. Whilst debugging, I can see that all the variables are showing the correct values, I just cant find an issue with it.The error is specifically with this line...$NewRole = New-Object Microsoft.SqlServer.Management.Smo.DatabaseRole $dbname, $RoleName...but it seems ok according to the net and my PoSh books. Would love a bit of help.Import-Module SQLPS -DisableNameChecking$InstanceName="Inst_1"$DBServerName="Serv_1"$TargetServer= "$DBServerName\$InstanceName"$RoleName= "Role1"$dbname="TopTrumps"Function fn-create-role-in-database ([String]$TargetServer, [String]$dbname, [String]$Rolename){$Server = New-Object Microsoft.SqlServer.Management.Smo.Server $TargetServer$NewRole = New-Object Microsoft.SqlServer.Management.Smo.DatabaseRole $dbname, $RoleName$NewRole.Create()}fn-create-role-in-appname-database $TargetServer $dbname $RoleNameThe error I am receiving is...Exception : System.Management.Automation.MethodException: Cannot find an overload for "DatabaseRole" and the argument count: "2". at System.Management.Automation.Adapter.GetBestMethodAndArguments(String methodName, MethodInformation[] methods, PSMethodInvocationConstraints invocationConstraints, Object[] arguments, Object[]& newArguments) at System.Management.Automation.DotNetAdapter.ConstructorInvokeDotNet(Type type, ConstructorInfo[] constructors, Object[] arguments) at Microsoft.PowerShell.Commands.NewObjectCommand.CallConstructor(Type type, ConstructorInfo[] constructors, Object[] args)TargetObject : CategoryInfo : InvalidOperation: (:) [New-Object], MethodExceptionFullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommandErrorDetails : InvocationInfo : System.Management.Automation.InvocationInfoScriptStackTrace : at fn-create-role-in-database, C:\Users\username\Documents\Create_DBRole.ps1: line 12 at <ScriptBlock>, C:\Users\username\Documents\Create_DBRole.ps1: line 16PipelineIterationInfo : {}PSMessageDetails : Thank you.D.

Query local SSMS server group with Powershell?

$
0
0
This may be a totally off the wall question, but it seems like it should be possible to do. Just can't find any specifics as to how I might accomplish it.I have a situation in that I have the same database (structurally) across multiple SQL Server instances, with different database names. Through SSMS I have a local server group defined that references each unique instance and individual database. This allows me query each database at once with a single SQL statement, regardless of database name.When queries are run through my SSMS environment, I have the option enabled to return the SQL Server instance in the grid output so the instance name is returned with each row. I would like to automate running my query and outputting the results to Excel via Powershell script.What I'm hung up on is that I need to be able (with Powershell) to reference my SSMS local server group as the the data source that the query runs against, and run the query. Has anyone done this? I appreciate any feedback..
Viewing all 467 articles
Browse latest View live


Latest Images