Does anyone has any handy PS query to get the details of each mount point and the associated LUN ID details?If anyone has, please share.
↧
Powershell query to get the Mount Points and the associated LUN ID details
↧
Poweshell script to script out jobs, databases, users, linked servers, logins, roles, alerts, etc from a list of servers
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}
↧
↧
Umlauts in my TSQL script are turning to "?" when called from a powershell script
I am using a powershell script to manage releases over multiple servers & databases.when the tsql runs, umlauts are changing to question marks.an example:the powershell[code="other"]clear-host[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null$filepath = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a Path name", "Release Tool 1.0", "C:\Temp\mysqlfile.sql")ForEach($item in (Get-ChildItem $filepath)) { Write-Output $item.FullName}invoke-sqlcmd -inputfile $filepath -serverinstance "<ServerName>" -database "tempdb"[/code]the tsql script[code="sql"]use tempdb goif exists (select name from sys.objects where object_id = object_id('PowershellTest'))begindrop table dbo.PowershellTestend gocreate table dbo.PowershellTest (StringValue varchar(64))go insert into dbo.PowershellTest(StringValue)select 'Gültig'go[/code]the results[code="sql"]select StringValue from dbo.PowershellTest[/code][code="other"]StringValueG?ltig[/code]Any help would be greatly appreciatedThanksIan
↧
SQL Logins output to a file via sp_help_revlogin
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
↧
Script improvement advice.
Hi everyone.Hoping someone could offer me some advice in regards to an issue I am stuck on.My script checks the Tempdb status , I would like the results to a .csv and also display on screen if possible.If possible could someone advise me on what I need to change in my script , how the options work etc.Any comments on how the script is working , and how I can change it would be most appreciated as I am trying to learn PowerShell.My current script:Clear-Hostforeach ($svr in get-content "C:\PowerShell\Servers.txt"){function Test-SQLConnection{ param([parameter(mandatory=$true)][string[]] $Instances) $return = @() foreach($InstanceName in $Instances){ $row = New-Object –TypeName PSObject –Prop @{'InstanceName'=$InstanceName;'StartupTime'=$null} try{ $check=Invoke-Sqlcmd -ServerInstance $InstanceName -Database TempDB -Query "SELECT @@SERVERNAME as Name,Create_Date FROM sys.databases WHERE name = 'TempDB'" -ErrorAction Stop -ConnectionTimeout 3 $row.InstanceName = $check.Name $row.StartupTime = $check.Create_Date } catch{ #do nothing on the catch } finally{ $return += $row } } return $return}Test-SQLConnection -Instances $svr}thank you in advance for any advice offered.
↧
↧
Printing
I need to schedule a powershell script in a SQL job.The powershell script should silently print pdf files from a UNC path to a network printer.I was able to print from command prompt (not silent printing) using this code.WORKING But Not printing Silently and prints only to the default printer:C:\Users\ic019084>"C:\Program Files (x86)\Adobe\Reader 11.0\Reader\AcroRd32.exe" /t "D:\GP.pdfAny ideas are appreciated.Thanks
↧
deploy SP to multiple database
Is there anyway I can use powershell to deploy a SP to Multiple dabases in same server. I have to depoly the same SP to 50+ databases which I can get the list from sys table in the same server.I am wondering if i can do it using powershell to save deployment time? i am using sql server 2008 r2 and 2014
↧
SQL Agent job not failing when Powershell script errors
First time using Powershell. And I'm trying to execute via SQL Agent job. So I don't know if I have something wrong in my Powershell script or my SQL Agent job or Both.SQL Server 2008 R2 PowerShell V2.0Have tried in Powershell the Trap and Try catch with a Throw and Exit 1. But for some reason the SQL Agent job doesn't fail.In Powershell I have:$ErrorActionPreference = "Stop"-ea stopIn Sql agent job I have:Command:powershell.exe -File "\\mypowershell\PSscript.ps1" -param1 "\myfilelocation" -param2 "\mydestination" -ErrorAction StopAdvanced:On failure action: Quit the job reporting failureNow when the Powershell script fails I want the sql agent job to fail.What am I missing?Thanks,Sqlraider
↧
Powershell query to find all SQL Instance names alone and export to .Txt
I am writing a query to find the SQL Servers which are all UP & Running. While doing so, I find that each instance has multiple SQL Instances. How to write a good powershell query to export all the SQL Instance details and export to Excel and .TXT so that at a next step I can check for tge ping status using win32_pingstatus Get-WMIObject class.Please suggest.Thanks in advance
↧
↧
How do you connect to Central Management Servers if your server has an instance name with it
Trying to connect to my CMS using powershell but the server name for CMS has an instance name and all of the script I find online only has the server name.I cant figure out the combination I need to use to make it work$serverGroupPath = "SQLSERVER:\SQLRegistration\Central Management Server Group\<Server\Instance>\NonProd\Dev"I've tryed " ",' ',(),[] and I figured not putting anything around it, it would think the instance name would be folder.ThanksScott
↧
Getting the error - Add-PSSnapin. added snapin "add-pssnapin SqlServerCmdletSnapin100;" still no luck
Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version2.At line:1 char:13+ add-pssnapin <<<< SqlServerCmdletSnapin100; + CategoryInfo : InvalidArgument: (SqlServerCmdletSnapin100:Strin g) [Add-PSSnapin], PSArgumentException + FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.Ad dPSSnapinCommand
↧
Reading Event Log: speeding up with If Exists equivalent?
In the Jack of all trades role, i've got a web application , that since it connects to SQL server, somehow also falls under my domain.without digging into the code, i know that at some point, an error occurs in the application, that causes it to lock up, and i can fix it by bouncing the application pool related to the web application.so i can actually see the event in the event log, so if i used powershell to search the event log, i could use a WMI call to bounce the app pool.all that works fine...but the issue is the test of reading the event log takes a loooong time; i'd like to speed it up, especially if it finds anything;it currently takes the same amount of time for a positive result and a negative result, which is 2.5-3 minutes.any suggestions to speed an inquiry like this up?[code]$start = Get-Date -format "dd-MMM-yyyy HH:mm:ss"Write-Host $startif(Get-EventLog -ComputerName GDC-WEB-P01 -LogName Application -EntryType Error,Warning -After ((Get-Date).addminutes(-5)) -Message "*Exception message: Specified cast is not valid.*"){Write-Host "The event occured, bouncing the application pool."}else{Write-Host "All clear, no work performed."}$now = Get-Date -format "dd-MMM-yyyy HH:mm:ss"Write-Host $now$val =NEW-TIMESPAN –Start $start –End $nowWrite-Host $val #00:02:41 in my case[/code]
↧
Unable to override the values of the configuration.ini file while doing SQL Install/Uninstall
HI GuysPlease suggest how would I be able to override the values of $action, $features,$INSTANCENAME , etc....to pass the values in the below section to override the values of "install" by "uninstall" etc and run the program so that I can use the same .ini files for sql install/uninstall purposes or at a better choice I could be able to update the values dynamically to give argument to powershell to install sql with such parameter valuesplease suggest how to write it$CONFIGURATIONFILE = "C:\test\Install_ConfigurationFile.ini" & $fileExe /CONFIGURATIONFILE=$CONFIGURATIONFILE clear-host$ini=get-content "C:\test\Install_ConfigurationFile.ini"$iniclear$ACTION = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'ACTION=*'} $FEATURES = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'FEATURES=*'} $INSTANCENAME = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'INSTANCENAME=*'} $INSTANCEID = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'INSTANCEID=*'} $SQLSYSADMINACCOUNTS = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'SQLSYSADMINACCOUNTS=*'} #Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'IAcceptSQLServerLicenseTerms=*'} $UpdateEnabled = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'UpdateEnabled=*'} $SQMREPORTING = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'SQMREPORTING=*'} $ERRORREPORTING = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'ERRORREPORTING=*'} $INDICATEPROGRESS = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'INDICATEPROGRESS=*'} $QUIET = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'QUIET=*'} $ACTION $FEATURES$INSTANCENAME$INSTANCEID$SQLSYSADMINACCOUNTS$UpdateEnabled$SQMREPORTING$ERRORREPORTING$INDICATEPROGRESS$QUIET$fileExe = "C:\SQL2012_X64_Copied\setup.exe";#$dir = Split-Path $fileExetry{$CONFIGURATIONFILE = "C:\test\Install_ConfigurationFile.ini" & $fileExe /CONFIGURATIONFILE=$CONFIGURATIONFILE echo INSTALLATION SUCCESSFULLY COMPLETED >> .\install_log.txt}catch {echo INSTALLATION ERROR (ERRORLEVEL=%ERRORLEVEL%) >> .\install_log.txt}
↧
↧
Need double quote in between a variable (Stirng Operation)
Hi Experts,Please help me getting a double quote in between the string. Thereafter I will write a logic to delete that specific folder which I can easily manage through test-path.$INSTALLSHAREDDIR = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'INSTALLSHAREDDIR=*'} ##O/P : INSTALLSHAREDDIR="c:\Program Files\Microsoft SQL Server"$INSTALLSHAREDDIR = Get-Content "C:\test\Install_ConfigurationFile.ini" | Where-Object {$_ -like'INSTALLSHAREDDIR=*'} $INSTALLSHAREDDIR = $INSTALLSHAREDDIR + "\MSSQL11.INST3"$INSTALLSHAREDDIR1 = $INSTALLSHAREDDIR -replace '"', """"o/P: INSTALLSHAREDDIR=c:\Program Files\Microsoft SQL Server\MSSQL11.INST3Want the output as (within double quotes):-"c:\Program Files\Microsoft SQL Server\MSSQL11.INST3"Thanks
↧
How to add a comma in between two strings
Hi,I want to add a comma in between these two strings. "domain1\OracleDBATeam" "domain1\SQLDBA TEAM"I tried with the below approach:$SQLSYSADMINACCOUNTS = Get-Content "C:\test\Install_ConfigurationFile_2012.ini" | Where-Object {$_ -match 'SQLSYSADMINACCOUNTS='} $pos = $SQLSYSADMINACCOUNTS.IndexOf("=")#$leftPart = $SQLSVCACCOUNT.Substring(0, $pos)$rightPart = $SQLSYSADMINACCOUNTS.Substring($pos+1)$SQLSYSADMINACCOUNTS = $rightPart -replace '"', "" $SQLSYSADMINACCOUNTS = """$SQLSYSADMINACCOUNTS""" -replace '\s+', ', ' # I think I need to append, instead of replace.$SQLSYSADMINACCOUNTSO/P is coming as :"domain1\OracleDBATeam" , "domain1\SQLDBA, TEAM"Any suggestion, how to refine it?
↧
Unable to read the encrypted password.
HiI used the below command to accept password. But unable to print the password entered.Please help me with the correct format to decrypt the password? I don't want to hard-code the password to my script.$SQLServiceAGTPassword = read-host "Enter a Password for SQL Agent AC:" -assecurestring | ConvertTo-SecureString -AsPlainText -Force$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SQLServiceAGTPassword)$RetrievePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)Write-Host "Password is: " $SQLServiceAGTPassword
↧
Script to find if a SQL Server Instance Exist
Kindly provide a good script to check if a sql server instance does exist. If not need to throw a good alert. I'm trying using the below script, but taking long time to execute. Any better way to write it, plz suggest $instance = "domain\INST4" $serverObject = New-Object Microsoft.SqlServer.Management.Smo.Server($instance) $instance = $instance.toupper() $serverName = $serverObject.ComputerNamePhysicalNetBIOS $serverName = $serverName +"\"+$serverObject.InstanceName $serverName
↧
↧
Check Existence of server with search progress and time took to retrieve the server (if present in the domain)
Hi,I am trying to search if a server is present, it will show the progress (using write-progress activity in a loop) and tell me the time it took to fetch the details. Unable to compose the script to check the time takes to fetch the server record and progress, Please help/suggest.[quote]clear-hostfunction checkserver{ $Global:instance= Read-Host "Enter the SQL Service Instance Name [Dont use "" "" in the servername]:`n" write-host "You entered server name as:" $instance $serverObject = New-Object Microsoft.SqlServer.Management.Smo.Server($instance) $instance = $instance.toupper() $serverName = $serverObject.ComputerNamePhysicalNetBIOS $serverName = $serverName +"\"+$serverObject.InstanceName #$serverName IF ( $serverName -ne "\") { $sess = new-pssession $serverName Print $serverName invoke-command -session $sess -scriptblock {start-job -name Date1 -scriptblock {get-date}} write-host "Server:" "'$serverName'" "exist" -ForegroundColor Green Write-Progress -Activity "Working..." ` $done = invoke-command -session $sess -command {wait-job -name Date1} $done.count } ELSEIF ( $serverName -eq "\") { #$sess = new-pssession $serverName #invoke-command -session $sess -scriptblock {start-job -name Date1 -scriptblock {get-date}} write-host "Wrong Server name" -ForegroundColor Red #$done = invoke-command -session $sess -command {wait-job -name Date1} #$done.count } }[/quote]
↧
Execute SQL Script on remote server with another windows account
Hi All,I have a set of SQL server Instances in another domain connected to my machine. These instances use windows authentication to login and all the instances use different accounts.I am trying to come up with a script which can run on all the instances either with Powershell/Vbs/Batch files, that can connect to each of theses instances and execute a SQL script but don't know how to switch windows account for each sql execution. Any help or at least pointing me in the right direction would help.Please note that my ID is like DomainA\User1 but other servers have sysadmin accounts like DomainB\UserX, DomainC\UserY.Thanks for your help
↧
Unable to generate the results in a proper pipe or ";" delimited format
HiNeed the output of the results to a comma / semi colon / pipe delimited format.Function RunningSQLServices{[CmdletBinding()] Param ( [Parameter(Position=0,Mandatory=$true)][string]$filepath #Enter filename containing server names with single quotes , [Parameter(Position=1,Mandatory=$true)][string]$outfile #Enter path with single quotes (The file will be recreated if you use the same output file.) )Process{ $result=@() ForEach ($objitem in get-content $filepath) { $result += $objitem |out-file $outfile $result += get-service -ComputerName $objitem -displayname *SQL*| Where-Object {$_.status -eq "Running"}| Select-Object Machinename, Status,Name,DisplayName | format-table -auto -wrap -force } #$result | export-csv $outfile -Delimiter "|" -NoTypeInformation$result | out-file $outfile#$result | Export-Csv -Path 'C:\service_status1.txt' -Delimiter ';' –notype#$result |export-csv -delimiter "$" -path $outfile}}## This is the way to trying to convert. But no luck.$path = 'C:\service_status1.txt'$outPath = $path -replace ".txt",".csv"Get-Content -path $path | ForEach-Object {$_ -replace "\s",";" } | Out-File -filepath $outPath
↧