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

Powershell SMO work in cmd, not from script

$
0
0
This was originally posted (incorrectly) in the SMO/RDO/DMO forum. Sorry.My code (Server 2003 Enterprise, SQL Server 10.0.5512.0, Powershell v1.0 ISE) is as follows:function Script-Database_01 {# Created: 09/06/2013# Edited: 09/06/2013[CmdletBinding()]param([Parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="Local directory to save build-scripts output.")][Alias('fp')][string[]] $Filepath,[Parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage ="Server or instance name.")][Alias('ds')][string[]] $DataSource,[Parameter(Mandatory=$true,ValueFromPipeline=$true,HelpMessage="The database to be scripted.")]#[Alias('db')][string[]] $DatabaseName)BEGIN{Write-Output $FilepathWrite-Output $DataSourceWrite-Output $DatabaseNameGet-PSSession}PROCESS{# Set 'Option Explicit' to catch subtle errors:set-psdebug -strict#Load SMO assembly, and SMOExtended and SQLWMIManagement libraries:$ms = "Microsoft.SqlServer"$v = [System.Reflection.Assembly]::LoadWithPartialName("$ms.SMO")[System.Reflection.Assembly]::LoadWIthPartialName("$ms.SMOExtended") | out-null$my = "$ms.Management.SMO"$source = new-object("$my.Server") $DataSourceif ($Source.Version -eq $null) {Throw "Cant find the instance $DataSource."}$db = $source.Databases[$DatabaseName]if ($db.name -ne $DatabaseName) {Throw "Cant find the database '$DatabaseName' in $DataSource."}$transfer = new-object("$my.Transfer") $db$transfer.Options.ScriptBatchTerminator = $true # This only goes to file$transfer.Options.ToFileOnly = $true # This only goes to file$transfer.Options.Filename = "$($Filepath)\$($DatabaseName)_Build_01b.sql"# Do it:$transfer.ScriptTransfer()}END{}}When I execute everything in the PROCESS{} section, the commands succeed, and the file is correctly output. When I run the script (as .\Script-Database_01.psq [+parameters] I get the follow error:New-Object : Cannot find an overload for "Server" and the argument count: "2".At C:\Powershell\Scripts\Script-Database_01.ps1:44 char:29+ $source = new-object <<<< ("$my.Server") $DataSource+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommandI assume this has something to do with the import of SMOExtended, but I can't see it.Can anyone point me in the "write" direction?

Who am I ?

$
0
0
Hi,I run, now, my jobs with steps written in powershell.I would like to get informations about the current job, the current step, I am running.I read some topics about token (like $(ESCAPE_NONEJOBID))) but don't succeed to use it in a powershell step.Is'nt exist more recent method ?Is there some initialized variables like $host or $myinvocation where I can find these informations ?Thank you for your help

Move SQL Instance to Another Node from a Remote Server

$
0
0
I am writing a script using Get-WmiObject to inspect remote clusters and determine if SQL instances are running on their preferred nodes. This is working fine, but now I want the script to move instances to the preferred node when they are on the non-preferred mode.I can't find a way of doing this remotely with Get-WmiObject.Does anyone know how to do this?

delete files before 8PM

$
0
0
hello experts,i have some error in using "sp_delete_file" Stored procedure. so looking some other option or script to delete files before 8 PM. daily. if some one can design such script please help.

SQL Logins output to a file via sp_help_revlogin

$
0
0
Hi all,I'm looking to get sql logins output to a file via powershell.After many different, but unsuccessful searches to find a PS script to retrieve SQL Logins via the stored proc sp_help_revlogin, I'm at a loss.Hopefully someone can help. Here's the code which returns a "0" when run. $SqlConnection = New-Object System.Data.SqlClient.SqlConnection$SqlConnection.ConnectionString = "server=srvname\instname;database=master;Integrated Security=sspi"$SqlCmd = New-Object System.Data.SqlClient.SqlCommand$SqlCmd.CommandText = "sp_help_revlogin"$SqlCmd.Connection = $SqlConnection$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter$SqlAdapter.SelectCommand = $SqlCmd$DataSet = New-Object System.Data.DataSet$SqlAdapter.Fill($DataSet) | out-File $outfile -append$SqlConnection.Close()$DataSet.Tables[0]returns: 0This works with a stproc like sp_helpdb, but not sp_help_revlogin. Suggestions?Thank you-RR

Printing to a specific printer

$
0
0
As of now I have this in my Execute Process task Command section to print a list of text files in a directory.Get-ChildItem -path $Directory -recurse -include *.txt | ForEach-Object {Start-Process -FilePath $_.fullname -Verb Print -PassThru | %{sleep 5;$_} | kill }I believe it goes to the locally configured printer.How do I make these files print to a specific network printer.Thanks

Powershell: Passing variables to scriptfile using invoke-sqlcmd

$
0
0
Hi,I have several large scripts that we have to usually modify manually to make changes to our databases. Usually this consists of 3 different variables. Lets use $city, $state, $country for example. I have been looking for a way to pass these variables to the script but can not find any examples, so I'm not sure if it is actually possible. I see that invoke-sqlcmd has a -variable option, which I tried passing an array too to see if I could pass the variables to the script without any luck.$scriptfile = 'c:\temp\mybigscript.sql'$server = 'localhost'$database ='bigdb"$MyArray = "MyVar1 = 'miami'", "MyVar2 = 'florida'", "MyVar3 = 'usa'"Invoke-SqlCMD -InputFile "$scriptfile" -ServerInstance $server -Database "$database" -variable $myarrayIs what I'm attempting to do even possible?Any help is appreciated.Thanks!

Help with PS Script

$
0
0
Need help from the PS gurus out there!I'm new to PS and I'm trying to create a script that dumps some basic server info to a CSV file. Now I can get it to work and gather most all my info I need and create the CSV. But, I cannot seem to return the hard drive info I'm trying to gather. Nothing goes in to the columns, they are blank. If you copy this script, change to your SQL Server, test environment not live :), and execute, it should be pretty self evident what I'm trying to do and what is missing.Any help is greatly appreciated!!!Here is my script thus-far:[code="other"][cmdletbinding()]param ( [parameter(ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)] [string[]]$ComputerName = "YOURSERVERNAME") begin {}process { foreach ($Computer in $ComputerName) { if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) { $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled} $Memory = Get-WmiObject Win32_ComputerSystem -ComputerName $Computer | Select TotalPhysicalMemory, Manufacturer, Model $Processor = Get-WMIObject Win32_Processor -ComputerName $Computer | Select Name $DriveSize = Get-WMIObject Win32_LogicalDisk -ComputerName $Computer | Select Name, Size, FreeSpace $SQLVersion = invoke-sqlcmd -query "select @@version" -ServerInstance $Computer | Select Column1 $Connections = invoke-sqlcmd -query "SELECT COUNT(dbid) as TotalConnections FROM sys.sysprocesses WHERE dbid > 0" -ServerInstance $Computer | Select TotalConnections foreach ($Network in $Networks) { $IPAddress = $Network.IpAddress[0] $mem = $memory.TotalPhysicalMemory / 1GB $Manufacturer = $memory.Manufacturer $Model = $memory.Model $ProcessorSpeed = $Processor.Name $DriveName = $DriveSize.Name $DriveSizeTotal = $DriveSize.Size / 1GB $DriveSizeFree = $DirveSize.FreeSpace / 1GB $SQLVersionNo = $SQLVersion.Column1 $ConnectionsNo = $Connections.TotalConnections $OutputObj = New-Object PSObject $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper() $OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress $OutputObj | Add-Member -MemberType NoteProperty -Name Manufacturer -Value $Manufacturer $OutputObj | Add-Member -MemberType NoteProperty -Name ServerModel -Value $Model $OutputObj | Add-Member -MemberType NoteProperty -Name TotalPhysicalMemoryGB -Value $mem $OutputObj | Add-Member -MemberType NoteProperty -Name Processor -Value $ProcessorSpeed $OutputObj | Add-Member -MemberType NoteProperty -Name DriveName -Value $DriveSize.Name $OutputObj | Add-Member -MemberType NoteProperty -Name DriveSizeTotal -Value $DriveSize.Size $OutputObj | Add-Member -MemberType NoteProperty -Name DriveSizeFree -Value $DriveSize.FreeSpace $OutputObj | Add-Member -MemberType NoteProperty -Name SQLVersion -Value $SQLVersionNo $OutputObj | Add-Member -MemberType NoteProperty -Name NumberOfConnections -Value $ConnectionsNo $OutputObj | Export-CSV -Path “C:\TEMP\report.csv” -notype } } }} end {}[/code]

Powershell script enhancement

$
0
0
Hi everyone.I have a script that works great at the moment. The Script I use checks all SQL servers in a table for the last backup status. It then emails out an exception report for databases missing a full backup etc.As I mentioned script works fine for all databases on the instances being checked.The enhancement I want to do is to amend the script to ignore certain databases that exist in say an exception table.This is the code segment that I think I need to amend.[code="other"]# COMMENT: This script checks every server in the inventory, and gets the databases # that have not been backed up for some time defined by minutes. # An exception report is created and sent to the DBA group.# Loop through the list OF SQL Server instances AND run the CHECK-Backups FUNCTION# against each instance TO get the BACKUP exceptions.Foreach ($sqlServer IN $sqlServers) { $sqlNetworkName=$sqlServer.SQLNetworkName $sqlInstanceName=$sqlServer.instanceName $tcpPort=$sqlServer.tcpPort $strResult="" IF ($sqlInstanceName -ieq 'MSSQLSERVER') { $strResult=(CHECK-Backups "$sqlNetworkName,$tcpPort"$backupType $minutes) IF ($strResult -ne "" { $exceptions=$exceptions + $strResult + "`n" } } ELSE { $strResult=(CHECK-Backups "$sqlNetworkName\$sqlInstanceName,$tcpPort"$backupType $minutes) IF ($strResult -ne "" { $exceptions=$exceptions + $strResult + "`n" } }}[/code]I am guessing I need some kind of table created that holds the databases to be excluded. The Script will then run against all the database in inventory , but then exclude those databases it finds in the exception table.Just not sure on how to code that ??Any help or advice appreciated,

Poweshell array confusion

$
0
0
HiI am new to powershell, and am struggling a bit with the passing of an array as a variable. Firstly, I have a function which will return a set of server names based on and variable for the environment. However, when I try to pass the output from the function to another script, it only returns data for the first value (I have set up my test for 3 servers to be returned). I must be passing the variable incorrectly, or scoping it incorrectly, but I am a bit stuck now. Can anyone tell me where I am going wrong, please?-----------------------------------------------------------------------------------------Function:Function GetComputerList{ Param( [string]$Environment) $comparray = @() $query = "SELECT ServerNameFROM Server SINNER JOIN dbo.Environment EON S.EnvironmentID = E.EnvironmentIDWHERE E.EnvironmentName = '$Environment'" $connection = new-object system.data.sqlclient.sqlconnection( "Data Source=localhost;Initial Catalog=Test;Integrated Security=SSPI;”) $adapter = new-object system.data.sqlclient.sqldataadapter ($query, $connection) $table = new-object system.data.datatable $adapter.Fill($table) | out-null $compArray = @($table | select -ExpandProperty ServerName) return ($compArray)}----------------------------------------------------------------------------Script 1:. \Powershell\GetComputerList.ps1set-location C:\Powershell#Write-Host "Calling CheckJavaProcesses"$ComputerArray = @()$ComputerArray = GetComputerList 'Prod'Write-host $ComputerArray#check AL_engine processes$Command = ".\CheckJavaProcesses.ps1 '$ComputerArray'"Invoke-Expression $Command--------------------------------------------------------------Script 2:param([string[]] $ComputerArray)$date = (get-date).tostring("yyyyMMddhhmm")$logfile = "C:\Powershell\Logs\PRD_CheckProcesses_$date.log"Write-Host $ComputerArray# ProcessesForEach ($i in $ComputerArray ){$i >> $logfile; get-process -computername $i -name java* >> $logfile}Notepad $logfileThanks for any help in advance :-)

pscustomobject help

$
0
0
Hi gang,I have an array, $Data, having a bunch of elements, $Datum, each of which contains something like this:@{Date =30-Nov-12; BillingWeek=1; BillingMonth=DECEMBER; Q=Q1; Weekday=Friday; CalendarMonth=November; Day=30; Year=2012; Time Due=8:00 AM)So for each $Datum, how can access the value, that's on the other side of "Date = " for example?P

Good current Powershell/SQL tutorials?

$
0
0
Hi,Trying to follow older tutorials is pretty frustrating. It seems like a lot of the syntax results in errors, or in some cases is a few versions behind and there are probably better ways to do things at this point. My main goal is getting PS to query SQL and write formatted Excel files of the results. I realize that I'm probably not going to get both in one shot, but if anyone has found a good read in either area, I'd really appreciate any suggestions. The Stairways that are posted on this site even seem a couple versions old.Thanks

Can't get powershell script to run as Agent Job - runs from CMD

$
0
0
I thought I'd try Powershell for some file maintenance. Thought it might be fun! And now I'm stuck.Can anyone see what I'm doing wrong?I'm having trouble with Rename-Item. This line works from CMD:[code="other"]Dir \\MyServer\MyShare\Transfer\*.txt | Rename-Item –Newname{($_.basename + (get-date -format '_MMddyyyy') + $_.extension)}[/code]But fails when run as part of a script in an Agent Job Step.Here's the entire script:[code="other"]#add the date - files will be named filename_mmddyyyy.txtSet-Location \\MyServer\MyShareDir \\MyServer\MyShare\Transfer\*.txt | Rename-Item –Newname{($_.basename + (get-date -format '_MMddyyyy') + $_.extension)}# copy the .txt files from MyShare\Tranfer to MyShareCopy-Item -Path \\MyServer\MyShare\transfer\*.txt -Destination \\MyServer\MyShare# delete the .txt files from the Transfer folderRemove-Item \\MyServer\MyShare\transfer\*.txt[/code]Here's the error message:Executed as user: MyHouse\sqladmin. A job step received an error at line 3 in a PowerShell script. The corresponding line is 'Dir \\MyServer\MyShare\Transfer\*.txt | Rename-Item ?Newname {($_.basename + (get-date -format '_MMddyyyy') + $_.extension)}'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'A positional parameter cannot be found that accepts argument '($_.basename + (get-date -format '_MMddyyyy') + $_.extension)'. '. Process Exit Code -1. The step failed.

script

$
0
0
I have this code which prints files inside the tempprint folder.TargetFolder = "C:\tempprint" Set objShell = CreateObject("Shell.Application") Set objFolder = objShell.Namespace(TargetFolder) Set colItems = objFolder.Items For Each objItem In colItems objItem.InvokeVerbEx ("Print") NextBut its poping up the print dialog to print every file.How do I suppress the print dialog and print all the files(300 files) in the tempprint directory smoothly.

Printing from powershell

$
0
0
Get-ChildItem -path $Directory -recurse -include *.html | ForEach-Object {Start-Process -FilePath $_.fullname -Verb Print -PassThru | %{sleep 5;$_} | kill }How do I suppress the print dialog ? I need to print a list of 200+ .html files. But the above code keeps prompting before printing each file ?

Copy a file from each subdirectory to one folder

$
0
0
Hi,I'm trying to do something like this:[code="plain"]Get-ChildItem -Path "\\drive\s*\*.txt" | ForEach-Object {Copy-Item "\\drive\Erik" }[/code]But it isn't working, and I'm not really getting anywhere with it. Any recommendations? I don't have a ton of time to research at the moment.Thanks

Powershell Script help for Scripting

$
0
0
Hello , Please assists me if any one has idead about this . I have script in powershell which script out SP with specific condition . Want to achieve is drop those SP once the script generation is completed . My script works only for one SP at time and I want it loop properly .if I add $proc.drop() and throws error : An error occurred while enumerating through a collection: Collection was modified; enumeration operation may not execute..At E:\RD\LVer.ps1:18 char:40+ foreach <<<< ($proc in $procs) + CategoryInfo : InvalidOperation: (Microsoft.SqlSe...dListEnumerator:SmoSortedListEnumerator) [], Runtim eException + FullyQualifiedErrorId : BadEnumeration[[b]u]Actual Script :[/u][/b]$rootDrive = "<Location for scripts>"[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null$MyScripter=new-object ("Microsoft.SqlServer.Management.Smo.Scripter")$srv=New-Object "Microsoft.SqlServer.Management.Smo.Server" "<ServerName>" $dbName = $srv.databases["<Database Name>"] $procs = $dbName.StoredProcedures $MyScripter.Server=$srv #STORED PROCEDURES if($procs -ne $null) { foreach ($proc in $procs) { #Assuming that all non-system stored procs have proper naming convention and don't use prefixes like "sp_" if ( $proc.Name.IndexOf("<any condition>") -eq 0) { $fileName = $proc.name.Replace("\", "") "Scripting SP $fileName" $scriptfile = "$rootDrive\$filename.sql" $MyScripter.Options.FileName = $scriptfile #AppendTofile has to be 'true' in order that all the procs' scripts will be appended at the end $MyScripter.Options.AppendToFile = "False" $MyScripter.Script($proc)|out-null $proc.Drop() } } }

Add output of Powershell query Multiple WMI Classes to SQL

$
0
0
Hi All,I'm new to Powershell and I've been playing around with scripts all week but not having a scripting background I'm really not sure what I'm doing. I located the below script in another one of the topics under Powershell. I've chopped and changed bits of it and just can't seem to quite get it. I must say staring at it for a week I feel like I'm starting to understand some of it. I need help expanding on it. It works for retrieving more than 1 value from the same class and inserts the values. What I need to do is to be able to retrieve values from other classes and insert the result in to the appropriate table column. Any help / advice would be so appreciated. I'm not sure quite what the etiquette is for the forum. All I can say is I am a newbie and need some help.$servernames = Get-WmiObject -computername Anycompname -class win32_ComputerSystem | Select Name, Manufacturer# Open Connection$conn = New-Object System.Data.SqlClient.SqlConnection$connectionString = "Server=;Database=;user=;pwd=;"$conn.ConnectionString = $connectionString$conn.Open()# Create the Command object to execute the queries$cmd = New-Object System.Data.SqlClient.SqlCommand$cmd.Connection = $conn$cmd.CommandType = [System.Data.CommandType]::Text# Write Dataforeach ($servername in $servernames){# Compose Query for this $servername - watch the single quotes for string values!!$query = "INSERT INTO dbo.U_Server (ServerName, OSVersion) VALUES ('" + $servername.Name + "', '" + $servername.Manufacturer + "')"# Uncomment next line to display query for checking$query # Setup Command$cmd.CommandText = $query# Execute Command to insert data for this $drive$result = $cmd.ExecuteNonQuery() }# Tidy Up $conn.Close()

Server 2003 powershell

$
0
0
What version of powershell ships with Windows Server 2003?

Poweshell script to script out jobs, databases, users, linked servers, logins, roles, alerts, etc from a list of servers

$
0
0
create a c:\servers.txt file with list of serversand copy the following into a file .ps1enjoyfunction getwmiinfo ($svr) { gwmi -query "select * from Win32_ComputerSystem" -computername $svr | select Name, Model, Manufacturer, Description, DNSHostName, Domain, DomainRole, PartOfDomain, NumberOfProcessors, SystemType, TotalPhysicalMemory, UserName, Workgroup | export-csv -path .\$svr\BOX_ComputerSystem.csv -noType gwmi -query "select * from Win32_OperatingSystem" -computername $svr | select Name, Version, FreePhysicalMemory, OSLanguage, OSProductSuite, OSType, ServicePackMajorVersion, ServicePackMinorVersion | export-csv -path .\$svr\BOX_OperatingSystem.csv -noType gwmi -query "select * from Win32_PhysicalMemory" -computername $svr | select Name, Capacity, DeviceLocator, Tag | export-csv -path .\$svr\BOX_PhysicalMemory.csv -noType gwmi -query "select * from Win32_LogicalDisk where DriveType=3" -computername $svr | select Name, FreeSpace, Size | export-csv -path .\$svr\BOX_LogicalDisk.csv –noType}function get-databasescripts {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.Databases | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "Databases.sql") }function get-backupdevices {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.BackupDevices | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "BackupDevices.sql") }function get-triggers {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.Triggers | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "Triggers.sql") }function get-endpointscripts {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.EndPoints | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "EndPoints.sql") }function get-errorlogs {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.ReadErrorLog() | export-csv -path $($directoryname + "Box_errorlogs.csv") -noType}function get-sqlagentscript {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.JobServer | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "sqlagentscript.sql") }function get-jobscripts {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.JobServer.Jobs | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "jobs.sql") }function get-linkscripts {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.LinkedServers | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "linkedservers.sql") }function get-userlogins {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.Logins | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "logins.sql") }function get-roles {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.Roles | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "roles.sql") }function get-alerts {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.JobServer.Alerts | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "alerts.sql") }function get-operators {[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver$srv.JobServer.Operators | foreach {$_.Script()+ "GO"} | Out-File $($directoryname + $serverfilename + "operators.sql") }$servers = get-content c:\servers.txtforeach ($server in $servers){ if (!(Test-Path -path .\$server)) { New-Item .\$server\ -type directory }$directoryname = "c:\downloads\DRTest\" + '\' + $server + '\' $sqlserver = $server$serverfilename = $servergetwmiinfo $serverget-databasescriptsget-errorlogsget-triggersget-backupdevicesget-endpointscriptsget-sqlagentscriptget-jobscriptsget-linkscriptsget-userloginsget-operatorsget-alerts}
Viewing all 467 articles
Browse latest View live