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

PowerShell module into SQL Server

$
0
0
Hello,I'm trying to find a way to burry my PS module into extended stored procedure(XP) in sql server. Any help in guiding me in this direction is highly appreciated.Thanks in AdvanceJagan K

move files from server to server

$
0
0
Hi,I need to move the files base on the query from sql database. The files name is on the table, and I need to move these files to another sever. I was looking at this, http://www.sqlservercentral.com/Forums/Topic1514396-1351-1.aspx, which give me some idea. Anyone have examples, to passed the result from the sql query, and loop thru to move the physical files?thanks

Powershell and Excel and SQL Server

$
0
0
Is there a way to read an entire Excel sheet into a Powershell variable, including the values as well as the cell formatting (specifically, Interior.ColourIndex), as opposed to the RBAR-CBAC (Cell By Agonizing Cell - to extend Jeff's nomenclature), method?Thanks!P

Fail sql job if error is encountered in powershell script

$
0
0
I have a powershell script that has 2 steps. The script is called by a SQL agent job. If a step fails, it is sending back the error to the job but wasn't actually failing the job. I found if I use "throw", it will fail the job. However if the 1st step fails, then it exits the script. I need it to continue on but still show a job failure regardless if step 2 fails or not. Is that possible?

Forms and controls

$
0
0
I'm trying to generate a dynamic control from data in SQL Server.The number of rows is variable, as is the visibility of the individual radiobuttons.criteria1 radiobutton1 radiobutton2 radiobutton3 inputboxcriteria2 radiobutton1 radiobutton2 radiobutton3 inputbox....I've got this working -- except that since all the radiobuttons are on the same control, clicking radiobutton1 on criteria2 turns off any other radiobuttons, on all rows.So what I need to do now is, for each row, to put the controls into a ...container control? and then add each container to my form.I tried a UserControl and GroupBox, to no avail.Bonus marks: assuming I get my container control set up, how do I determine the selected radiobutton? Or do I set a property on the container when then radio button becomes checked?

Need a way to script out LinkedServers on a SQL 2005\2008 boxes but place the script in seperate files.

$
0
0
If I run this it scripts them out all into one file. Can this be adjusted to put them in to individual files or is there a better way to do this?Add-PSSnapin SqlServerCmdletSnapin100Add-PSSnapin SqlServerProviderSnapin100[system.Reflection.Assembly]::LoadWithPartialName(‘Microsoft.sqlserver.smo’) |out-nullCLSCD SQLSERVER:\SQL\OM37345\DEFAULT\LinkedServersGCI | %{$_.script()} | out-file "C:\LinkedServers.sql"

Powershell code encapsulation into exe with dynamic parameters

$
0
0
Might be anyone could help with solution. I need to encapsulate powershell logic into exe. At the moment I am calling *.ps1 file using an agent job with passing to it parameter. Works fine, no issues. Unfortunately I need to deploy the script on client site. Due to company ethics need to hide the code. Any suggestion would be appreciated. Oh, and of course, I know, Powershell was created for task automation and configuration management framework.

Copy file to folder with current date

$
0
0
HiI am trying to copy a multiple files the have the current date as the creation date using a wild card but can't seem to get the syntax correct. Any help would be appreciated.Copy-item "D:\Solomon\Solomon IV\EventLog\DD500*.log" (CreationTime -eq (Get-Date)) ("C:\Temp\Emaillogs")

Powershell using SMO is painfully slow

$
0
0
this is probably more of a rant than a request for a solution....I threw a ton of time adapting and enhancing the script found in another topic here:[b][url=http://www.sqlservercentral.com/Forums/Topic1240480-1351-1.aspx]Powershell script to script out jobs, databases, users, linked servers, logins, roles, alerts, etc from a list of servers [/url][/b]if you looked at it, each function creates it's own instance of a [i]$srv = "Microsoft.SqlServer.Management.Smo.Server" [/i]and does it's scripting work; i added some additional stuff that scripts out each database objects.tested it on a single box, get the script results i like, and modify the txt file to have a few more for a more robust test.just ten servers took hours with the original code; moving the SqlServer.Management.Smo.Server and other objects out of the functions,and passing them in speeded things up some, but [b]dayum[/b]; in this world of instant satisfaction, powershell is looking to me like one of those overnight batch processing things.I've found an SMO tweak like setting $Server.SetDefaultInitFields($true) so things load up front, instead of when they are referenced, but still, it's painfully slow; if i needed to scan or re-scan a list of 20 or more servers, it's going to take all day. I'd need to start adding logic to skip if exists instead of letting it always script, just to squeeze a bit of performance.

Powershell within SQL 2012 SP1 can not load any modules

$
0
0
I have been attempting to run a Powershell script from a SQL Server agent job on SQL2012. The script runs fine in SQL 2008R2 however, I receive the below error when attempting to import any module in SQL2012. I am able to import modules when running PS from Windows (on the SQL2012 Server) however, they can not be loaded when running PS from Management Studio or from the SQL Agent. I can replicate this issue on several SQL2012 servers. PS SQLSERVER:\SQL\SERVERNAME\DEFAULT> import-module ActiveDirectory[size="1"]import-module : The 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\ActiveDirectory\ActiveDirectory.psd1' module cannot be imported because its manifest contains one or more members that are not valid. The valid manifest members are('ModuleToProcess', 'NestedModules', 'GUID', 'Author', 'CompanyName', 'Copyright', 'ModuleVersion', 'Description', 'PowerShellVersion', 'PowerShellHostName','PowerShellHostVersion', 'CLRVersion', 'DotNetFrameworkVersion', 'ProcessorArchitecture', 'RequiredModules', 'TypesToProcess', 'FormatsToProcess', 'ScriptsToProcess', 'PrivateData', 'RequiredAssemblies', 'ModuleList', 'FileList', 'FunctionsToExport', 'VariablesToExport', 'AliasesToExport', 'CmdletsToExport'). Remove the members that are not valid ('HelpInfoUri'), then try to import the module again.At line:1 char:14+ import-module <<<< ActiveDirectory + CategoryInfo : InvalidData: (C:\Windows\syst...eDirectory.psd1: String) [Import-Module], InvalidOperationException + FullyQualifiedErrorId : Modules_InvalidManifestMember,Microsoft.PowerShe ll.Commands.ImportModuleCommand[/size]I can view the modules as well:[size="1"]PS SQLSERVER:\SQL\SERVERNAME\DEFAULT> get-module -listAvailableModuleType Name ExportedCommands---------- ---- ----------------Manifest ActiveDirectoryManifest ADCSAdministrationManifest ADCSDeploymentManifest ADDSDeploymentManifest ADFSManifest ADRMSManifest ADRMSAdminManifest AppLockerManifest AppxManifest BestPracticesManifest BitsTransferManifest BranchCacheManifest CimCmdletsManifest DFSNManifest DirectAccessClientComponentsManifest DismManifest DnsClientManifest GroupPolicyManifest InternationalManifest iSCSIManifest IscsiTargetManifest ISEManifest KdsManifest Microsoft.PowerShell.DiagnosticsManifest Microsoft.PowerShell.HostManifest Microsoft.PowerShell.ManagementManifest Microsoft.PowerShell.SecurityManifest Microsoft.PowerShell.UtilityManifest Microsoft.WSMan.ManagementManifest MMAgentManifest MsDtcManifest NetAdapterManifest NetConnectionManifest NetLbfoManifest NetQosManifest NetSecurityManifest NetSwitchTeamManifest NetTCPIPManifest NetworkConnectivityStatusManifest NetworkTransitionManifest MSFT_NfsMappedIdentityManifest NFSManifest PKIManifest PrintManagementManifest PSDiagnosticsManifest PSScheduledJobManifest PSWorkflowManifest PSWorkflowUtilityManifest RemoteDesktopManifest ScheduledTasksManifest SecureBootManifest ServerCoreManifest ServerManagerManifest ServerManagerTasksManifest SmbShareManifest SmbWitnessManifest StorageManifest TroubleshootingPackManifest TrustedPlatformModuleManifest UserAccessLoggingManifest VpnClientManifest WdacManifest WebAdministrationManifest WheaManifest WindowsDeveloperLicenseManifest WindowsErrorReportingManifest SQLASCMDLETSManifest SQLPS[/size]Here is my version info:PS SQLSERVER:\SQL\ServerName\DEFAULT> $psversiontable[size="1"]Name Value---- -----CLRVersion 2.0.50727.6413BuildVersion 6.1.7600.16385PSVersion 2.0WSManStackVersion 2.0PSCompatibleVersions {1.0, 2.0}SerializationVersion 1.1.0.1PSRemotingProtocolVersion 2.1[/size]Any help would be greatly appreciated.

Powershell Multithreading with SQL Agent

$
0
0
Hello All,So I have 4 SQL Agent jobs that all run PowerShell scripts that utilize the multithreading abilities of PowerShell but I am running into issues. These 4 jobs are set to run every 5 minutes because they collect perfmon stats about our servers. Each job takes between 1-2:30 minutes to run to completion, each job is set to grab data for approximately 75 servers, and each PowerShell script is set to have a maximum of 6 threads running at a time. The issue I am encountering is SQL Agent will mark the job as failed if the PowerShell script reaches the end of the script but there are still active threads. I currently have it set up to check the total number of running threads and when that count reaches zero, it will finish the script. However, with all 4 of these jobs running, the script will count the total number of running threads from any of the scripts to calculate if the script is finished or not and this will get hung as the day goes on and the run times begin to overlap.Does anyone know of a good way to manage how many threads are running for a given SQL Agent job and only finish the script if the PowerShell threads for the current script have all finished executing?

Problem with Powershell and SQL Agent Job token

$
0
0
I'm working on a script that will transfer SQL Agent Jobs to another job server. One of the jobs uses the SQL Agent Token in a step:[code="sql"]WHERE job_id = $(ESCAPE_SQUOTE(JOBID)) [/code]Once the job is scripted out to a variable, I need to do -replace a string value with another string value to prepare the job script for the new environment. The values I want to replace are not even in this part of the script, but it causes Invoke-SQLCmd to fail because Powershell attempts to interpret the $() as an expression.Any suggestions?

SQL Server documentation using Powershell

$
0
0
Hi allI have been using SQL Power Doc to document my instances. [url]https://sqlpowerdoc.codeplex.com/wikipage?title=Guide%20For%20PowerShell%20Beginners[/url].I am in the process of running the conversion of the xml files to Excel.Is there a way to do a batch conversion of XML's? I need to be able to feed it all the XML's I've collected and then it needs to convert all of them into separate Excel documents for each server, is this possible? This is the code for the conversion:[code="plain"].\Convert-SqlServerInventoryClixmlToExcel.ps1 -FromPath "C:\Inventory\SQL Server Inventory.xml.gz"[/code]

Syntax error help please

$
0
0
Hello EveryoneI am running the below script which is meant to check the creation date of certain files and send an email if the file is missing or if the creation date is not current date. When I run it in an agent job I get this error and can't figure out the correct syntax. Any help would be appreciated.ERROR: 'A parameter cannot be found that matches parameter name 'eq'. '. Process Exit Code -1Code[code="plain"]Set-ExecutionPolicy RemoteSigned -ErrorAction SilentlyContinue$today = (get-date).Date$file1 = "CRAADDET" $file2 = "CRACRDTL"$file3 = "CRACRDDB" $file4 = "CRACON" $file5 = "CRACONDB"$file6 = "CRAAAD"$file7 = "CRAAPPDB"$files8 = "CRAAAD2"$files9 = "SCORECARDAPP"if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file1*.tab" -eq (get-date)) -eq $true) {Write-host $file1-ForegroundColor Green " File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file1 - Arrived Successfully" } else {Write-Host $file1 -ForegroundColor Yellow "Does Not Exist"} if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file2*.tab" -eq (get-date)) -eq $true) {Write-host $file2 -ForegroundColor Green "File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file2 - Arrived Successfully" } else {Write-host $file2 -ForegroundColor Yellow "Does Not Exist"} if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file3*.tab" -eq (get-date)) -eq $true) {Write-host $file3 -ForegroundColor Green "File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file3 - Arrived Successfully" } else {Write-host $file3 -ForegroundColor Yellow "Does Not Exist"} if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file4*.tab" -eq (get-date)) -eq $true) {Write-host $file4 -ForegroundColor Green "File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file4 - Arrived Successfully" } else {Write-host $file4 -ForegroundColor Yellow "Does Not Exist"} if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file5*.tab" -eq (get-date)) -eq $true) {Write-host $file5 -ForegroundColor Green "File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file5 - Arrived Successfully" } else {Write-host $file5 -ForegroundColor Yellow "Does Not Exist"}if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file6*.tab" -eq (get-date)) -eq $true) {Write-host $file1-ForegroundColor Green " File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file1 - Arrived Successfully" } else {Write-Host $file1 -ForegroundColor Yellow "Does Not Exist"}if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file7*.tab" -eq (get-date)) -eq $true) {Write-host $file1-ForegroundColor Green " File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file1 - Arrived Successfully" } else {Write-Host $file1 -ForegroundColor Yellow "Does Not Exist"}if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file8*.tab" -eq (get-date)) -eq $true) {Write-host $file1-ForegroundColor Green " File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file1 - Arrived Successfully" } else {Write-Host $file1 -ForegroundColor Yellow "Does Not Exist"}if((Test-Path -Path "\jfocus01\WFMASTERS\Created\$file9*.tab" -eq (get-date)) -eq $true) {Write-host $file1-ForegroundColor Green " File Exists"Send-MailMessage -From "NJFOCUS01@marlinleasing.com" -To "dbrown@marlinleasing.com" -SmtpServer "njmail03.marlincorp.com" -Body "Success" -Subject "$file1 - Arrived Successfully" } else {Write-Host $file1 -ForegroundColor Yellow "Does Not Exist"} [/code]

Getting My List of Databases as an array?

$
0
0
Fairly new to powershell, but not to programming.I've got the script below, that i [b]thought[/b] was going to create a array that i could lop through.when i write out the contents, i'm getting the # of elements as an initial value, like below:[quote][color="#0000FF"]VERBOSE: Database Name: 3VERBOSE: Database Name: CommonSecurityVERBOSE: Database Name: dbWardenVERBOSE: Database Name: ReportServerTempDB[/color][/quote]would someone be kind enough to offer an example or point out what i'm doing wrong?[code]#################################################################################################### All servers In SIMPLE Recovery, thus needing FULL/DIFF strategy.###################################################################################################function Get-DbListSimpleRecovery($svr) { $SqlQuery = "select [name] from master.sys.databases where recovery_model_desc = 'SIMPLE' and database_id > 4 order by [name]" $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $SqlQuery $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($DataSet) $SqlConnection.Close() $results = @() foreach ($Row in $DataSet.Tables[0].Rows) { $results += $Row.name; } return $results}#$WhichServer = "LOWELL-DEV"#if blank, uses the default intance of the lcoal server $dbs = Get-DbListSimpleRecovery($WhichServer) foreach($db in $dbs) { write-verbose -Message "Database Name: $db" -verbose }[/code]

Continue on error in foreach

$
0
0
I have PS that select all instance setup in CMS and then using that list does a foreach check for errors in the database mail log. IF all instance connect it runs great but if it cant connect to one instance it fails. I tried to add a try and catch but maybe didnt know where or who and also tried setting $ErrorActionPreference. Anyone out there able to help me out?[center]$instanceNameList = invoke-Sqlcmd -query "SELECT [server_name] as Name FROM [msdb].[dbo].[sysmanagement_shared_registered_servers_internal] SSRSIjoin [msdb].[dbo].[sysmanagement_shared_server_groups_internal] SSSGIon SSRSI.server_group_id = SSSGI.server_group_idwhere SSSGI.server_group_id = '15' or SSSGI.server_group_id = '14' or SSSGI.server_group_id = '13' or SSSGI.server_group_id = '12'" -serverinstance "consoleserver"$results = @() foreach($instanceName in $instanceNameList){$results += Invoke-Sqlcmd -Query "use msdbgoSELECT @@servername, items.subject, items.last_mod_date ,l.description FROM dbo.sysmail_faileditems as itemsINNER JOIN dbo.sysmail_event_log AS l ON items.mailitem_id = l.mailitem_idWHERE items.last_mod_date > DATEADD(hh, -1,getdate())" -ServerInstance $instanceName.Name}$results| Where-Object {$_} | Export-Csv c:\MailFailure.csv -NoTypeInformat[/center]

Filtering Get-ChildItem results with -LIKE?

$
0
0
i cannot for the life of me pinpoint my error here.this should be fairly simple: find matching files, and print em out before i explicitly delete them.i'm trying to test each file in a folder to match certain criteria to determine whether i want to delete it or not.eventually it will be four items total,including "older than x days, but i cannot even get the first item to filter and prove it was found.i'm trying to find something that matches a database name between underscores, and starts with "FULL_" and also the "right" extension.As far as i know, it's never even entering /testing my if statement.i thought maybe the underscores were part of the problem with a -LIKE statement, but even removing them doesn't get me to return anything inside the write-host commands.I've tried -like, startswith, and lots of other variations, but i'm obviously stuck on something super basic that my programming skillset assumes or takes for granted.can anyone see an obvious mistake here?[code="plain"]#folder contains the following files for example:#FULL_(local)_CommonSecurity_20140407_141304.sqb#FULL_(local)_dbWarden_20140407_141304.sqb#FULL_(local)_master_20140407_122503.sqb#FULL_(local)_model_20140407_122505.sqb#FULL_(local)_msdb_20140407_122505.sqb#FULL_(local)_ReportServerTempDB_20140407_141305.sqb#variable definitions$dbname="CommonSecurity";$Full_LOG_or_DIFF = "FULL";$extension = ".sqb";$limit = (Get-Date).AddDays(-7)$fl = Get-ChildItem -path "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup" ;foreach($item in $fl) { Write-Host $item.Name; if ( $item.Name -like ".sqb") { Write-Host $item.Name; Write-Host $item.FullName; } #if ( $item.Name -like "_${dbName}_" -and $item.Name.StartsWith("${Full_LOG_or_DIFF}_") -and $item.Name -like $extension -and $_.CreationTime -lt $limit) if ( $item.Name -like $extension ) { Remove-Item $item.FullName -WhatIf; } }[/code]

***-PSSnapin SQLServerCmdLetSnapin110 ....cannot add

$
0
0
HelloI have gotten part of this powershell script from the web, and first part configured by me.#Define Variables and configure variables#----------------------------------------#First Set the target database on server1$targetdb ="DevTest2010_Content80_Portal_ProjServSitCol"#Now set the source database from server2$sourcedb="Prod2010_Content80_Portal_ProjServSitCol"#Define the main source of backup folder$Mainsource = "\\server3\location1\"#concatenate Main Source and Source DAtabase name to get the full path to the file containing the backup you wish to use for restore.$FullSource=$MainSource+$sourcedbwrite-host $fullsource#find the name of the file$backupfilename = get-childitem $FullSource -Exclude *.trn | sort-object -descending lastwritetime |select Name -first 1write-host $backupfilename.name#Concatenate the $fullsrouce with the FileName to feed to the restore command$sourcefilename=$fullsource+"\"+$backupfilename.namewrite-host $sourcefilename[ScriptBlock] $global:RestoreDB = { param ([string] $targetdb, [string] $FullSource, [string] $sqlDataPath, [string] $dataLogicalName, [string] $logLogicalName) [string] $dbCommand = "RESTORE DATABASE [$targetdb] " + "FROM DISK = N'$FullSource' " + "WITH FILE = 1, " + "MOVE N'$dataLogicalName' " + "TO N'$sqlDataPath\$targetdb.mdf', " + "MOVE N'$logLogicalName' " + "TO N'$sqlDataPath\$targetdb.ldf', " + "NOUNLOAD, STATS = 10" $sqlSnapin = Get-PSSnapin | where {$_.Name -eq "SqlServerCmdletSnapin110"} if($sqlSnapin -eq $null) { Add-PSSnapin SqlServerCmdletSnapin110 } Invoke-Sqlcmd -Query $dbCommand}It does not let me run Add-PSSnapin SqlServerCmdletSnapin110. Error message I get is, "Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 2."I could not find anything on the web that would help me overcome this.

Dynamically creating / evaluating variables

$
0
0
I can't remember where I saw this, and can't find it now :-(I want the value of $cTime to be the current value of $Hourly8, namely, 10$Hourly8 = 10$Hour = 8$Var = $($('$Hourly'+$Hour))set-Variable -Name cTime -Value $("$var")$cTimeThanks!

Move Logins via SMO

$
0
0
It's possible to create in Powershell, a script that move the login from a source server to a destination server, including the password ?I tried to use the sp_help_revlogin procedure, but I'm unable to get the t-sql output into a variable.[code="sql"]$handler = [System.Data.SqlClient.SqlInfoMessageEventHandler] {param($sender, $event) $LoginDes | Write-Host $event.Message };$smoSrc.connectionContext.add_InfoMessage($handler);$smoSrc.connectionContext.executeNonQuery("EXEC master..sp_help_revlogin $dbLogin")[/code]If a try to use the script() method, the code generated has the password field, but is not the sid value.Tks
Viewing all 467 articles
Browse latest View live