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

Concat hard value to each row of Hash Table

$
0
0
I'm a newbie to Powershell and this one is driving me nuts. I have a document with many many rows of data and many columns for each row. I am sending this data via HTTPS post to a webserver and need to have each line prepended and appended with a "boundary". I can't seem to create a hash table with the first column of boundary, a second column blank (to be updated with Get-Content from the file), and a third column of boundary. And when I try a FOR loop to get the data prepended, the hard coded value ends up at the end of the file.I've done about 30 different iterations of code, getting errors and making changes along the way. The below code is the closest I've come to desired results:[code]$bound = '------=_12253dsfae4654'$Hash3 = @{};$Hash3 = (Get-Content .\SampleData.txt | Select -First 10 | Format-Table -Property FirstName,LastName,Location)$Hash3$Cnt2 = (Get-Content .\SampleData.txt | Measure-Object)$Counter = $Cnt2.Count$Test = $boundfor ($i=1;$i -le $Counter; $i++) { $Test = "$($Test) $($bound) $($Hash3[$i]) $($bound)" }$Test [/code]Screenshot of my results is loaded and for brevity's sake, I've created a sample data file with only 3 columns and 6 rows.Here's what I'm looking to achieve, but results do NOT have to be ordered like they are in the sample file. My only requirement is that each record have this boundary value prepended and appended to each row. [quote]------=_12253dsfae4654Mickey,Mouse,Florida------=_12253dsfae4654------=_12253dsfae4654Donald,Duck,Orlando------=_12253dsfae4654------=_12253dsfae4654Doctor,Who,Tardis------=_12253dsfae4654...etc[/quote]My Google-Fu gives me all sorts of basic help files on Hash Tables and Arrays, but nothing that helps me with concating a hard coded value to each individual line. I would appreciate any links, suggestions, etc. that you can think of.

Encoding data with Powershell

$
0
0
I'm pulling a text file into Powershell so I can send it via HTTPS. But as part of the send, the data needs to be encoded as Multipart/Form-Data (MIME) format. I'm unsure if that's automatically a part of the transmission process (somehow I doubt it) or if I need to something additional.Does anyone have experience with this sort of thing?

SQL Server Detach database

$
0
0
HiI am a SQL Server DBA and have never used Powershell before. I'm trying to detach a database using Powershell, but not getting very far.Have read up a bit and most ppl do it like below. I tried to run this, but getting an error that I'm not finding a solution for, so I'm pretty sure I'm doing something very wrong or possibly not doing something that I need to add to the script. Below is what I'm running and the error I'm getting.Please if anyone has any suggestions, please let me know.PS SQLSERVER:\> [void] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")PS SQLSERVER:\> $server = new-object Microsoft.SqlServer.Management.Smo.Server('SERVERNAME')PS SQLSERVER:\> $server.DetachDatabase("databasename")Cannot find an overload for "DetachDatabase" and the argument count: "1".At line:1 char:1+ $server.DetachDatabase("databasename")+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBestThanks!TDP

Add Network Places using PoSh

$
0
0
I'm getting a new Windows 7 desktop. From a powershell perspective, probably a good thing.But, I have a goodly number of Network Places mapped on my XP box, and I'd like to re-create those mappings on my new box.I've not seen anything that looks programmatic / PoSh in my search results.They seem to point to AddNetPlaceRunDll, but....Any ideas?

Programmatically create a New Network Location link Windows 7

$
0
0
Still trying to programmatically create a New Network Location link.I've got it down to -- [i]I think[/i]:$Newlink = New-Object System.IO.DirectoryInfo "$MyPath"But I can't figure out how to set the target, which is a \\Server\Drive$Any ideas?

Powershell Test-Path hanging

$
0
0
I am running a script that checks for mdf and ldf files on all of our SQL Servers and the script gets about halfway through before it hangs. It hangs at the line:[code="other"]Test-Path $fullPath[/code]Where $fullPath is the complete file path. Like I said, the script works perfectly fine and it tests half of the file paths in the list but after about half way, it will hang here.Could this be something to do with the file it gets hung on or the path? I have taken this snippet out of the script and executed it with the path that the script keeps getting hung on and it returned true within milliseconds.Please note that it hangs on the same file/same spot every time.

MSCluster gwmi access denied...locally on node..

$
0
0
Has anyone experienced this? I'm getting an access denied when trying to access Cluster WMI Objects...but only on a local node. I can access the objects just fine from other locations.

powershell WMI error: "Could not obtain SQL Server Service information. An attempt to connect to WMI ... failed with the following error: access is denied."

$
0
0
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?

Copy files using Powershell

$
0
0
Hey guys, I'm trying to figure out how to copy backup files from one shared location to another. I'm looking to be able to delete files at the destination, that no longer exist at the source, so what I'm looking for is for the destination to mirror the source location exactly. Thanks!

SQLPS takes 30 minutes to import. How to fix it?

$
0
0
Hey SSC,SQLPS on my workstation used to take around 30 seconds to import. Not exactly speed-of-thought, but acceptable.Now it takes around 30 minutes! This is unacceptable because it blocks my spontaneous PowerShell queries.What could have changed to make the module so unbearably slow to load?The ISE debugger has helped me to narrow down the cause, but not enough to say what the problem is or how to fix it.In a new instance of ISE I open a one-line script to import the module.[code="plain"]Import-Module SQLPS[/code]I set a breakpoint on the line and start debugging.I press 's' repeatedly at the prompt to step into every subsequent breakpoint until the module has loaded.The debugger seems to skip some lines. I'm not sure I'm getting the whole picture, but I carry on.Between this line in Sqlps.ps1:[code="plain"]Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000[/code]and this line in SqlPsPostScript.ps1:[code="plain"]Set-Location SQLSERVER:[/code]I have to wait a very long time.Just before the debugger returns control, it produces this output.[code="plain"]WARNING: The local computer does not have an active instance of Analysis Services.[/code]The warning about Analysis Services could be misleading. Analysis Services has never been installed on my workstation. The warning appeared when performance was still fast enough. How can I track down the true source of the problem and fix it?Thanks!

Managing Connection properties of Maintenance plans using Powershell

$
0
0
Hi All,We are managing the password reset activity from a central server for a login which is used on our servers for executing jobs and maintenance plan jobs.We are using the below powershell script for changing password which works quite well :$Items = Import-CSV $ENV:TEMP\PwdList.csv -Delimiter "|" ForEach ($Item in $Items){ $Instance = $Item.ServerName $Pwd = $Item.Pwd $Server = New-Object Microsoft.SqlServer.Management.Smo.Server($Instance) $Server.Logins.Item('adw').ChangePassword($Pwd) $Server.Logins.Item('adw').Alter()}Everything works fine, however, there are some maintenance plan jobs which uses this login. So I have to open the maintenance Plan -> go to manage connection -> local server connection and then change the password there as well. If I do not perform this activity, the maintenance plan fails.Can someone please let me know if there is a way to handle this as well using powershell so that everything is automated ?Thanks in advance.

Agent job with powershell

$
0
0
HiI am trying to create an agent job that looks for a file to exist and file if the file is not fount. I am using a try\catch block but the job will not fail. Any ideas?try { Get-Item -Path E:\Migration Files\myfile.txt -ErrorAction Stop} catch { # File Does Not Exist}

Set_Login Error in powershell script

$
0
0
Hi All,I was trying to automate my Password reset activity for Sql Logins from a central servr using Powershell.With the help of some useful tips from the below link, I was able to create a script : http://www.mssqltips.com/sqlservertip/1947/connect-to-sql-server-via-windows-powershell-with-sql-server-authentication/Initially I am just trying to read from the csv file and print the details to check if it works properly. Here is the script :[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null #imports the csv file with details $Items = Import-CSV D:\TEMP\test.csv -Delimiter "|" #Use the chosen delimiterForEach ($Item in $Items){ $Instance = $Item.ServerName $uname = $Item.uname $pwd = $Item.pwd $newpwd = $Item.newpwd$srv = new-object ('Microsoft.SqlServer.Management.Smo.Server') $Instance#This sets the sql authentication$srv.ConnectionContext.LoginSecure=$false; #This sets the login name $srv.ConnectionContext.set_Login($uname); #This sets the password $srv.ConnectionContext.set_Password($pwd) echo $Instanceecho $unameecho $pwdecho $newpwd}This script works fine and prints everything as desired. However, there is an error that pops up in the powershell window and I would like to handle this error before I proceed.The error is as below :[i]Exception calling "set_Login" with "1" argument(s): "Cannot apply value `null' to property Login: Value cannot be null."At line:11 char:33+ $srv.ConnectionContext.set_Login <<<< ($uname); + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : DotNetMethodException[/i]Can someone please let me know if there is anything wrong that I am doing here?Thanks a Lot !!!

Passing Parameter to SQl Agent Job that runs powershell

$
0
0
HiI have created a SQL Agent Job with a powershell step. The powershell script looks like the following:[code="other"]Param( [string]$A, [string]$B, [int]$C)#Do something with $A,$B and $C[/code]Now I have added it as a step and then created the job. What I am not able to figure out is how can I execute this job by passing parameters to the powershell script?

Powershell exit code

$
0
0
I have a script that I'm trying to run in TeamCity, essentially I want to force an exit code if an error happens.Here's the script:[code="other"]$s = "kbullen-865";$db_name = "tempdb";$ExceptionMessage = "";##Add-Type -Path "C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null$serv = New-Object Microsoft.SqlServer.Management.SMO.Server($s)Function CheckObject{ Param ( $DatabaseName, $ObjectSchema, $ObjectName) $scon = New-Object System.Data.SqlClient.SqlConnection #$scon.ConnectionString = "SERVER=" + $s + ";DATABASE=" + $DatabaseName + ";Integrated Security=true" $scon.ConnectionString = "SERVER=$s;DATABASE=$db_name;Integrated Security=true" $trycmd = New-Object System.Data.SqlClient.SqlCommand ## We refresh the object with the schema.table $trycmd.CommandText = "EXECUTE sys.sp_refreshsqlmodule '$ObjectSchema.$ObjectName'" $trycmd.Connection = $scon try { $scon.Open() $trycmd.ExecuteNonQuery() | Out-Null } catch [Exception] { $CurrentException = $_.Exception.Message -replace "'", "''"; $ExceptionMessage = $ExceptionMessage + $CurrentException; #Write-Host $DatabaseName"."$ObjectSchema"."$ObjectName ":" #Write-Host $_.Exception.Message Write-Host $CurrentException; } finally { $scon.Close() $scon.Dispose() }}$db = $serv.Databases[$db_name];foreach ($proc in $db.StoredProcedures | Where-Object {$_.IsSystemObject -eq $false}){ $o = $proc.Name $sc = $proc.Schema CheckObject $db.Name $sc $o }foreach ($trig in $db.Triggers | Where-Object {$_.IsSystemObject -eq $false}){ $o = $trig.Name $sc = $trig.Schema CheckObject $db.Name $sc $o}foreach ($udf in $db.UserDefinedFunctions | Where-Object {$_.IsSystemObject -eq $false}){ $o = $udf.Name $sc = $udf.Schema CheckObject $db.Name $sc $o}foreach ($view in $db.Views | Where-Object {$_.IsSystemObject -eq $false}){ $o = $view.Name $sc = $view.Schema CheckObject $db.Name $sc $o}if ($ExceptionMessage){ Write-Host $ExceptionMessage; exit 1;} [/code]The code appears to work, I get values written to the host by the line Write-Host $CurrentException. But at the end, the $ExceptionMessage appears empty.What am I doing wrong?

Cannot open file because the current provider (SqlServer) cannot open a file.

$
0
0
Server has SQL 2012Opened powershellsqlps got PS SQLSERVER:\> promptPS SQLSERVER:\> echo "xxxx" > tempps.txt[b]This works fine in normal powershell[/b]. In sqlps I get error:Cannot open file because the current provider (SqlServer) cannot open a file.Well, I must have left out a step. Can somebody tell me how to get sqlps permission to open a file?

Using a Helper Library from a powershell script that will be running via a SQl Agent job

$
0
0
Hi I am having a Powershell Script, [b]A.ps1[/b] that calls some functions from a Helper script [b]HelperFunctions.ps1[/b]. In order to execute A.ps1 from console I make sure I have the helper script imported. I use the following code.[code="plain"].".\HelperFunctions.ps1"[/code]But my actual requirement is that the script A.ps1 be executed from a SQL Agent job. I execute it as an Operating system step:[code="plain"]C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe -NoProfile -WindowStyle Hidden -Command C:\Users\querty\Desktop\Scripts\A.ps1[/code]When I run the script via SQL Agent job, then referencing the helper library as .".\HelperFunctions.ps1" throws an error and I need to use the full path of the helper function(even if the main script and the helper are in the same location). Now, my problem is this SQL Agent job will be running in multiple production servers. I do not know where the actual scripts will be placed and so I cannot hardcode and mention it inside the main script.I want a way to reference the helper script in the main script without mentioning the full path as this might change from server to server.One way of doing it is by passing it as a parameter but I want to keep it as a last option. Any other way I can reference the helper script directly from the main without caring about the actual path?Thanks and RegardsSaptarshi Chaudhuri

Unable to run the PS query.

$
0
0
How to check if I have a list of SQL Servers in a .TXT file and in the list, what are the SQL Servers are not accessible/stopped/not working?$MachineList = get-content "C:\PS\list_server.txt";$MachineList.Countforeach ($Machine in $MachineList){#Run ping test$MachineName = $Machine$result = Get-WMIObject -query “select StatusCode from Win32_PingStatus where Address = ‘$MachineName’” }The above query is throwing error....

How to find number of columns returned from query in powershell

$
0
0
I want to find out number of columns returned from a query in a powershell script.As we will be passing a dynamic query which can retrieve only 2 columns or 5 columns or n columns based on user's choice.$SQLQuery = " select * from sysdatabases "$QueryResults = Invoke-Sqlcmd -Query $SQLQuery -ServerInstance Win7 -SuppressProviderContextWarningforeach ($row in $QueryResults){ $row.Item(0)}Can you please help on how to find number of columns returned from above query.

email if no new files in last 2 days

$
0
0
I have this code that works great if there is a new file in the last 23 hours. how can I adjust it that if there is no new files in the last 2 days it will send me an emailParam ( [string]$Path = "d:shared\ftpimport\failed", [string]$SMTPServer = "mail.optonline.net", [string]$From = "SFTPAlert@yahoo.com", [string]$To = "morris@yahoo.com", [string]$Subject = "New File Failed to upload" )$SMTPMessage = @{ To = $To From = $From Subject = "$Subject at $Path" Smtpserver = $SMTPServer}$File = Get-ChildItem $Path | Where { $_.LastWriteTime -ge [datetime]::Now.Addhours(-23) }If ($File){ $SMTPBody = "`nThe following files have recently been added/changed:`n`n" $File | ForEach { $SMTPBody += "$($_.FullName)`n" } Send-MailMessage @SMTPMessage -Body $SMTPBody
Viewing all 467 articles
Browse latest View live


Latest Images