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

Problem with escaping periods from powershell piped variable

$
0
0
Hi EveryoneI am writing a very basic scripts which pulls info from one DB and pushes it to another. I wont go into reasons for doing this etc.The pulling is working correctly and I am building an array of the results.When I do the following is when i run into issues:$data | ForEach-Object {Invoke-Sqlcmd -Database $database -ServerInstance $server -Query "insert into $table (SessionIdTime, SessionIdSeq) VALUES ('$_.SessionIdTime', '$_.SessionIdSeq')"}The results in the table come out as follows:SessionIdTime SessionIdSeqSystem.Data.DataRow.SessionIdTime System.Data.DataRow.SessionIdSeqSo it is recognising the $_ part but then it looks to me like the period (.) is causing the next part to be text. I have tried various ways of escaping it with no luck.I can get it to work by creating a variable for each one in the foreach loop but this seems inefficient i.e:$data | ForEach-Object {$SessionIDTime = $_.SessionIDTime ; $SessionIdSeq = $_.SessionIdSeq ; Invoke-Sqlcmd -Database $database -ServerInstance $server -Query "insert into $table (SessionIdTime, SessionIdSeq) VALUES ('$SessionIdTime', '$SessionIdSeq')"}Your assistance with this would be highly appreciated. RegardsBrendon

How to get list of pending HotfixID from a remote server using Powershell

$
0
0
Is there a way to get list of Pending HotfixID yet to be installed from a windows 2012 server remotely using Powershell?

datetime and string conversion problem

$
0
0
Hi EveryoneIm pulling some data out of one database with a query that looks like:[quote]$localquery = "SELECT [SessionIdTime],[SessionIdSeq],[InviteTime],[FromUri],[ToUri],[FromUriType],[ToUriType]..........$data = Invoke-Sqlcmd -serverinstance "localhost" -query $localquery[/quote]If I look at the object type of the "SessionIdTime in the $data array it is a date time object and contains the milliseconds that have been pulled from the database.I then put this info into another database (Dont ask :D):[quote]foreach ($d in $data){$qry = "insert into $table VALUES ('$($d.SessionIdTime)', '$($d.SessionIdSeq)', '$($d.InviteTime)', '$FromUri', '$ToUri', '$($d.FromUriType)'.........Invoke-Sqlcmd -Database $database -ServerInstance $server -Query $qry}[/quote]The problem comes in where during this insert the value is put in as a string and the milliseconds are lost which are key to this requirement.I have tried to change the this and do a check as follows:[quote]foreach ($d in $data){$check = $d.SessionIdTime | get-date$qry = "insert into $table VALUES ('$check', '$($d.SessionIdSeq)', '$($d.InviteTime)', '$FromUri', '$ToUri', '$($d.FromUriType)'.........Invoke-Sqlcmd -Database $database -ServerInstance $server -Query $qry}[/quote]I then get the error:Invoke-Sqlcmd : Conversion failed when converting datetime from character string.The value in the array is definitely a date object and there is no other code between this.The field is a datetime field in the destination database.Your assistance with this is much appreciated.

Get $ sign with -match

$
0
0
"this transaction will cost $600" -match "\`$ \d{1,3}"I want matches[0] $600what am I missing ?

Changing entries in a .ini file using powershell

$
0
0
Hello,I am currently working on automating SSRS installs and need a way of changing a few entries in the .ini file. I've done a fair bit of reading, but there seems (as there always is) several ways of going about it, and I'm having trouble picking a direction.I'm thinking I can Get-Content and then replace some entries (service account, instance name, service account etc..), but when I replace them, do I set them up as parameters or variables at the beginning?I also read that I can get the contents into a hash table, change the entries, and then right back to disk, but from what I have read this does not appear the best way.Ideally, I'd like be able to have something that allows me to do something like...NAME OF POWERSHELL SCRIPT Param1- "instancename" -Param2 "ServiceAccount" etc.orNAME OF POWERSHELL SCRIPT $instancename "TheInstanceName", $SrvAccount "ServiceAccount"...but I am not sure of the initial direction to go in. Would someone please provide me with some advice on what I need to use/employ to get started down this road? I'd also like to hear how some of the more experienced guys here would go about it, perhaps that will help me.I thought that I would need to start the script with a list of variables or parameters laid out then have, say, Get-Content to get the file contents and replace the existing entries with the new values.Does this seem correct? Thank you in advance for any advice given.Kind regards,D.

Disable NIC on remote server in powershell

$
0
0
Hi I have a requirement to disable NIC using powershell remotely. I'm using below command. It works when i hardcode NIC's Name in the command but it is failing when i pass the NIC's Name in variable. Working Fine: [code="other"]Invoke-Command -Computer MYREMOTESERVER {(Disable-NetAdapter –Name "Trunk1" –Confirm:$false)}[/code]Failing: [code="sql"]Invoke-Command -Computer MYREMOTESERVER {(Disable-NetAdapter –Name $NICName –Confirm:$false)}[/code]

List SSL Certificates and List SSL Certificate Bindings

$
0
0
Hello,I have a question about the above Methods. Running $wotevah.ListSSLCertificates() Provides the following details (when run on my local Win7 machine)...__GENUS : 2__CLASS : __PARAMETERS__SUPERCLASS : __DYNASTY : __PARAMETERS__RELPATH : __PROPERTY_COUNT : 5__DERIVATION : {}__SERVER : __NAMESPACE : __PATH : CertificateHash : {THE_LONG_HASH_NUMBER}CertName : {FQDN of Machine}Hostname : {FQDN of Machine}HRESULT : 0Length : 1PSComputerName : ...now looking at ListSSLCertificateBindings, the parameters are...LCIDThe locale to use for the error messages that are returned.Application[][out] The applications that have certificate bindings.CertificateHash[][out] The hashes for the certificates.IPAddress[][out] The IP address for the applications.Port[][out] The port number stored in the binding in rsreportserver.config.Errors[][out] The descriptions for errors that occurred.Length[out] The length of the array returned by the method.HRESULT[out] Value indicating whether the call succeeded or failed....but I am not sure how to use these parameters and get the Method to work. Do I need to use some of the output from the first method? I cant find an example of actual syntax in action to copy, or use as a guide. Would love a bit of help.Thank you,D.

Why SMO return a lot of emty properties and how to filter only ones containing values

$
0
0
Example my station has SSMS 2008R2 # SQL server ( myserver\inst1) is SQL 2014 STD code executed from station [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | out-null$srv = new-Object Microsoft.SqlServer.Management.Smo.Server('myserver\inst1,7889')$svr | fl * -- return empty values for most of properties ( example - I cut most of the properties)OutputCollation : CollationID : Edition : ServiceAccount : ServiceInstanceId : ServiceName : DefaultTextMode : TrueConnectionContext : server=''myserver\inst1'';Trusted_Connection=true;Application Name='SQL Management';multipleactiveresultsets=falseState : Existing1.Why most of the properties empty ? 2. how can filter out output result and return only properties with values something like $svr | where {$_.value -ne ''} | fl *

Powershell error

$
0
0
I have a loop statement in powershell, and it's give me error. I think that "+$Row2+" as 'col 2' is not right.anyone could help? Thanks so much[quote]foreach($Row in $DataSet.Tables[0].Rows){ $Row1 $Row2= $Row[0] $Row3= $Row[1] $Row4= $Row[2] $Row5= $Row[3] $Query_grab = " use "+$Row2+" select * from ( select '12' as 'col 1' "+$Row2+" as 'col 2' from table a left outer join table b on a.id = b.id group by b.groupname ) as x"[/quote]

Retrieve InstallationID from an XML document. Almost there but...

$
0
0
Hello,I am trying to automate the initialization of the Report Server in SSRS Configuration Manager using Powershell.So far I have worked out that I can use the InitializeReportServer Method which requires the InstallationID as a parameter. This can be found in the rsreportserver.config XML file and appears like this..<InstallationID>{d63c8ae2-003e-4f3e-bdae-faa7688b7a79}</InstallationID>...so I retrieve it using this...$XML=[XML](Get-Content 'C:\Program Files\Microsoft SQL Server\MSRS11.MSSQLSERVER\Reporting Services\ReportServer\rsreportserver.config')$InstID = $XML.DocumentElement | Select InstallationID$SSRSConMgr = Get-WmiObject -Namespace "root\Microsoft\SqlServer\ReportServer\RS_MSSQLSERVER\v11\Admin" -Class MSReportServer_ConfigurationSetting -ComputerName $env:COMPUTERNAME$SSRSConMgr.InitializeReportServer([string]$InstID)...however, it returns the result with the curly braces included, so I get an error when I try to use the variable as a parameter...__GENUS : 2__CLASS : __PARAMETERS__SUPERCLASS : __DYNASTY : __PARAMETERS__RELPATH : __PROPERTY_COUNT : 2__DERIVATION : {}__SERVER : __NAMESPACE : __PATH : ExtendedErrors : {The parameter value provided for 'InstallationID' does not match the parameter type. (rsParameterTypeMismatch), Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).}HRESULT : -2146233088PSComputerName : ...so my questions is, how do I return the result, but exclude the curly braces?Any help, is as always, greatly appreciated.Kind regards,D.

Need to generate 1 script per object (indexes)

$
0
0
Hello - Have been looking all over for a solution that will allow me to script out my Non-Clustered Indexes to a single file for each index. The closest thing I have found was from Vince Panuccio (SmoDB version 1.0 Powershell script), but it does not generate a file for the NCI's.I wanted to see if I was to post it here, if someone might be able to either tell me how to modify it (to include the NCI's) or just show me a better example. Since this script belongs to someone else, I didn't know if it would be appropriate or not to include it here, but my hope is to find a solution (and I will forward the change on to them upon successfully doing so). Here is the Powershell script:[code="plain"]################################################################################################################################## Script Name : SmoDb# Version : 1.0# Author : Vince Panuccio# Purpose :# This script generates one SQL script per database object including Stored Procedures,Tables,Views, # User Defined Functions and User Defined Table Types. Useful for versionining a databsae in a CVS.## Usage : # Set variables at the top of the script then execute.## Note :# Only tested on SQL Server 2008r2# ################################################################################################################################$server = "sandy"$database = "DBA"$output_path = "C:\SQL\Script"$schema = "dbo"$table_path = "$output_path\Table\"$storedProcs_path = "$output_path\StoredProcedure\"$views_path = "$output_path\View\"$udfs_path = "$output_path\UserDefinedFunction\"$textCatalog_path = "$output_path\FullTextCatalog\"$udtts_path = "$output_path\UserDefinedTableTypes\"[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server$db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")$tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($server)# Get the database and table objects$db = $srv.Databases[$database]$tbl = $db.tables | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject } $storedProcs = $db.StoredProcedures | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject } $views = $db.Views | Where-object { $_.schema -eq $schema } $udfs = $db.UserDefinedFunctions | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject } $catlog = $db.FullTextCatalogs$udtts = $db.UserDefinedTableTypes | Where-object { $_.schema -eq $schema } # Set scripter options to ensure only data is scripted$scripter.Options.ScriptSchema = $true;$scripter.Options.ScriptData = $false;#Exclude GOs after every line$scripter.Options.NoCommandTerminator = $false;$scripter.Options.ToFileOnly = $true$scripter.Options.AllowSystemObjects = $false$scripter.Options.Permissions = $true$scripter.Options.DriAllConstraints = $true$scripter.Options.SchemaQualify = $true$scripter.Options.AnsiFile = $true$scripter.Options.SchemaQualifyForeignKeysReferences = $true$scripter.Options.Indexes = $true$scripter.Options.DriIndexes = $true$scripter.Options.DriClustered = $true$scripter.Options.DriNonClustered = $true$scripter.Options.NonClusteredIndexes = $true$scripter.Options.ClusteredIndexes = $true$scripter.Options.FullTextIndexes = $true$scripter.Options.EnforceScriptingOptions = $truefunction CopyObjectsToFiles($objects, $outDir) { if (-not (Test-Path $outDir)) { [System.IO.Directory]::CreateDirectory($outDir) } foreach ($o in $objects) { if ($o -ne $null) { $schemaPrefix = "" if ($o.Schema -ne $null -and $o.Schema -ne "") { $schemaPrefix = $o.Schema + "." } $scripter.Options.FileName = $outDir + $schemaPrefix + $o.Name + ".sql" Write-Host "Writing " $scripter.Options.FileName $scripter.EnumScript($o) } }}# Output the scriptsCopyObjectsToFiles $tbl $table_pathCopyObjectsToFiles $storedProcs $storedProcs_pathCopyObjectsToFiles $views $views_pathCopyObjectsToFiles $catlog $textCatalog_pathCopyObjectsToFiles $udtts $udtts_pathCopyObjectsToFiles $udfs $udfs_pathWrite-Host "Finished at" (Get-Date)[/code]I did try adding $index_path = "$output_path\index\", but to no avail.Many thanks in advance

how in powershell (smo and scripter or other object )list tables with dependencies,indexes,FK,constrains

$
0
0
Hi, we need to output list of tables with dependencies, indexes ,FK, constrains I used TSQL and scripted info using ---run in msdb to test it--run with output to grid to avoid warning about tables with no indexSET NOCOUNT ONdeclare @tbl varchar(100), @schema varchar(100) , @schema_table varchar(200) if OBJECT_ID('tempdb..#tmp0')is not null drop table #tmp0 create table #tmp0( tablename varchar(100), constrains text, ObjectsThatDependOnTable text, AllIndexes text, DefaultConstraints text, HasReferenceToTables text, ReferedByTables text ) if OBJECT_ID('tempdb..#tmp4')is not null drop table #tmp4 create table #tmp4(index_name varchar(100),index_description varchar(100),index_keys varchar(100))declare C1 cursor forselect table_schema, table_name from INFORMATION_SCHEMA.TABLES open c1fetch c1 into @schema, @tblwhile @@FETCH_STATUS = 0begin set @schema_table = @schema +'.'+@tbl insert into #tmp4 exec sp_helpIndex @schema_table insert into #tmp0 (tablename, constrains,allIndexes, DefaultConstraints, ObjectsThatDependOnTable, HasReferenceToTables, ReferedByTables) select @tbl, ( select '['+ constraint_type + ' = ' + CONSTRAINT_NAME + ']' AS [text()] FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS where TABLE_NAME = @tbl and TABLE_SCHEMA = @schema and constraint_type !='CHECK' FOR XML PATH('') ), ( select '[Name = (' + index_name + ') Type = (' + index_description + ') keys = (' + index_keys + ')]' AS [text()] from #tmp4 FOR XML PATH('') ), ( select '[DFC NAME = ' +c.name + ';DFC COLUMN = ' + col.name + '; DFC VALUE = '+ definition + '] ' AS [text()] from sys.default_constraints c inner join sys.columns col on col.default_object_id = c.object_id inner join sys.objects o on o.object_id = c.parent_object_id inner join sys.schemas s on s.schema_id = o.schema_id where s.name = @schema and o.name = @tbl FOR XML PATH('') ), ( SELECT '[ '+ o.type_desc + ' '+ IsNull(object_schema_name(Referencing_ID),'*No Ref. to schema*')+'.'+ object_name(Referencing_ID) +']' AS [text()] FROM sys.sql_expression_dependencies INNER JOIN sys.objects AS o ON referencing_id = o.object_id WHERE referenced_id =object_id(@schema_table) for xml path('') ) , ( SELECT distinct '['+ object_name(referenced_object_id) + ']' AS [text()] FROM sys.foreign_keys WHERE parent_object_id = object_id(@schema_table) for xml path('') ) , ( SELECT distinct '['+ object_name(parent_object_id) + ']' AS [text()] FROM sys.foreign_keys WHERE referenced_object_id = object_id(@schema_table) for xml path('') ) truncate table #tmp4 fetch c1 into @schema, @tblendclose c1deallocate c1Question ... SQL server management studio provide with option to view object dependencies example SSMS->table->View dependencies I am assuming SMO and scripter object used to generate and present those values Please point me to direction how to get similar view of dependencies using Powershell so far my attempts to use Database.Script Method did not provide me any results https://technet.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.database.script(v=sql.105).aspx Thank you

Powershell job issues

$
0
0
So I am trying to schedule a powershell job on SQL Server[code="plain"]set-location "c:\Users\sqlagent\Documents".\Funcion_Get-Connection_New.ps1.\Test-ADGroupExists.ps1.\Get-ImpactProjects.ps1$DstDB = $null.\Check_DB_LoginsUsersRoles.ps1 "parm0" $DstDB "parm2" "parm3" "parm4"[/code]In the last script, Check_DB_LoginsUsersRoles.ps1, a call is made to a function created in Get-ImpactProjects.ps1. But the Job History shows an error saying that function could not be found ("is not recognized as a cmdlet, function, ..." etc.What am I doing wrong?

How to add a filter to a variable.

$
0
0
Hello,I hope someone can offer some guidance. I have written a function to set some SSRS settings. It all worked well until I added a couple more SSRS instances. Now, even though I specify the instance name when I call it, the script tries to do all the SSRS instances it finds. I just want it to do the one I specify when I call it. From what I understand I need to apply a filter, but I am not sure where or how, and whether I could apply the filter at the global variable level, rather than on each of the functions that contains the variable. The variable is "SQLInstanceName".Here is my code...function fn-Set-SSRS-ReportServer-VirtualDirectory ([String]$SQLInstanceName, [String]$SSRSDatabaseServerName, [String]$SSRSDatabaseServerTcpPort, [String]$InstID){ Try { $SSRSConMgr = Get-WmiObject -Namespace "root\Microsoft\SqlServer\ReportServer\RS_$SQLInstanceName\v11\Admin" -Class MSReportServer_ConfigurationSetting -ComputerName $ManagedComputer $SSRSConMgr.SetDatabaseConnection("$SSRSDatabaseServerName,$SSRSDatabaseServerTcpPort","ReportServer", 2, "", "") $SSRSConMgr.SetVirtualDirectory("ReportServerWebService", "ReportServer", "3081") $SSRSConMgr.ReserveURL("ReportServerWebService","http://+:80","3081") $SSRSConMgr.ReserveURL("ReportServerWebService","http://+:443","3081") $SSRSConMgr.SetVirtualDirectory("ReportManager", "Reports", "3081") $SSRSConMgr.ReserveURL("ReportManager","http://+:80","3081") $SSRSConMgr.ReserveURL("ReportManager","https://+:443","3081") $XML=[XML](Get-Content "E:\Program Files\Microsoft SQL Server\MSRS11.$SQLInstanceName\Reporting Services\ReportServer\rsreportserver.config") $InstID = $XML.DocumentElement.InstallationID.Trim("{","}") $SSRSConMgr.DeleteEncryptedInformation() $SSRSConMgr.InitializeReportServer($InstID) $Result = $SSRSConMgr.Isinitialized if ($Result -ne 'True') { Throw "$Result and $Error[0]" } } Catch { Write-Error $Result } }Thank you for reading.Kind regards,D.

Get-ChildItem where is property -LiteralPath?

$
0
0
I needed to move files (using powershell V2) finely I found one liner to do the job,to my understanding Move-Item use -LiteralPath parameter --- (Accept pipeline input? true (ByPropertyName))but how it submitted to Move-Item if Get-ChildItem has no property name LiteralPath (only Fullname)Get-ChildItem -Path C:\Application\Log\*\*.Log | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-90) } | Move-Item -Destination { "\\NASServer\Archives\{0}\" -f $_.Directory.Name } example taken from --https://becomelotr.wordpress.com/2013/04/30/event-1-my-way/

If SQL DB exists, dont run function. If it doesnt run function.

$
0
0
Hello, I have created the script below, it works well, but I need to put a line in there to check whether the report server database exists or not before running the function. If it does exist, I'd like to exit the SQL provider (pop-location), and continue on with the rest of the functions. But I am not sure how to do this. Do I need to write another function, or can I add a line in somewhere between the 'Set-Location' line and the 'Invoke-SqlCmd' line? I am also not sure if I can use a powershell line, or another Invoke-SqlCmd line.Any help would be great, and thank you for taking the time to read/respond.Function fn-Set-SSRS-Create-RS-DB ([String]$ManagedComputer, [String] $SqlInstanceName, [String]$SSRSDatabaseServerName, [Int]$SSRSDatabaseServerTCPPort)#{#Try { Push-Location Import-Module "SqlPS" -DisableNameChecking $SSRSConMgr = Get-WmiObject -namespace "root\Microsoft\SqlServer\ReportServer\RS_$SqlInstanceName\v11\Admin" -Class MSReportServer_ConfigurationSetting -ComputerName $ManagedComputer $CreateSSRSDB = $SSRSConMgr.GenerateDatabaseCreationScript("ReportServer","3081","False") Set-Location SQLSERVER:\SQL\$SSRSDatabaseServerName Invoke-Sqlcmd -query $CreateSSRSDB["Script"] -ServerInstance $SSRSDatabaseServerName Pop-Location #if ($Result -ne (0)) #{ #Throw "Failed to create ReportServer Database : $Error[0]" #} #} #Catch #{ #$Error[0] #}}

Import-Module SqlPS running too slowly

$
0
0
Hi All,I have the following installed on a machineWindows Server 2008 R2SQL Server 2012 PowerShell 3Microsoft SQL Server 2012 Feature Pack Powershell toolsMy problem is that whenever i run a script that uses the invoke-sql scmdlet, it takes an huge amount of time. I believe this is because it is importing the module automatically each time (i.e. import module sqlps).Is there any way to install the invoke-sql cmdlet as an inbuilt feature of powershell? This would make my scripts run almost immediately instead of taking minutes as they do now.

Prompt For Choice

$
0
0
Hi,I am very new to writing in powershell, so bear with me.My aim is to get a list of certificates and prompt the user to select which certificate they require. In my head I want the output0 Cert11 Cert23 Cert3Select your cert 0, 1, 2This is where I have got to from internet research. Appreciate any help.[code="plain"]$caption = “Select the certificate you require” $message = “Select the desire certificate” $choices = [System.Management.Automation.Host.ChoiceDescription[]] ` @(Get-ChildItem -path cert:\LocalMachine\My) [int]$defaultChoice = 0 $choiceRTN = $host.ui.PromptForChoice($caption,$message, $choices,$defaultChoice) [/code]

deleting email from mailbox and saving then to sql server

$
0
0
Hi I am working on script to save emails to database and delete them using example https://sqlnotesfromtheunderground.wordpress.com/2014/08/14/delete-emails-older-than-x-days-from-outlook-specific-folder-with-powershell/My delete code $MailBox = "SQLDBA@MYDomain.com"$Subfolder = "DBA_ALERTS"# Outlook Connection$Outlook = New-Object -ComObject Outlook.Application# Outlook folder to clean$EmailsInFolder = $Outlook.Session.Folders.Item($MailBox).Folders.Item($Subfolder).Items $OlderThenDays = 1$Today = get-date$counter = 0$EmailsInFolder.countforeach ($email in $EmailsInFolder){ $difference = New-TimeSpan -Start $email.SentOn -End $Today if ($difference.Days -ge $OlderThenDays) { $difference.Days $email.SentOn $email.Subject $email.Delete()$counter ++ } }Write-Host $countercode is working but does not delete all selected emailfolder contain 500+ email meeting condition but foreach loop does not delete all selected emails at once I have to run code several times and each time it delete different amount of emails in decreasing order 205,96,4815Do I have to call some other metod or set specific property in object in order to delete all selected emails at once ?

Free eBook today: SQL Server 2012 with PowerShell V3 Cookbook

$
0
0
[url=https://www.packtpub.com/packt/offers/free-learning]https://www.packtpub.com/packt/offers/free-learning[/url]
Viewing all 467 articles
Browse latest View live


Latest Images