Hi,I have a script I am writing to make life easier for myself around requests for new Database environments by our developers. (Dev/Test/Live).All was going well until I stumbled on a little "issue-et". I can create my db and users on one SQL instance Fine. When I created a loop to do this for each instance the second time around the loop I get the following error. from this line *** $SQLuser.Create("123456789Ac") ** [code="other"]Exception calling "Create" with "1" argument(s): "Create failed for Login 'XXzzx2314gsrdf_user'. "At S:\Al\Scripts\PS script\New Database\CreateNewDatabase.ps1:108 char:16+ $SQLuser.Create <<<< ("123456789Ac") + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException[/code]An extract of my code below$DevServer = "MSSQL\DEV"$TestServer = "MSSQL\TEST"$LiveServer = "MSSQL\LIVE"$AllServers = $DevServer,$TestServer,$LiveServer .....get db name and user details here....[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Nullforeach ($server in $AllServers){$sqlSrv = New-Object Microsoft.SqlServer.Management.Smo.Server ($server)$SQLLoginname = $DatabaseName + "_user"$SQLuser = new-object Microsoft.SqlServer.Management.Smo.Login -ArgumentList ($sqlSrv,$SQLLoginname)$SQLuser.Name = $SQLLoginname$SQLuser.LoginType = "SQLLogin"$SQLuser.PasswordExpirationEnabled = $false$SQLuser.DefaultDatabase = $DatabaseName$SQLuser.PasswordPolicyEnforced = $false$SQLuser.Create("123456789Ac")# Windows Group$SQLLoginname = "MyDomain\$ADSQLGroup"$WGuser = new-object Microsoft.SqlServer.Management.Smo.Login -ArgumentList ($sqlSrv,$SQLLoginname)$WGuser.Name = $SQLLoginname$WGuser.LoginType = "WindowsGroup"$WGuser.DefaultDatabase = $DatabaseName$WGuser.Create()Remove-Variable -name sqlSrvRemove-Variable -name SQLuserRemove-Variable -name WGuser }Any help I can get on why I get the error would be great. (No alternative suggestions please) :-D
↧
Administration and Powershell
↧
Get-WMIObject Win32_Volume fails on proxy account from Agent Job
It may just be a case of me missing something, but I get unexpected behaviour when running a job as a proxy from the SQL Agent. The job itself is a simple one in Powershell that grabs partition usage (and other telemetry, such as BlockSize etc.)The line it has a problem with is:$Volumes=get-WMIObject WIN32_Volume |where-object {$_.FreeSpace -ne $null};The initial test was run on the given test server using the credentials of the proxy account (in a terminal server window, interactive with the desktop). The result was a clean run, all the necessary info displayed.I then put this as a Powershell Job Step, using that same proxy account. The result was an "Access Denied" message on attempting to query the WMI Object.Running the same task as the SQL Agent account (which also has non-sysadmin privileges, but more privileges on the database engine than I'd like) results in this working correctly.Setting the Proxy account as to a local administrator makes the job work correctly under the proxy account. As you can imagine, this is a no-go.Playing around with various other local group memberships makes no difference. There are articles about using PowerShell v2 to get the protected connections for WMI, but utilising that route results in the error that this is a local connection, so the settings for a remote query aren't applicable (yes, I ran this as a command via the CMD process, invoking powershell to execute a file as well).CMD usage with V2 gives the same results as using this via the sqlps embedded mini shell, even with COM execution, and explicit permissions on the WMI stack.So, currently my options seem to be to give the proxy a local system admin for the windows server, or allow it to run as the SQL Agent service account, neither of which are very secure solutions.. I strongly suspect I'm missing something; anyone able to enlighten me?Cheers,Rich
↧
↧
Powershell for network path
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
↧
How to copy last line of .txt file into new .txt file?
Windows Server 2008 R2I'm totally new to PowerShell but was trying to use it to solve an issue with data files that come with the last row being a) short and b) containing the row count for the file. For example, a file with 77,571 rows with 34 columns per row ends with a row (row 77,572) that contains just the text 'Total Exported:77571' plus row end chars.I can get PowerShell to give me the content of the last row using: Get-Content filepath.txt | Select-Object -last 1However, I haven't figured out how to write that to a new file... Oh, and I'd like to remove that row from the file when I'm done. I can use a script that will parse all files in a directory. Anyone have time to help with this? Many Thanks!
↧
French characters into SQL Server
Hi all,I use Powershell to deploy DB scripts. In one script file, I have French accented characters.When I call Invoke-sqlcmd and pass the script to the -inputfile, the French characters get mangled.In the bad old days, the workaround was to save the files as unicode, and sqlcmd would handle them OK.How do I go about this in this brave new world?Thanks!Paul
↧
↧
Power shell
Hi guys, I am new to powershell, can anyone please help me in undertanding powershell. I googled about powershell. But i dint get any clear idea about it. I would like to know about, for what purpose we are using powershell. And i need to use powershell for deployment. Please help me on this.
↧
Get table's unique indexes
Is there a way to list the unique table constraints on a given table using smo/powershell?Or do I have to query the system views?Thanks!
↧
get-unique
I [strike]want[/strike] need to understand why the code below returnsalpha ----- Y Can someone explain why I don't see alpha-----XYBonus points: if the last 2 lines are$cAlphas = $Objects | select alpha | Get-Unique$cAlphas why do I get alpha-----XThanks![code="VB"]$Objects = @()$Object = New-Object system.object$Object | Add-Member -Type NoteProperty -Name alpha -value "X"$Object | Add-Member -Type NoteProperty -Name Num -value "1"$Objects += $Object$Object = New-Object system.object$Object | Add-Member -Type NoteProperty -Name alpha -value "X"$Object | Add-Member -Type NoteProperty -Name Num -value "2"$Objects += $Object$Object = New-Object system.object$Object | Add-Member -Type NoteProperty -Name alpha -value "Y"$Object | Add-Member -Type NoteProperty -Name Num -value "1"$Objects += $Object$Object = New-Object system.object$Object | Add-Member -Type NoteProperty -Name alpha -value "Y"$Object | Add-Member -Type NoteProperty -Name Num -value "2"$Objects += $Object$cAlphas = $Objects | select alpha $cAlphas | Sort-Object -Unique[/code]
↧
Remove items from an array based on another array
Hi,I have 2 Array or ArrayList objects, with data like[code="vb"]$Results = New-Object system.Collections.ArrayList$Results.Add("IMP_Trn_Project_Agent_6,User1")$Results.Add("IMP_Trn_Project_Agent_6,User2")$Results.Add("IMP_Trn_Project_Agent_6,User3")$Remove = New-Object system.Collections.ArrayList$Remove.Add("User2")[/code]How can I efficiently remove from the first array all items containing the users in the 2nd array?Paul
↧
↧
Scrip to connect to remote windows box to get SQL version
Dear All,I am very much new to power shell scripting where i need to find out what version of SQL Server is running on it and on which port the DB is running on the remote windows box.Could you pls help us to script this out in powershell.Regards,Gangadhara
↧
powershell WMI error: "Could not obtain SQL Server Service information. An attempt to connect to WMI ... failed with the following error: access is denied."
I get the following error when I launch powershell from SSMS, after right-clicking on a remote SQL instance and choosing "Start powershell":[quote]Warning: Could not obtain SQL Server Service information. An attempt to connect to WMI on server1 failed with the following error: access is denied.[/quote]How can I fix this?
↧
Script to loop through SQL Server Instances and pass Instance Name to Connection String
I am trying to use a SQL Table to loop through SQL Instances and pass the Instance to a script:$DestinationSQLServer = 'coaidera01\idera'$DestinationDBName = 'CTM_Monitoring'$DestinationQry = "select InstanceName from COA_SQLServerInstanceInfo WHERE InstanceName Like 'coaidera01\idera'"$SQLSvr = get-SqlData -sqlserver $DestinationSQLServer -dbname $DestinationDBName -qry $DestinationQry$SQLSvr | foreach { $myserver = $_$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $myserver;------------------------------------------------------------------------------I get this error: The following exception was thrown when trying to enumerate the collection: "Failed to connect to server System.Data.DataRow.".Any Clues
↧
Help with replace parameter
Hi. I have a script that looks at the sysjobsteps table to find SSIS script locations and then copies them out to disk for disaster recovery. It works fine but I am making an assumption in the script that all scripts will be found on drive C. This is currently true but it could change without notice. My current script lines are like this:$Server = 'server1'$job ='FILE "C:\Projects\Scripting Restart.dtsx" /CHECKPOINTING OFF /REPORTING E'$URL = $job -replace 'FILE "C:',"\\$Server\C`$" -replace 'dtsx"','dtsx'$URLThe only method I can think of is to use a subscript like this. I haven't made it work yet but I'm sure it's possible.$Drive = $job.Substring(6,1)$DriveIt's getting pretty convoluted. Does anybody have a better way to handle this? I should be able to pass a masking character but I can't figure out how. Thanks in advance for any ideas you can offer.Judy S.
↧
↧
Query to variable - not wanting table style result
HiI am trying to run a script that queries the last full backup file for a specific database. Invoke line formated for ease of reading.[code="plain"]# Script is ran on the SQL server (not remotely)# Instance is called sql-instance# database is called sql-dataimport-module SQLPS -disableNameChecking$instanceName = "$($env:computername)\sql-instance"$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName$lastBackupFile = Invoke-Sqlcmd -Query " SELECT TOP 1 msdb.dbo.backupmediafamily.physical_device_name FROM msdb.dbo.backupmediafamily INNER JOIN msdb.dbo.backupset ON msdb.dbo.backupmediafamily.media_set_id = msdb.dbo.backupset.media_set_id WHERE msdb..backupset.type = 'D' and msdb.dbo.backupset.database_name = 'sql-data' ORDER BY msdb.dbo.backupset.backup_finish_date desc"[/code]The result I get with this is in a table format:[code="plain"]physical_device_name--------------------C:\Program Files\Microsoft SQL Server\MSSQL11.SIMS2012\MSQL\Backup\full_sql-data_20121101.bak[/code]Is there any way to just get the result and not the heading stuff?I need just the path and filename for using elsewhere in the script.I tried searching around but only found articles that give the table format and I don't know enouth to trim this down with confidence.Thanks in advance
↧
Inserting into table with Powershell
I have a script that I'm adapting from something I found on the internet where I'm getting database size information and insert that into a table I've created. I've been working with PS for a couple of months, but I'm still a bit green. Below is the section of relevant code - I looked at this Don Jones article [url=http://technet.microsoft.com/en-us/magazine/hh289310.aspx]here[/url] to get an idea how to do this. I'm not sure what the -f is for and he doesn't address it in the article. In any case, the variables have the right data in them at this point in the script (verified with the debugger) but the INSERT command is not working. That is, no data is in the table after the script is completed. No error is thrown, so I'm wanting to use Try...Catch to find out what the problem is. Does anyone have a recommendation as to what to put in the catch in this case? The info I've found on the internet is pretty generic and I don't know what kind of exception to interrogate for a SQL Server command.[code]$cmd.commandtext = "INSERT INTO dbo.db_sizes (Server, DatabaseName, DataFileName, DataSize, DataUsedSpace) VALUES('{0}','{1}','{2}','{3}', '{4})" -f$dbname, $mdfInfo.Name, $mdfInfo.FileName, ($mdfInfo.size / 1000), ($mdfInfo.UsedSpace / 1000)Try { $cmd.executenonquery() }catch { }[/code]
↧
Powershell execution error
Greetings,I have a script that was executing a powershell script from within a batch file with the following syntax:"“powershell.exe -NoLogo -Noninteractive -Command "& \"%~dp0ScriptName.ps1\" %1; exit "Everything was working fine until the OS team patched the server and upgraded Powershell to version 3 (it had version 2). After Powershell was upgraded the script failed with the error:"powershell.exe' is not recognized as an internal or external command, operable program or batch file"For the time being I have "fixed" the issue by executing powershell with an explicit path:"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -NoLogo -Noninteractive -Command "& \"%~dp0ScriptName.ps1\" %1; exit"Now, this change may make my script functional again, but I don't understand what exactly is going on. What changed when Powershell was upgraded that made the way I was calling the script invalid? Any information or good links to information would be greatly appreciated.Thanks!Kim
↧
Query local SSMS server group with Powershell?
This may be a totally off the wall question, but it seems like it should be possible to do. Just can't find any specifics as to how I might accomplish it.I have a situation in that I have the same database (structurally) across multiple SQL Server instances, with different database names. Through SSMS I have a local server group defined that references each unique instance and individual database. This allows me query each database at once with a single SQL statement, regardless of database name.When queries are run through my SSMS environment, I have the option enabled to return the SQL Server instance in the grid output so the instance name is returned with each row. I would like to automate running my query and outputting the results to Excel via Powershell script.What I'm hung up on is that I need to be able (with Powershell) to reference my SSMS local server group as the the data source that the query runs against, and run the query. Has anyone done this? I appreciate any feedback..
↧
↧
Failed SQL job info from PS to sql table
Hi All,Please have a look at the below link and help me to get the details (as 4 Columns) into a SQL Server table instead of Mail as I can make a SSR report from the data. SERVER = JOB = LASTRUN = LASTRUNDATE = http://www.sqlservercentral.com/blogs/sqlsandwiches/2012/01/29/find-failed-sql-jobs-with-powershell/RegardsSrikanth Reddy Kundur
↧
Get SQL Query Results as E-Mail
Gurus, I am trying to write a code to send out list of failed jobs in the last 24 hours. I am using out-string to convert my table to string. I am able to get email with list of jobs. But, i would like to see the e-mail in a table format rather than a string format. Here is code. Please help me out for converting my code to send email in HTML format. Thank you in advance. [code="plain"]#Set-ExecutionPolicy RemoteSigned############################################################################ Declare ServerName, DatabaseName and TableName to Get Server List###########################################################################$SourceServerName = 'local'$SourceDatabaseName = 'dbadb'#$SourceTablename = 'LookUp_ServerList_NonProd'############################################################################ Declare Variables for Sending E-mails###########################################################################$ToRecipient = "********@email.com"$From = "*********@email.com"$SMTPServer = "smtp.email.com"$GetDate = get-date -format g############################################################################ Create SqlConnection object and define connection string###########################################################################$SQLCon = New-Object System.Data.SqlClient.SqlConnection$SQLCon.ConnectionString = "Server=$SourceServerName; Database=$SourceDatabaseName; Integrated Security=true"############################################################################ Create SqlCommand object, define command text, and set the connection###########################################################################$SQLCmd = New-Object System.Data.SqlClient.SqlCommand$SQLCmd.CommandText = "SELECT SQLServerInstanceNameFROM [dbo].[LookUp_SQLServerInstanceList_NonProd] AS LUSSILNPINNER JOIN [dbo].[LookUp_ServerList_NonProd] AS LUSLNPON [LUSSILNP].[ServerID] = [LUSLNP].[ServerID]WHERE [SqlPingFlag] = 1"$SQLCmd.Connection = $SQLCon############################################################################ Create SqlDataAdapter object and set the command###########################################################################$SqlDataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter$SqlDataAdapter.SelectCommand = $SQLCmd############################################################################ Create and fill the DataSet object###########################################################################$DataSet = New-Object System.Data.DataSet$SqlDataAdapter.Fill($DataSet, "SQLServerInstanceName") | Out-Null############################################################################ Close the connection###########################################################################$SQLCon.close()############################################################################ Function for sending E-mails to ********@email.com###########################################################################Function SendEmail{ #param($strTo, $strFrom, $strSubject, $strBody, $smtpServer) param($To, $From, $Subject, $Body, $smtpServer) $msg = new-object Net.Mail.MailMessage $smtp = new-object Net.Mail.SmtpClient($smtpServer) $msg.From = $From $msg.To.Add($To) $msg.Subject = $Subject $msg.IsBodyHtml = 1 $msg.Body = $Body $smtp.Send($msg)}############################################################################ Declare Database and query###########################################################################$SQLDatabaseName = "msdb"$SQLQueryText = "SELECT [S2].[name], [dbo].[agent_datetime]([run_date] , [run_time]) AS RunDateFROM dbo.[sysjobhistory] AS SINNER JOIN dbo.[sysjobs] AS S2ON [S].[job_id] = [S2].[job_id]WHERE [dbo].[agent_datetime]([run_date] , [run_time]) >= GETDATE() - 1 AND ([run_status] IN ( 0 , 3 ) AND [S].[step_id] = 0)"################################################################################################### Iterate through the dataset to Run the query on Remote Server and send Results as E-Mails##################################################################################################foreach ($row in $DataSet.tables["SQLServerInstanceName"].rows){ $DestinationServerName = $row.SQLServerInstanceName #RunSQLQuery -SQLServerName $DestinationserverName -SQLDatabaseName $SQLDBName -SQLQuery $SQLQueryText $SQLConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server = $DestinationServerName; Database = $SQLDatabaseName; Integrated Security=true" $SqlCommand = New-Object System.Data.SqlClient.SqlCommand $SqlCommand.CommandText = $SQLQueryText $SqlCommand.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCommand $SQLDataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($SQLDataSet) | Out-Null $SqlConnection.Close() $Results = $SQLDataSet.Tables | Format-Table -Auto Name, RunDate | out-string $CountRows = $SQLDataSet.Tables[0].Rows.Count #$Text = @"Following Jobs have Failed:"@ $BodyText = ("$Results") IF($CountRows -ne 0 ) { $DestinationServerName $Subject = "$DestinationServerName - SQL Job Failed - $GetDate" #$Body = $TableResults SendEmail -To $ToRecipient -From $From -Subject $Subject -Body $BodyText -BodyASHTML -Auto Name -smtpServer $SMTPServer }}[/code]
↧
Help me Error SSIS Error (Agent Service)
An invalid reporting option was specified. Only E, W, I, C, D, P, V, and N are allowedImport Data Source from Oracle to SQL Server2008 password Oracle have '[' how solutionthanks
↧