Hello,I searched for this on here and google and didn't see an exact answer to my question, so sorry if it's been asked and answered before. If I run a query using Invoke-Sqlcmd and put it in a variable: $results = Invoke-Sqlcmd -Query $query -ServerInstance $QueryServer -Database $QueryDB;and I get multiple rows back, I see that $results has a type of System.Array. I can get a count of the number of returned results by using $results.Length.However if I get only 1 row back, the Type is Syste.Data.DataRow and $results.Length is NULLI've gotten around this by creating a new variable called ResultsLen and doing the following:$resultsLen = $results.<field in query>.Length$resultsLen += $results.Lengthbut this doens't really work, as the $results.<field in query>.Length is a count of the number of characters in the returned field. this works for what I need...which is just to run a IF statement to only run some code if there are 1+ records returned in the query...but I'm wondering if there is a better way of doing it?Thanks.
↧
Invoke-Sqlcmd Count
↧
Windows Batch, VBScript and PowerShell
I have written tons of Windows Batch scripts and compiled VB6, however not as much VBScript. That said, I seen have entire books about managing Windows with VBScript and I know there are many people out there that use it a lot. PowerShell being the newest kid on the block I am not aware of anything VBScript offers that PowerShell does not. Maybe manipulating Windows GUI components? If I were learning a new scripting language for Windows from the ground up in hopes of having it become my one-stop-shop for all my scripting needs is there a specific reason or use-case where you might recommend VBScript or Windows Batch over PowerShell?
↧
↧
SSRS report powershell script
I have SSRS 2008R2 reporting having 3 data sources.Say reportname = \Marketing\Test.rdlDataSource name = \Shared DataSources\Data1 , 2 ,3Now when deploy the report using reports manager upload functionality , after deployment it looses all three connection reference.is there any powershell script to set again correct datasource for this 1 report.
↧
How to pass a response to a .exe called by PoSh
I'm calling an command line .exe from within a PoSh script. This is generating a hit Y for Yes / N for No choice. How can I send a Y in my PoSh script?Thanks!
↧
collecting a count of errorlogs using posh
Hi, I am running a script to collect a count of all errors in the current error log using smo, as below:$sqlServer = new-object ("Microsoft.SqlServer.Management.Smo.Server") "MYSERVER"$logs = $sqlServer.ReadErrorLog() | where {($_.Text -like "Error*" -or $_.Text -like "*Fail*") -and ($_.Text -notlike "*Found 0 Errors*")};$count = $logs.Count$countand then dumping this into a monitor database.This works fine for most servers, but I have a 2005 cluster that for some reason won't return the count. If I just read the error log into console that works fine, but the .Count method disappears completely from the object. It is like, for this server, the object returned from $sqlServer.ReadErrorLog() is different to the rest of the servers.Any ideas?Thanks for reading.
↧
↧
Getting printers on a remote PC in a workgroup
I'm trying to learn PowerShell. So I did a [b]Get-Help Get-Printer -examples[/b] and saw that I can issue the command [b]Get-Printer -ComputerName[/b] [i]<computer name>[/i]. So, that's what I tried to do, but it doesn't work in my home network. Is this because I only have a peer-to-peer workgroup at home? Do commands like [b]Get-Printer -ComputerName[/b] [i]<computer name>[/i] only work in Active Directory domains?
↧
Risks/Best practices on execution policy
While it would be easy to set the execution policy to unrestricted, or possibly set it to unrestricted in an agent job, do the work, then set back to restricted, I'm wondering what the best practices are.Restricted - No scripts can be run. Windows PowerShell can be used only in interactive mode.AllSigned - Only scripts signed by a trusted publisher can be run.RemoteSigned - Downloaded scripts must be signed by a trusted publisher before they can be run.Unrestricted - No restrictions; all scripts can be run.
↧
Determining if a server is clustered or stand-alone
I'm in the process of writing a powershell script to inventory my SQL Server environment. In collecting the server information, I'd like to grab the physical hostnames that make up any clustered environments. I know I can use $nodes=get-clusternode -Cluster SERVERNAME |select nameto get the physical servers in the cluster, but if I run that on a non-clustered server, I get an error, obviously. So, can someone recommend a good way to determine whether the SERVERNAME I've connected to is a cluster resource group or a physical stand-alone server?
↧
Sql Inventory Script: Fill method fails
I found a sql server inventory script that seems to be available on several sites. It actually seems to generate all of the reports but fails on the SqlDataAdapter fill method whether named pipes is turned on or not. If I remote desktop to the server and run it I don't get this error.[b]fill : Exception calling "Fill" with "1" argument(s): "A network-related or instance-specng a connection to SQL Server. The server was not found or was not accessible. Verify thahat SQL Server is configured to allow remote connections. (provider: Named Pipes Providerction to SQL Server)"At C:\powershell\GetServerInfo3.ps1:27 char:9+ $da.fill <<<< ($ds) | Out-Null + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException[/b][url=https://www.simple-talk.com/sql/database-administration/let-powershell-do-an-inventory-of-your-servers/][/url][url=http://colleenmorrow.com/2012/05/31/building-a-sql-server-inventory-part-2/][/url]
↧
↧
Run SSIS package from Powershell
I have the following powershell script:$html_file_dir = "C:\Scripts"$cvs_file = "C:\Scripts\SpaceFiles\DiskSpace_20130327060003.csv"$loadFile = "$cvs_file"$dbServer = "."$dbName = "ServerSpaceReports"#DBServer ,DBName$constring = "Data Source=$dbServer;Initial Catalog=$dbName;Provider=SQLNCLI10.1;Integrated Security=SSPI;Auto Translate=False;"#Data Source=.;Initial Catalog=ServerSpaceReports;Provider=SQLNCLI10.1;Integrated Security=SSPI;Auto Translate=False;#"\Package.Variables[User::PlanID].Properties[Value]";"1"$DTexecPath = "C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\DTExec"#cd $DTexecPath$setPackageVars = "/Set \Package.Variables[""CSVFile""].Value;" + """$loadFIle"""$command = " /F C:\scripts\Package.dtsx $setPackageVars"$commandDTExec.exe $command When I run this I get an error:Option " /F C:\scripts\Package.dtsx /Set \Package.Variables[CSVFile].Value;C:\Scripts\SpaceFiles\DiskSpace_20130327060003.csv" is not valid.If I take the same thing and run it from a command line it runs successfully.I have no idea why this may be failing can any one help me out.Thanks Gary
↧
INSERT statements containing regex as a string being read as regex
I am attempting to run a sql script with 4 simple INSERT statements. Each of the 4 INSERTS is inserting a regexp as an NVARCHAR string. 2 of them have within the string the combination of "$(" without quotes of course and 2 of them don't.I am holding the script contents in a variable and then executing nonquery, but I keep getting an error for the INSERTS containing the "$(". I know this is a sqlcmd replacement variable combination so i assume something similar is going on here in PoSH.Can anyone provide a better way to do this or provide a workaround?Snippet:FUNCTION runSql () { $dbName = "someDb" $tSql = "path\somesql.sql" [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SQLServer.SMO") | Out-Null$srv = NEW-OBJECT Microsoft.SqlServer.Management.Smo.Server("someServer")$db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, $dbName)$db.Create() $sr = New-Object System.IO.StreamReader($tSql) $script = $sr.ReadToEnd() $extype = [Microsoft.SQLServer.Management.Common.ExecutionTypes]::ContinueOnError $db.ExecuteNonQuery($script, $extype)}INSERTS causing issues:INSERT INTO [dbo].[regexes] ([regex]) VALUES (N'%(NS)(.[^\^]{1,12}|\^)\^*(.[^\$]+)\$(.[^\^\$]+|\${1,35})\$*\w*\^(.[^\^]{1,29}|\^)\^*\?;636013(\d+)=\d+=\?#"\s(\w+\s\w+)\s+')INSERT INTO [dbo].[regexes] ([regex]) VALUES (N'%(TX)(.[^\^]{1,12}|\^)\^*(.[^\$]+)\$(.[^\^\$]+|\${1,35})\$*\w*\^(.[^\^]{1,29}|\^)\^*\?;636015(\d+)=\d+\?#"\s(\d+)\s')
↧
Orphaned DB?
So I am exploring PowerShell, and found a DB with .Databases that I can't see in sys.databases.I ran this following (starting from the Machine level with sqlps):[code="other"] $i = ls $i | %{$_.Databases}[/code]It returns a list of all the DBs, but there is one that says that the state is Normal, Standyby.I don't see it through SSMS, and it isn't in sys.databases.What could cause this and what should I do about that?
↧
Pass parameter into XML file using Powershell
Hi,I have a project to automate SQL server restore.........use restore db's using third party tool called Simpana, Commvault.....we would like to automate the restore using powershell....i can restore the database using commnd prompt and powershell but to automate its pretty complicated.We usually do restore in Simpana using its GUI...and Simpana has some commands for restore...and when using GUI we have an option to save the restore process as script...it saves as .xml file and .dat file.... To restore the database using powershell we need to use that xml file or we can create a dynamic xml file using that format..i was able to do that....here is the dynamic xml file that i'm generating...i need to pass parameters in to this xml file e.g., db name, destination db name ,source server,dest server Please let me know if anyone have any questions or need more information....$template_Power = "<TMMsg_CreateTaskReq> <taskInfo> <task> <taskFlags> <disabled>false</disabled> </taskFlags> <policyType>DATA_PROTECTION</policyType> <taskType>IMMEDIATE</taskType> <initiatedFrom>COMMANDLINE</initiatedFrom> <alert> <alertName></alertName> </alert> </task> <associations> <backupsetName>defaultBackupSet</backupsetName> <subclientName></subclientName> <clientName></clientName> <appName>SQL Server</appName> <instanceName></instanceName> </associations> <subTasks> <subTask> <subTaskType>RESTORE</subTaskType> <operationType>RESTORE</operationType> </subTask> <options> <restoreOptions> <browseOption> <commCellId>2</commCellId> <backupset> <clientName></clientName> <backupsetName>defaultBackupSet</backupsetName> </backupset> <timeRange/> <noImage>true</noImage> <useExactIndex>false</useExactIndex> <mediaOption> <library/> <mediaAgent/> <drivePool/> <drive/> <copyPrecedence> <copyPrecedenceApplicable>false</copyPrecedenceApplicable> <synchronousCopyPrecedence>0</synchronousCopyPrecedence> <copyPrecedence>0</copyPrecedence> </copyPrecedence> <proxyForSnapClients> <clientName></clientName> </proxyForSnapClients> </mediaOption> <timeZone> <TimeZoneName>(GMT-05:00) Eastern Time (US & Canada)</TimeZoneName> </timeZone> <listMedia>false</listMedia> </browseOption> <destination> <destClient> <clientName></clientName> </destClient> <destinationInstance> <clientName></clientName> <appName>SQL Server</appName> <instanceName></instanceName> </destinationInstance> </destination> <sqlServerRstOption> <dbOnly>false</dbOnly> <overWrite>true</overWrite> <pointOfTimeRst>false</pointOfTimeRst> <sqlRestoreType>DATABASE_RESTORE</sqlRestoreType> <sqlRecoverType>STATE_RECOVER</sqlRecoverType> <stopStartSSA>false</stopStartSSA> <preserveReplicationSettings>false</preserveReplicationSettings> <stopMarkRestore>false</stopMarkRestore> <stopBeforeMarkRestore>false</stopBeforeMarkRestore> <partialRestore>false</partialRestore> <logShippingOnly>false</logShippingOnly> <ffgRestore>false</ffgRestore> <ignoreFullBackup>false</ignoreFullBackup> <vSSBackup>false</vSSBackup> <device>|DBA_Rep2|#12!DBA_Rep2_Test|#12!DBA_Rep|#12!D:\MSSQL\DATA\DBA_Rep2_Test.mdf|#12!D:\MSSQL\DATA\DBA_Rep2.mdf</device> <device>|DBA_Rep2|#12!DBA_Rep2_Test|#12!DBA_Rep_log|#12!L:\MSSQL\LOG\DBA_Rep2_Test_log.ldf|#12!L:\MSSQL\LOG\DBA_Rep2_1.ldf</device> <restoreSource>DBATest</restoreSource> <database>DBATest</database> <timeZone> <TimeZoneName>(GMT-05:00) Eastern Time (US & Canada)</TimeZoneName> </timeZone> <keepDataCapture>false</keepDataCapture> </sqlServerRstOption> <fileOption> <mapFiles/> </fileOption> <commonOptions> <detectRegularExpression>true</detectRegularExpression> <restoreDeviceFilesAsRegularFiles>false</restoreDeviceFilesAsRegularFiles> <restoreSpaceRestrictions>false</restoreSpaceRestrictions> <ignoreNamespaceRequirements>false</ignoreNamespaceRequirements> <skipErrorsAndContinue>false</skipErrorsAndContinue> <onePassRestore>false</onePassRestore> <revert>false</revert> <recoverAllProtectedMails>false</recoverAllProtectedMails> <isFromBrowseBackup>false</isFromBrowseBackup> <clusterDBBackedup>false</clusterDBBackedup> </commonOptions> </restoreOptions> <adminOpts> <updateOption/> </adminOpts> <commonOpts> <startUpOpts> <startInSuspendedState>false</startInSuspendedState> <priority>66</priority> <useDefaultPriority>true</useDefaultPriority> </startUpOpts> <prePostOpts> <preRecoveryCommand></preRecoveryCommand> <postRecoveryCommand></postRecoveryCommand> <impersonation> <!--PrePost Command Impersonation Level--> <level>NO_SELECTION</level> <user> <userName></userName> </user> </impersonation> <runPostWhenFail>false</runPostWhenFail> </prePostOpts> <!--User Description for the job--> <jobDescription></jobDescription> </commonOpts> </options> </subTasks> </taskInfo></TMMsg_CreateTaskReq>"$template_XML > C:\Program Files\Commvault\simpana\Base\template_restXML.xml
↧
↧
Can't script the schema for a FK
Hi,I use the below script to script out FKs in a database:#DECLARE TIMESTAMP FOR THE FILES$timestamp = Get-Date -Format yyyy-MM-dd#SCRIPTSL SQLSERVER:\SQL\'MyServer'\DEFAULT\Databases\'MyDB'\Tables$so = new-object Microsoft.SqlServer.Management.Smo.ScriptingOptions$so.IncludeIfNotExists = 1$so.SchemaQualify = 1$so.SchemaQualifyForeignKeysReferences = 1$so.ScriptSchema = 1dir | foreach {$_.ForeignKeys} | foreach {$_.Script()} > "Z:\MyDB\03_FKs $timestamp .sql"The result I get looks like this:ALTER TABLE [MySchema].[MyTable1] WITH CHECK ADD CONSTRAINT [FK_MyTable1_MyTable2_ID] FOREIGN KEY([ID])REFERENCES [MyTable2] ([ID])ON DELETE CASCADEI am getting an error when using the above script:Msg 1767, Level 16, State 0, Line 1Foreign key 'FK_MyTable1_MyTable2_ID' references invalid table 'MyTable2'.Msg 1750, Level 16, State 0, Line 1Could not create constraint. See previous errors. The reason for this is because MyTable2 belongs to a schema other then 'dbo', so the generated script should look like this:ALTER TABLE [MySchema].[MyTable1] WITH CHECK ADD CONSTRAINT [FK_MyTable1_MyTable2_ID] FOREIGN KEY([ID])REFERENCES [b][MySchema].[/b][MyTable2] ([ID])ON DELETE CASCADEAny ideas?Thanks. Quick Reply
↧
Problem copying .bak with "$" in file path/name (PS running in SQL job step)
I'm using OLA's SQL JOBs to do my database maintenance. So far, I really like them; they're very handy, especially when apps create new databases each month (WILDCARD dbnames!).I have to copy files across server instances on occasion; since we're deploying SQL2008r2 I've started using Powershell to do this.I've got a powershell job step that works fine to get bak files from my old servers to new servers.But now I have to copy a backup created by the Ola backup process... it includes $ in the path (as servername$instancename) and at the start of the backup file name.It LOOKS like the $ is confusing Powershell...Is there a control character I can use to allow the "$" into the path/filename, or is there [b]another [/b]way to do this?[code="plain"]#Example: (this is a powershell step in a sql job)# get yesterdays date as YYYYMMDD$dd = (get-date).AddDays(-1).ToString("yyyyMMdd")# here's the original source/target location for the backup file#$from = "\\srvrname\r$\SQL\MSSQL10_50.instname\MSSQL\Backup\srvrname$instname\DBNAME\FULL\srvrname$instname_DBNAME_FULL_" + $dd + "*.BAK"#$to = "\\SA01SQL002\u$\SQL\MSSQL10_50.TEST\MSSQL\Backup\from$instname\"#and here's the error on the copy-item line:# 'An object at the specified path \\srvrname\r$\SQL\MSSQL10_50.instname\MSSQL\Backup\srvrname\DBNAME\FULL does not exist.'# ********# whoops... that should say \srvrname$instname\## that blows up so tried wrapping $from and $to within a double quote... this didn't fly either.$from = """" + ...TheOriginalString... + """"$to = """" + ...TheOriginalString... + """"# the error references this line copy-item $from $to -Force -Recurse[/code]
↧
how can i get Powershell
to search stored procedures for server names?we have the list of server names, but not sure if we must script the procedures out and search for server names from the server name list on the file system or is it possible to use the server list and search the procedures traversing each db on a server?thanks a lotdrew(powershell illiterate)
↧
Retrieve data and log file names from SQL database
Hi,I'm trying to pull the logical and physical file names from sql server database using powershell and add those values in exisiting xml file...This whole process is for database restore...we don't do direct sql db restore..we use third party tool called Commvault...that is the reason for restore automation...Here's my code....its just a part of it....param([Parameter(Mandatory="True")][String]$ClientName,[Parameter(Mandatory="True")][String]$Sourcedatabase#[Parameter(Mandatory="True")][String]$Destdatabase)$SqlConnection = New-Object System.Data.SqlClient.SqlConnection$SqlCmd = New-Object System.Data.SqlClient.SqlCommand$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter#$DataSet = New-Object System.Data.DataSet$SqlConnection.ConnectionString = "Server = $ClientName; Database = $RestoreSource; Integrated Security = True"$SqlCmd.CommandText = "select d.name dbname,f.name logicalfilename,f.physical_name from sys.master_files f, sys.databases d where f.database_id = d.database_id and d.name = '$Sourcedatabase' and f.type = 0 " $SqlCmd.Connection = $SqlConnection$SqlAdapter.SelectCommand = $SqlCmd$SqlAdapter.Fill($DataSet)|out-null$dbs = $DataSet.Tables[0]$dbs $SqlConnection.Close()In the above sql server i'm just trying to pull data file with type = 0..its working fine...if i put type =1 i can get log file info....please let me know how to get data and log file information, such that i can path those information into xml file ...like below<device>|SourceDB|#12!DestinationDB|#12!SourceLogicaldatafilename|#12!Destinationdatafilepath|#12!Sourcedatafilepath</device><device>|SourceDB|#12!DestinationDB|#12!SourceLogicallogfilename|#12!Destinationlogfilepath|#12!Sourcelogfilepath.ld </device>all fields needs to filled accordingly...if we have more than one data file...then it hsould populate n number of device tags....Please help me on this...thanks....let me know if you have any questions...
↧
↧
replace string in path using powershell
Hi,i'm trying to get the default sql server data and log file path using the below script...[quote]param($ClientName,$DESTINATIONDB)$SqlConnection = New-Object System.Data.SqlClient.SqlConnection$SqlCmd = New-Object System.Data.SqlClient.SqlCommand$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter$DataSet = New-Object System.Data.DataSet$SqlConnection.ConnectionString = "Server = $ClientName; Database = '$DESTINATIONDB'; Integrated Security = True"$SqlCmd.CommandText = "select f.physical_name from sys.master_files f, sys.databases d where f.database_id = d.database_id and d.name = 'master'" $SqlCmd.Connection = $SqlConnection$SqlAdapter.SelectCommand = $SqlCmd$SqlAdapter.Fill($DataSet)|out-nullforeach ($Row in $Dataset.Tables[0].Rows){ $dev = $($Row[0]) $dev }[/quote]i'm getting the output like thisC:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\master.mdfC:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\mastlog.ldfi would like to replace the name of master in the above path my paramter $destinationDB.Please let me knowthanks in advance
↧
Inserting Active Directory Data into a SQL Server table
I wanted to gather Active Directory data into SQL Server table to analyze permissions on critical data. I wanted to use a SQL Server Agent Job that would refresh a couple of time per day. I also wanted it to be as clean and portable as possible, so I tried to run everything within the server itself and not rely on external resources which tend to complicate matters. This task seems pretty straight forward, however due to limitations in the OLE DB driver for Microsoft Directory Services and limitations in Powershell it has become quite a chore. The first problem I ran into was trying to bring in "description" from AD using a linked server. The query returned the error: Cannot get the data of the row from the OLE DB provider "ADSDSOObject" for linked server "ADSI". Could not convert the data value due to reasons other than sign mismatch or overflow.Upon further examination I found that the "description" field in AD is a "multi value" field and the OLE DB provider doesn't know what to do with it so it errors. I then turned to Powershell which has been held up as the future of Microsoft product integration. Though it's a powerful tool, and did exactly what it was supposed to while running in a Command Prompt, once I put it into a SQL Job it threw a syntax error because the job engine could not parse the following line of code: $Command.CommandText = "INSERT INTO Test(Name, Title, Phone, description) Values('$($Name)', '$($Title)', '$($Phone)', '$($description)')"I guess I will have to create an external .PS1 file and run it as an Operating System (CMDExec) file unless someone has a better suggestion.
↧
Unable to automate the Script
The below script provides the list of trace files available to the location : D:\Trace$fileEntries = [IO.Directory]::GetFiles("D:\Trace\"); foreach($fileName in $fileEntries) { [Console]::WriteLine($fileName); }I want to pass each trace files to the below block to change the trace files compatible to SQL 2008 R2 format.# Enter your filename here$fileName = "D:\Trace\XXXX.trc" # The version information we want to write: 0x0A = 10 = SQLServer 2008[Byte[]] $versionData = 0x0A# The offset of the version information in the file$offset = 390 [System.IO.FileMode] $open = [System.IO.FileMode]::OpenOrCreate$stream = New-Object System.IO.FileStream -ArgumentList $fileName, $open$stream.Seek($offset, [System.IO.SeekOrigin]::Begin);$stream.Write($versionData, 0, $versionData.Length);$stream.Close()Kindly assist....
↧