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

Retrieving Data From Hyphenated Server

$
0
0
What better place to solve a nagging Powershell issue than good ol' SQL Server Central :)I'm trying to retrieve disk usage data from servers on my domain. Server list is pulled from a simple text file on the local computer, each server is then queried for disk information, data is saved in a table, data is written to a database table.This was taken from somewhere on the internet and tweaked to work in my environment, and it has worked splendidly until I was asked to incorporate additional servers that had hyphenated names.[code="other"]#define servers to be monitored$server = get-content C:\<path>\serverList.txt#data table to hold resultsFunction out-DataTable { $dt = new-object Data.datatable $First = $true foreach ($item in $input){ $DR = $DT.NewRow() $Item.PsObject.get_properties() | foreach { if ($first) { $Col = new-object Data.DataColumn $Col.ColumnName = $_.Name.ToString() $DT.Columns.Add($Col) } if ($_.value -eq $null) { $DR.Item($_.Name) = "[empty]" } elseif ($_.IsArray) { $DR.Item($_.Name) =[string]::Join($_.value ,";") } else { $DR.Item($_.Name) = $_.value } } $DT.Rows.Add($DR) $First = $false } return @(,($dt))}#function to retrieve disk informationFunction Get-DisksSpace ([string]$Servername, $unit= "GB"){$measure = "1$unit"Get-WmiObject -computername $serverName -query "select SystemName, Name, DriveType, FileSystem, FreeSpace, Capacity, Label from Win32_Volume where DriveType = 2 or DriveType = 3" `| select SystemName ` , Name ` , @{Label="SizeIn$unit";Expression={"{0:n2}" -f($_.Capacity/$measure)}} ` , @{Label="FreeIn$unit";Expression={"{0:n2}" -f($_.freespace/$measure)}} ` , Label}#execute the functionsforeach ($s in $server){#Write what is being retrievedGet-DisksSpace $s#Load into table and database$dataTable = Get-DisksSpace $s | where {$_.name -like "E:\*" -or $_.name -like "C:\*"} | out-DataTable$connectionString = "Data Source=<Server\Instance>; Integrated Security=True;Initial Catalog=<DestinationDB>;"$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString$bulkCopy.DestinationTableName = "<Schema.Table>"$bulkCopy.WriteToServer($dataTable)}[/code]This returns all the information requested except for a system name for hyphenated servers. If you run just the Get-WmiObject cmdlet, two different results are returned.[code="other"]Get-WmiObject -computername computername -query "select SystemName from Win32_Volume where DriveType = 2 or DriveType = 3" [/code]Returns[quote]__GENUS : 2__CLASS : Win32_Volume__SUPERCLASS : __DYNASTY : __RELPATH : __PROPERTY_COUNT : 7__DERIVATION : {}__SERVER : __NAMESPACE : __PATH : SystemName : [b]COMPUTERNAME[/b][/quote][code="other"]Get-WmiObject -computername computer-name -query "select SystemName from Win32_Volume where DriveType = 2 or DriveType = 3" [/code]Returns[quote]__GENUS : 2__CLASS : Win32_Volume__SUPERCLASS : __DYNASTY : __RELPATH : __PROPERTY_COUNT : 1__DERIVATION : {}__SERVER : __NAMESPACE : __PATH : SystemName : [/quote]I've tried surrounding the computer-name with single and double quotes. I've tried escaping the hyphens with backquotes " ` ". Has anyone else ran into this issue before?

Help making my RestoreDB script better pls?

$
0
0
I'm a total noob with posh :-) I got it powershell running and then hacked together this script.I was following the article about powershell restores (https://www.simple-talk.com/sql/backup-and-recovery/backup-and-restore-sql-server-with-the-sql-server-2012-powershell-cmdlets/).I made a script based on this, but I had some further needs not met in the article.First, SingleUserMode. Maybe it's just my environment, but restores of our big DB doesn't work without this. Application just keeps making connections. Second, I have to perform some actions I've currently figured was easiest done with TSQL. Here I'm just looking at the last restore date.In reality, I have to reset passwords, remove/add logins, attach logins to users, sometimes run a special script to change some default settings... Just a few executenonquery type of things.I'll also have to add moving the backup file as well or as a separate method/function. Whats it called when you encapsulate in powershell?First, if there is a 100% powershell way to do most of these things, I'd love to learn it!But I'd also love to learn how one would best run a query with results and without results against a server.And that last bit? That's a total hack on displaying the information. Can anyone point to a better way to displaying it? [code="plain"]cls#import SQL Server moduleImport-Module SQLPS -DisableNameChecking# Sets context for getting a db reference.# I use the reference to change the user access and verify the backup date after the restoreSet-Location SQLSERVER:\SQL\(server)\(instance)\Databases\(database)$dbName = "db"$db = Get-Item .echo $db.UserAccess# The next few lines handle changing the databases user access mode which prevents restoring due to active connections# I run this if the db is set to Multiple (it normally is)#$db.UserAccess = "Multiple"$db.UserAccess = "Single"$db.Parent.KillAllProcesses($dbName)$db.Alter()Restore-SqlDatabase -Database $dbName -BackupFile "(backup path).bak" -ReplaceDatabase # Here and below is my TSQL hammer approach to solve the problem of verifing the restore date on the DB we're attempting to restore.# I'm sure that this can be done more elegantly within Posh and even using a TSQL query, this has to be a hacky way to display the output of a known schema result.cls$BackupTimeQuery = @"SELECT TOP 1 destination_database_name As dbname, restore_date, user_name As RestoredBy FROM msdb.dbo.restorehistory RH WHERE RH.destination_database_name = '$dbName' ORDER BY restore_date DESC;"@<# Commented out the StringCollection as I don't need it for a single query# Setting up StringCollection to use with ExecuteWithResults for multiple queries. $sqlQuery = new-object System.Collections.Specialized.StringCollectionQuery to find the most recent backup of the DB being restored. $sqlQuery.Add("")#>$ds = $db.ExecuteWithResults($BackupTimeQuery)# Please don't anyone use this as an example, but please do suggest a better way to display multiple fields of a single row returned within Posh.Foreach ($t in $ds.Tables){Foreach ($r in $t.Rows){Foreach ($c in $t.Columns){Write-Host $c.ColumnName "=" $r.Item($c)}}}[/code]

Open Excel Error Using PowerShell in SQL Server Agent Job

$
0
0
I am trying to run a Powershell script, which opens and modifies an Excel spreadsheet, from a SQL Agent job step, . The script runs fine by itself, and from BIDS. I have tried running as an SSIS pkg with a proxy, and when that didn't work I setup the step to simply run the Powershell script.This is the error I receive:A job step received an error at line 17 in a PowerShell script. The corresponding line is '$Workbook=$objExcel.Workbookds.Open("\\files\reporting\Dailyreport_MMDDYYYY.xls",0,$False,1,"password")'Correct the script and reschedule the job.The error information returned by PowerShell is: "Exception calling "Open" with "5" arguments(s)."Microsoft Excel cannot access the file "\\files\reporting\Dailyreport_MMDDYYYY.xls".There are several possible reasons: The file name or path does not exist [i](Yes, it does!)[/i]The file is being used by another program [i](No, it’s not!)[/i]The workbook you are trying to save has the same name as a currently open workbook." [i](No again, no workbooks open)[/i]Process Exit Code -1. The step failedIt appears that it does not want to open Excel, but why?FYI: 64-bit System, 64-bit SQL 2008 R2, 32-bit Office 2010. I have already tried adding "Desktop" to SysWoW64 and editing my DCOM settings, with no change in results.Thanks,Lorna

Write PowerShell Output to SQL Server Table

$
0
0
Heh... First time I've had to admit being a "newbie" in a long time so be gentle with me. I might not even know enough to ask the right questions.I managed to pick up the following PS script from the internet. Lot's of you know what it is. It gets some disk space information from every disk device for the given computer. I've removed all field formatting just to keep it super simple.[code="plain"]Get-WmiObject Win32_LogicalDisk -computer 'SomeComputerName' | Select SystemName,DeviceID,VolumeName,Size,FreeSpace | Format-Table[/code]What I'd like to do is write the output to a table in a given SQL Server. I've Googled for answers and have found some (IMHO) very over complicated methods. Some are generic (which is very cool) but not what I need. I just want to write this one output to a table.The table for this example is simple as well (I've removed all but the necessary columns including a Date/Time column)...[code="sql"] CREATE TABLE dbo.DiskSpace ( SystemName VARCHAR(128), DeviceID CHAR(2), VolumeName VARCHAR(128), Size BIGINT, FreeSpace BIGINT );[/code]I realize that we're going to need a connection to the database. I'd like it to be a trusted connection so we don't have to hardcode a user name or password. Assume that the server name is "TestServer" and that the database name is "TestDB". From what I've been able to read up on, the business of the connection would look something like this (please correct it if I'm wrong)...[code="plain"]$conn=new-object System.Data.SqlClient.SQLConnection $ConnectionString = "Server=TestServer;Database=TestDB;Integrated Security=True;Connect Timeout=0"$conn.ConnectionString=$ConnectionString $conn.Open()...something goes here but I don't know what... $conn.Close() [/code]Like I said, I'm brand-spanking-new to PowerShell. I sure could use some help on how to get the data from the first script above into the table that I posted the CREATE TABLE code for without having to build a bunch of functions like in the following link.[url]http://blogs.technet.com/b/heyscriptingguy/archive/2010/11/01/use-powershell-to-collect-server-data-and-write-to-sql.aspx[/url]Thanks for the help, folks. And, yeah... if you have a good book recommendation for the syntax and how to "start thinking in PowerShell" like I do in T-SQL, it would also be much appreciated.

Count imported Files

$
0
0
I need following in the script.- Compair the Field [b]"Count_import"[/b] of delivered with "Count_fault" document and send a E-Mail if there is a difference or Count_Fault>0have write a script, which works fine but what is missing is, when field Count_Fault > 0, then a email should be sent to me.There is my Script which checks two Directory and write it to DB Tabel TBL_Import.Table:TBL_Import********************************************IDX Count_Import Count_Fault Date_Import Send_Message1 182 0 29.06.2013 21:11:10 MyScript*****************************************************$strFilter = "(&(objectCategory=person)(objectClass=user))"$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://dc=dom,dc=de")$Searcher = New-Object System.DirectoryServices.DirectorySearcher$Searcher.SearchRoot = $objDomain$objSearcher = New-Object System.DirectoryServices.DirectorySearcher$objSearcher.SearchRoot = $objDomain$objSearcher.PageSize = 200$objSearcher.Filter = $strFilter$objSearcher.SearchScope = "Subtree"$colProplist = "Count_Import", "Count_Fault", "Date_Import"## Get a count of files in a directory.#$directory_file_count = "0"$directory_fault_count = "0"$Import_directory_pdf = "N:\Import Files" $Import_directory_fault = "N:\Fault Files" # check that the directory exists.$does_directory_exist = (Test-Path $Import_directory_pdf)# if it does, then continueif ($does_directory_exist){# file count does include directories but not a count of their contents.$directory_file_count = (get-childitem $Import_directory_pdf -filter *.pdf).count$directory_fault_count = (get-childitem $Import_directory_fault -filter *.tif).countWrite-Host "Directory file count: $directory_file_count"Write-Host "Directory fault count: $directory_fault_count"}else{# directory doesn't existWrite-Host "Directory $server_directory_string - DOES NOT EXIST"}foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}$colResults = $objSearcher.FindAll()$Connection = New-Object System.Data.SqlClient.SqlConnection("Data Source=mydatabase;Initial Catalog=mydata;Integrated Security=SSPI")$Connection.Open()$Command = $Connection.CreateCommand()#ForEach ($objResult in $colResults)#{$Count_Import = $directory_file_count$Count_Fault = $directory_fault_count$Date_Import = get-date $Command.CommandText = "INSERT INTO TBL_IMPORT(Count_Import, Count_Fault, Date_Import) Values('$($Count_Import)', '$($Count_Fault)', '$($Date_Import)')"$Command.ExecuteNonQuery()#}$Connection.Close() Edited: Today @ 8:31:58 PM by zero1de

Getting Cluster information from Powershell scripts

$
0
0
HiI am logged in remotely to a workstation and connecting locally to sql server 2008r2 cluster node. Is there a way to run Powershell scripts to get information about the cluster environment?

Update Table with get-date

$
0
0
Hi,i want to update my table Field Date_Import=get-date -f (without time)TBL_Import [Count_Import] int NULL,[Count_Fault] int NULL,[Date_Import] date NULL$Command = $Connection.CreateCommand() $Count_Fault = $directory_file_count $Date_used = get-date $Command.CommandText ="update TBL_IMPORT set Count_Fault=$Count_Import where $Date_Import=$date_used" $Command.ExecuteNonQuery() $Connection.Close()What is wrong in my code ? the Problem is on where clause ..Many THXI get this Msg: Ausnahme beim Aufrufen von "ExecuteNonQuery" mit 0 Argument(en): "Incorrect syntax near '16'."Bei D:\Skripte\Count_Fault.ps1:54 Zeichen:27+ $Command.ExecuteNonQuery <<<< () + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException

Powershell script being run as SQL agent job

$
0
0
Hi everyone.I have a powershell script that lists all backup status across various servers.Script runs fine via Powershell gui (Normally) Sometimes I see an issue. Think it is regarding Excel and how it outputs its results.I can see that when the spreadsheet is created, it leaves the excel.exe*32 running on my machine.Unless I close that , or go into spreadsheet and exit it, subsequent runs also fail.When not there , runs fine.However when run as SQL agent job it always fails.this is the error.A job step received an error at line 88 in a PowerShell script. The corresponding line is '$Excel.SaveAs("Y:\SQL\Failedjobs.xlsx")'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Exception calling "SaveAs" with "1" argument(s): "SaveAs method of Workbook class failed"Any tips on how to correct this , or what I am doing wrong and need to check ?many thanks

Run SQL Server 2012 package with Project environment

$
0
0
Hi experts,I try to launch SSIS 2012 packages stored into SSISDB with PowerShell. In my SSISDB, I have several Project environements (DEV,PROD,...); I would like to change project environnement from my PS script but I can't.[code="other"]function launch_package(){ $instanceName = "MYSERVER" $SSISDBFolderName = "MyFolder" $projectName = "MyProject" $packageName = "MyPackage.dtsx" $SSISEnvironmentName = "DEV" # import SQL Server module Import-Module SQLPS -DisableNameChecking # load the IntegrationServices assembly Add-Type -AssemblyName "Microsoft.SqlServer.Management.IntegrationServices, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" $connectionString = "Data Source=$instanceName;Initial Catalog=master;Integrated Security=SSPI;" $conn = New-Object System.Data.SqlClient.SqlConnection $connectionString $SSISServer = New-Object Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices $conn $SSISDB = $SSISServer.Catalogs["SSISDB"] $SSISDBFolder = $SSISDB.Folders[$SSISDBFolderName] $SSISDBAssoc = $SSISDBFolder.Environments[$SSISEnvironmentName] # Here is the issue : $SSISDBAssoc.References.Add($SSISEnvironmentName) $SSISDBAssoc.Alter() $SSISDBAssoc.Projects[$projectName].Packages[$packageName].Execute($false, $null) }[/code]Error message is : You cannot call a method on a null-valued expression.Any one can help ?

Integrity check output to file using Invoke-Sqlcmd failing

$
0
0
Hi all, I am having fun trying to get a PowerShell called database integrity check to output to a file. This is so I can then search the output for specific lines/words to reduce the ammount to be read.This works:[code="other"]& sqlcmd -S $servername -E -Q "dbcc checkdb(N'$($dbName)') with all_errormsgs" >"$($ResultFile)"[/code]but it feels like cheating when there is Invoke-Sqlcmd but I cannot get Invoke-Sqlcmd to produce the output to file.This produces an empty file:[code="other"]Invoke-Sqlcmd -ServerInstance $servername -Query "dbcc checkdb(N'$($dbName)') with all_errormsgs" | out-file "$($ResultFile)"[/code]The following produces an error about not recognising -ServerInstance (I guess it is linking the switch to Add-Content)[code="other"]Add-Content $ResultFile Invoke-Sqlcmd -ServerInstance $servername -Query "dbcc checkdb(N'$($dbName)') with all_errormsgs"[/code]So I put the Invoke-Sqlcmd into bracers but this only produces an empty result file.[code="other"]Add-Content $ResultFile (Invoke-Sqlcmd -ServerInstance $servername -Query "dbcc checkdb(N'$($dbName)') with all_errormsgs")[/code]For the times that do not produce an error, time does pass before the prompt comes back so I guess it is performing the check.Does anyone know how to get Invoke-Sqlcmd to output to a file, or should I give up and use the command prompt code (which works).

Powershell error - Ok in ISE , fails in Agent job

$
0
0
Morning all.I am trying to run script to get Translog details. The script works fine in ISE and produces report as expected. Produces excel report etc.When it runs in an agent job it fails with the following error:Executed as user: XXXXXX. A job step received an error at line 56 in a PowerShell script. The corresponding line is '$logInfo = $db.LogFiles | Select Name, FileName, Size,UsedSpace'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'The following exception was thrown when trying to enumerate the collection: "An exception occurred while executing a Transact-SQL statement or batch.". '. Process Exit Code -1. The step failed.This is part of that script.$intRow++ $logInfo = $db.LogFiles | Select Name, FileName, Size, UsedSpace If ($loginfo.UsedSpace / $loginfo.Size * 100 -gt 50) { $dbname = $db.Name $Sheet.Cells.Item($intRow,2) = $dbname $Sheet.Cells.Item($intRow,3) = ($logInfo.Size / 1024) $Sheet.Cells.Item($intRow,4) = ($logInfo.UsedSpace / 1024) $Sheet.Cells.Item($intRow,5) = ($loginfo.UsedSpace / $loginfo.Size * 100) $Sheet.Cells.Item($intRow,5).Interior.ColorIndex = 3 } else { $dbname = $db.Name $Sheet.Cells.Item($intRow,2) = $dbname $Sheet.Cells.Item($intRow,3) = ($logInfo.Size / 1024) $Sheet.Cells.Item($intRow,4) = ($logInfo.UsedSpace / 1024) $Sheet.Cells.Item($intRow,5) = ($loginfo.UsedSpace / $loginfo.Size * 100) $Sheet.Cells.Item($intRow,5).Interior.ColorIndex = 14 } }I am doing anything wrong there ?Confused over how it works fine in ISE but fails as a SQL agent job.Any advice appreciated.

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

Insert xml data into SQL server via SqlBulkCopy with powershell (casting error)

$
0
0
I tried to strip down this example to make it as terse as possible so it would be easy to read\answer.I'm getting a "cast not valid" error when trying to insert a data table containing xml using sqlbulckcopy.I cast the DataColumn that will hold the xml data to type System.Xml.XmlNode is that incorrect? Looking [url=http://msdn.microsoft.com/en-us/library/cc716729.aspx]here [/url]it just says the .NET Framework type is xml.Here an example of some xml data (located in C:\test\test.xml) I want to insert:<!-- Edited by XMLSpy® --><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>Here is the script I am using to try and insert it:[quote]$SQLDBName = 'test'$SQLServer = 'myserver,1433' #Open connection to sql DB$connectionString = "Server = $SQLServer;Integrated Security=true;Initial Catalog=$SQLDBName;"#$connectionString = "Server = $SQLServer;Data Source=SQLSERVER;Integrated Security=true;Initial Catalog=$SQLDBName;"$SQLConnection = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString$SQLConnection.DestinationTableName = "ForwardedEvents"#create columns for datatable and set their types$columns = @()$columns += #Order MUST match that of the DB(New-Object System.Data.DataColumn -ArgumentList @("EventLogXML" , [System.Xml.XmlNode] ))#build datatable for bulk insert$dt = New-Object System.Data.DataTable$columns | %{$dt.Columns.add($_) | Out-Null}$row = $dt.NewRow() #Create row$row.Item("EventLogXML") = [xml](cat C:\test\test.xml)$dt.Rows.Add($row) #add row to table#insert into DB and close connection$SQLConnection.WriteToServer($dt)$SQLConnection.close()[/quote]Running this script I get the following error:[quote]Exception calling "WriteToServer" with "1" argument(s): "Specified cast is not valid."[/quote]

Special method for evaluating Database Properties through conditional statements?

$
0
0
Passing an Instance name for $Instance, this loops through all databases on the instance. Gathers their name and Recovery model. Writes the name and recovery model. However, the conditional statement always evaluates false, despite the database being in Full recovery Mode. Is there some special way to evaluate database properties?[code="plain"]$InstanceObject = New-Object (’Microsoft.SqlServer.Management.Smo.Server’) -argumentlist $InstanceName# loop through all databases within this instance$InstanceObject.Databases | foreach-object { # get database object into a variable $DatabaseObject = $_ $DatabaseName = $DatabaseObject.Name $RecoveryModel = $DatabaseObject.RecoveryModel write-host $DatabaseName $RecoveryModel if($RecoveryModel -eq "Full"){write-host "$DatabaseName is in $RecoveryModel recovery mode"} }[/code]

powershell script through agent job only performing half the steps it should.

$
0
0
Ok. I'm out of ideas.I have a script that grabs a list of sqlserver instances, then connects to each (foreach), executes a query and loads the results into a table.Every time I execute the script through a sql agent job(via cmdexec) , it only queries against 2 of the 4 servers it should.Its run successfully from powershell, powershell ise, starting powershell through sql server, it even runs successfully if I run it through a standard command prompt.Any ideas?

using Sqlpsx functions on a production sql box

$
0
0
There is a very handy cmdlet called Get-sqlerrorlog that I'd like to use but everyone is very strict about installing anything on a production sql server. I want to use it to save off the sql error logs ( specific entries ). I wish there was a way to "embed" the function in the powershell sql agent job so it wasn't dependent on something installed on the server.http://sqlpsx.codeplex.com/releases/view/25394

Powershell script to capture SQL service status

$
0
0
Hello everyoneCan anyone offer some advice on how I would capture SQL server services, i.e started etc for each SQL instance in a .txt file containing the servers I want to look at ?One issue I have is that I need to use SQL authentication to connect to the boxes as they are across different domains.Any tips or help greatly appreciated.All I want is a list exported to excel , Server name , SQL Service status etc.Many thanks for any advice.

Powershell for SQL Server Instructor-Led Class

$
0
0
I keep getting the message that powershell is very usefull for the DBA. I believe it. But I need a class.At SQL Pass Summit I went to several presentations that tended to be givenby very talented people who's approach was to present the clever scripts theywrote and tell what the tricky parts were. Not useful. So I took a 5 day Microsoft instructor led class where I managed to get some of the basics (not easy for an old Cobol dude to grasp) but it did not cover anything aboutSQL Server. The instructor promised to fire up some SQL plugins and do some stuffbut he never got around to it. Marginally usefull. Not worth 5 days and big bucks. I can do stuff with files and Windowsbut nothing with SQL Server (or I could a year ago. I forgot it all).I need to start at square one in an instructor-led class that is targeted at a SQL Server DBA.Does such an animal exist (no, I don't want blogs or books) ?

Retrieve file from web

$
0
0
Hello,I've exhausted myself trying to get this to work with cURL, and am trying to get it to work with PS v3 now. I've stitched together code from a couple places and come up with this:[code="other"]$formFields = @{sendusername='user';password='pass'}invoke-webrequest “http://www.ims-dm.com/cgi/download2.php?productid=WIREFTPM”| -Method Post -Body $formFields select -exp links|where{$_.href -like "*.zip"}|select -exp href|foreach{start-bitstransfer $_ C:\SurveyComputing}[/code]Which results in this:[code="plain"]-Method : The term '-Method' is not recognized as the name of a cmdlet, function, script file, or operable program.Check the spelling of the name, or if a path was included, verify that the path is correct and try again.At line:1 char:81+ ... tid=WIREFTPM”| -Method Post -Body $formFields select -exp links|where{$_.href -l ...+ ~~~~~~~ + CategoryInfo : ObjectNotFound: (-Method:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException[/code]The cURL issue I was running into was something with the URI of the website being obscured by a .php or Java redirect. Not sure if I'll have the same issue with PS, but I'd like to give something else a try.Any suggestions or pointers are appreciated.Thanks

SQL inventory powershell script

$
0
0
Hi everyone.Hope someone can offer some advice on my issue. I have been learning Powershell with the aid of the SQL Server 2008 Administration with Windows Powershell book published by Wrox.Book is good and I have learnt a lot from it. The book covers SQL 2000, SQL 2005 and SQL 2008. Up to a stage now where my inventory also includes SQL 2008 R2 and SQL 2012.I don't think the scripts are configured to capture the correct parameters for capturing SQL 2008 R2 and SQL 2012 details.I have included the full script.Could any one offer me any advice on how to the scripts should be changed to capture SQL 2008R2 and SQL 2012 configs. (and if possible and explanation on what was changed so I can learn from it?) Full script:# ======================================================================================================================# # NAME: Upsert-Server.ps1# # AUTHOR: Yan and MAK# DATE : 6/8/2008# # COMMENT: This script adds a server record into inventory. # If the server already exists, then this script updates the existing server record.# Example: Upsert-Server -instanceName MSSQLSERVER -hostName POWERPC -status U# =======================================================================================================================############################################################################### Initialize parameters ##############################################################################param ( [switch]$help, [string]$instanceName = {}, # Name of the SQL Server instance to add into inventory. For a default instance, it is MSSQLSERVER. [string]$hostName = {}, # Name of the SQL Server host. [string]$clusterName = {}, # Name of the SQL Server cluster. [string]$status = {} # Status of the SQL Server instance. Possible values include D, Q, P, U and R. )# This function connects with a SQL Server instance [$pHostName\$pInstanceName,$pTcpPort] to execute a SQL query $pSql.function execSQL([String] $pHostName, [String] $pInstanceName, [String] $pSql, [String] $pTcpPort){ if ( $pInstanceName -eq 'MSSQLSERVER' ) { (Invoke-Sqlcmd -Query "$pSql" -ServerInstance "$pHostName,$pTcpPort" -Database master).Column1 } else { (Invoke-Sqlcmd -Query "$pSql" -ServerInstance "$pHostName\$pInstanceName,$pTcpPort" -Database master).Column1 }}# This function returns the statements that can be used to get a server configuration in a column called Column1. function getConfigSql([String] $option){ $strSql = "CREATE TABLE #temp (name nvarchar(35), minimum int, maximum int, config_value int, run_value int)`n" $strSql = $strSql + "INSERT INTO #temp EXEC (`'exec sp_configure `'`'$option`'`'`')`n" $strSql = $strSql + "SELECT run_value as Column1 from #temp`n" $strSql = $strSql + "DROP TABLE #temp`n" return $strSql}# This function connects to the HKLM registry hive of the SQL Server host $pHostName # and retrieve the TCP/IP port number that the instance $pInstanceName is listening on. function getTcpPort([String] $pHostName, [String] $pInstanceName){ $strTcpPort="" $reg = [WMIClass]"\\$pHostName\root\default:stdRegProv" $HKEY_LOCAL_MACHINE = 2147483650 # Default instance if ($pInstanceName -eq 'MSSQLSERVER') { #SQL Server 2000 or SQL Server 2005/2008 resides on the same server as SQL Server 2000 $strKeyPath = "SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\SuperSocketNetLib\Tcp" $strTcpPort=$reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,"TcpPort").svalue if ($strTcpPort) { Set-Variable -Name instanceRegPath -Value "SOFTWARE\Microsoft\MSSQLServer\MSSQLServer" -Scope 1 return $strTcpPort } } else { #SQL Server 2000 or SQL Server 2005/2008 resides on the same server as SQL Server 2000 $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\$pInstanceName\MSSQLServer\SuperSocketNetLib\Tcp" $strTcpPort=$reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,"TcpPort").svalue if ($strTcpPort) { Set-Variable -Name instanceRegPath -Value "SOFTWARE\Microsoft\Microsoft SQL Server\$pInstanceName\MSSQLServer" -Scope 1 return $strTcpPort } } #SQL Server 2005 for ($i=1; $i -le 50; $i++) { $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.$i" $strInstanceName=$reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,"").svalue if ($strInstanceName -eq $pInstanceName) { $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.$i\MSSQLServer\SuperSocketNetLib\tcp\IPAll" $strTcpPort=$reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,"TcpPort").svalue Set-Variable -Name instanceRegPath -Value "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.$i\MSSQLServer" -Scope 1 return $strTcpPort } } #SQL Server 2008 $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.$pInstanceName\MSSQLServer\SuperSocketNetLib\Tcp\IPAll" $strTcpPort=$reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,"TcpPort").svalue if ($strTcpPort) { Set-Variable -Name instanceRegPath -Value "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.$pInstanceName\MSSQLServer" -Scope 1 return $strTcpPort } return ""}# This function connects to the HKLM registry hive of the SQL Server host $pHostName # and retrieve the network protocols used by the instance $pInstanceName. function getServerNetWorkProtocols([String] $pHostName, [String] $pInstanceName){ $strProtocols="" $reg = [WMIClass]"\\$pHostName\root\default:stdRegProv" $HKEY_LOCAL_MACHINE = 2147483650 $strKeyPath = "$instanceRegPath\SuperSocketNetLib" #SQL Server 2000 $arrValues=$reg.GetMultiStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,"ProtocolList").sValue if ($arrValues) { $arrValues | foreach -process { $strProtocols=$strProtocols + $_ + ',' } return $strProtocols.Substring(0, $strProtocols.Length-1) } #SQL Server 2005 or 2008 else { $strKeyPath = "$instanceRegPath\SuperSocketNetLib\Tcp" $intEnabled=$reg.GetDWORDValue($HKEY_LOCAL_MACHINE,$strKeyPath,"Enabled").uvalue if ($intEnabled) { if ($intEnabled -eq 1) { $strProtocols='tcp,' } $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.$instanceNo\MSSQLServer\SuperSocketNetLib\Np" $intEnabled=$reg.GetDWORDValue($HKEY_LOCAL_MACHINE,$strKeyPath,"Enabled").uvalue if ($intEnabled -eq 1) { $strProtocols=$strProtocols + 'np,' } $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.$instanceNo\MSSQLServer\SuperSocketNetLib\Sm" $intEnabled=$reg.GetDWORDValue($HKEY_LOCAL_MACHINE,$strKeyPath,"Enabled").uvalue if ($intEnabled -eq 1) { $strProtocols=$strProtocols + 'sm,' } $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.$instanceNo\MSSQLServer\SuperSocketNetLib\Via" $intEnabled=$reg.GetDWORDValue($HKEY_LOCAL_MACHINE,$strKeyPath,"Enabled").uvalue if ($intEnabled -eq 1) { $strProtocols=$strProtocols + 'via,' } return $strProtocols.Substring(0, $strProtocols.Length-1) } }}# This function connects to the HKLM registry hive of the SQL Server host $pHostName # and retrieve the startup parameters used by the instance $pInstanceName. function getStartupParameters([String] $pHostName, [String] $pInstanceName){ $reg = [WMIClass]"\\$pHostName\root\default:stdRegProv" $HKEY_LOCAL_MACHINE = 2147483650 $strKeyPath = "$instanceRegPath\Parameters" $arrValues=$reg.EnumValues($HKEY_LOCAL_MACHINE,$strKeyPath).sNames #SQL Server 2000 if ($arrValues) { for ($i=0; $i -lt $arrValues.Length; $i++) { $strParameters=$strParameters + $reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,$arrValues[$i]).svalue + ";" } return $strParameters } #SQL Server 2005 for ($i=1; $i -le 50; $i++) { $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.$i" $strInstanceName=$reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,"").svalue if ($strInstanceName -eq $pInstanceName) { $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.$i\MSSQLServer\Parameters" $arrValues=$reg.EnumValues($HKEY_LOCAL_MACHINE,$strKeyPath).sNames if ($arrValues) { for ($i=0; $i -lt $arrValues.Length; $i++) { $strParameters=$strParameters + $reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,$arrValues[$i]).svalue + ";" } return $strParameters } } } #SQL Server 2008 $strKeyPath = "SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.$pInstanceName\MSSQLServer\Parameters" $arrValues=$reg.EnumValues($HKEY_LOCAL_MACHINE,$strKeyPath).sNames if ($arrValues) { for ($i=0; $i -lt $arrValues.Length; $i++) { $strParameters=$strParameters + $reg.GetStringValue($HKEY_LOCAL_MACHINE,$strKeyPath,$arrValues[$i]).svalue + ";" } return $strParameters }}############################################################################### Main Program ##############################################################################[String] $strUpsertSql=""[String] $instanceRegPath = '' # Registry path for the instanceif ( $help ) { "Usage: Upsert-Server -serverName <string[]> <<-hostName <string[]>|-clusterName <string[]>> -status <string[]>" exit 0}if ( $instanceName.Length -eq 0 ) { "Please enter an instance name." if ($instanceName -ieq 'mssqlserver') { $instanceName='MSSQLSERVER' } exit 1}if (( $hostName.Length -eq 0) -and ($clusterName.Length -eq 0)) { "Please enter a host name or a cluster name." exit 1}if (( $hostName.Length -gt 0) -and ($clusterName.Length -gt 0)) { "You only need to enter either a host name or a cluster name." exit 1}if ( $status -notmatch '^D|Q|P|U|R$' ) { "The status is invalid. Please enter D, Q, P, U or R." exit 1}[String] $sqlNetworkName="" # For standalone host, it is the same as $hostName. For cluster, it is the same as $clusterName[String] $windowsNetworkName="" # For standalone host, it is the same as $hostName. For cluster, it is the WindowsClusterName from the Clusters table.if ($hostName.Length -gt 0) { $sqlNetworkName=$hostName $windowsNetworkName=$hostName}else { $sqlNetworkName=$clusterName # Find the Windows Cluster Name $strQuerySql="SELECT WindowsClusterName FROM Clusters WHERE SQLClusterName='$clusterName'" $sqlCluster=Invoke-Sqlcmd -Query $strQuerySql -ServerInstance $inventoryServer -Database $inventoryDatabase $windowsNetworkName=$sqlCluster.WindowsClusterName}$tcpPort=(getTcpPort $windowsNetworkName $instanceName)# If tcpPort is not available, the server or the host doesn't exist.if ($tcpPort -eq "") { "Tcp port is not found. Please check the server name and the host/cluster name." exit 2}if ($hostName.Length -gt 0) { $strUpsertSql = $strUpsertSql + "exec uspUpsertServers '$instanceName', '$status', '$hostName', Null, '$tcpPort', "}else { $strUpsertSql = $strUpsertSql + "exec uspUpsertServers '$instanceName', '$status', Null, '$clusterName', '$tcpPort', "}$strUpsertSql = $strUpsertSql + "'" + (getServerNetWorkProtocols $windowsNetworkName $instanceName) + "', "$strQuerySql = "SELECT CASE SUBSTRING(CONVERT(nvarchar, ServerProperty ('ProductVersion')), 1, CHARINDEX('.', convert(nvarchar, ServerProperty('ProductVersion')))-1 ) WHEN '10' THEN '2008' WHEN '9' THEN '2005' WHEN '8' THEN '2000' END"$strUpsertSql = $strUpsertSql + "'" + (execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + "', "$strQuerySql = "Select ServerProperty('Edition')" $strUpsertSql = $strUpsertSql + "'" + (execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + "', "$strQuerySql = "Select ServerProperty('ProductVersion')"$strUpsertSql = $strUpsertSql + "'" + (execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + "', "$strQuerySql = "Select ServerProperty('ProductLevel')"$strUpsertSql = $strUpsertSql + "'" + (execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + "', "$strParameters =(getStartupParameters $windowsNetworkName $instanceName)$strUpsertSql = $strUpsertSql + "'" + $strParameters + "', "$strQuerySql = "select top 1 filename as Column1 from dbo.sysfiles"$strUpsertSql = $strUpsertSql + "'" + (execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort | Split-Path -parent) + "', "$strErrorLog=( $strParameters.Split(";") | where {$_.StartsWith("-e")} )$strUpsertSql = $strUpsertSql + "'" + $strErrorLog.Substring(2, $strErrorLog.Length-2) + "', "$strQuerySql = "Select ServerProperty('Collation')"$strUpsertSql = $strUpsertSql + "'" + (execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + "', "$strQuerySql = ( getConfigSql "min server memory" )$strUpsertSql = $strUpsertSql + ( execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + ", "$strQuerySql = ( getConfigSql "max server memory" )$strUpsertSql = $strUpsertSql + ( execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + ", "$strQuerySql = ( getConfigSql "awe enabled" )$strUpsertSql = $strUpsertSql + ( execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + ", "$strQuerySql = ( getConfigSql "user connections" )$strUpsertSql = $strUpsertSql + ( execSQL $sqlNetworkName $instanceName $strQuerySql $tcpPort) + " "$strUpsertSql = $strUpsertSql + ";"$strUpsertSqlInvoke-Sqlcmd -Query $strUpsertSql -ServerInstance $inventoryServer -Database $inventoryDatabase
Viewing all 467 articles
Browse latest View live