Quantcast
Channel: PowerShell General
Viewing all 10624 articles
Browse latest View live

Examples running SQL Stored Procedures from Powershell with Output Parameters

$
0
0

Does anyone have a good example of calling a SQL Server stored procedure from powershell with output parameters that returns a string with more than one character?  I have a stored procedure with an output parameter that returns a char(3) value and I am only getting one character returned.

 Here is my code.  @CanGrow should return a value of "Yes" or "No" but all I get is Y or N.  @Reason should return a string of about 30 characters but I only get the first letter.

 

       $connString="Server=$CentralmanagementServer;Database=$CMSdb_name;Trusted_Connection=True"

       $connection=new-objectSystem.Data.SqlClient.SqlConnection$connString

       $connection.Open()

 

       $Command=new-ObjectSystem.Data.SqlClient.SqlCommand("abc_can_datafile_be_grown", $connection)

       $Command.CommandType = [System.Data.CommandType]'StoredProcedure'

        

       $Command.Parameters.Add("@Serverid", [System.Data.SqlDbType]"int")

       $Command.Parameters["@Serverid"].Value = [int]$DB.Serverid

      

       $Command.Parameters.Add("@Databaseid", [System.Data.SqlDbType]"int")

       $Command.Parameters["@Databaseid"].Value = [int]$DB.DatabaseId

      

       $Command.Parameters.Add("@DatabaseName", $DB.DatabaseName)

       $Command.Parameters.Add("@MonitorType", "GROWDATAFILE")

 

       $Command.Parameters.Add("@CanGrow","")

       $Command.Parameters["@CanGrow"].Direction = [system.Data.ParameterDirection]::Output

      

       $Command.Parameters["@CanGrow"].DbType = [System.Data.DbType]'String';

       $Command.Parameters.Add("@Reason","") | out-null

       $Command.Parameters["@Reason"].Direction = [system.Data.ParameterDirection]::Output

        

       $Command.ExecuteNonQuery() | Out-Null

       $NotWhitelisted=$Command.Parameters["@CanGrow"].value

       $WhitelistedReason=$Command.Parameters["@Reason"].value

       $connection.Close() | Out-Null

       $Command.Dispose() | Out-Null

       $connection.Dispose() | Out-Null

 

 


Function that updates the database - Guid Problem

$
0
0

I have a function that updates the database with a project name.  The PK column is a GUID. 
When I pass in the project name and an empty GUID I get a error that reads:  
   "Conversion failed when converting from a character string to uniqueidentifier
Even when I pass in a GUID I get an error:
  "Object reference not set to an instance of an object"
 
 function Update_DB {
param(
 $GUID,
 [string]$ProjectName
)
 if (($GUID -eq $null) -or ($GUID -eq "") ) {
  # Assign new GUID
  $GUID = $([guid]::NewGuid()).ToString();

  ## SQL Insert query##


  $sqlConnectionString = "Data Source=" + $Server + ";Initial Catalog=DB;Integrated Security=SSPI";
 $Conn = New-Object System.Data.SqlClient.SqlConnection $sqlConnectionString;
 if ($Conn -eq $null)
 { Write-Error "Database Connection to DB cannot be made";}
 $Conn.Open(); # Open SQL Connection
 $SqlCmd = $Conn.CreateCommand(); # Set up SQLCommand object
 $SqlCmd.CommandText = $Query;
 $SqlCmd.CommandTimeout = 0;
 try {
  $SqlCmd.ExecuteNonQuery();
 } Catch {
  $ErrMsg = "Error: SQL Error SQL execution<br />" + $_.Exception.Message;
  Write-Error $ErrMsg
 }
 $Conn.Close();

Why can I pass in a null or empty GUID and how do I make the GUID a uniqueidentifier to insert into the database?
Any help would be great.

determine with powershell the cause for service stop

$
0
0

Hi all,

i want to determine when a service was stopped manually and when a service was broken caused by systemcrash.

I tried it with Get-Process but i have no luck.

Passing parameter from command line to powershell or vbscript

$
0
0

Sounds like an easy one to answer and that I simply didn't look for the answer.  Unfortunately the issue is a bit more complex.  Using Talend to query/output to file.  Unfortunately, having an issue with Talend which requires using a command line module and calling a powershell script. Works great when it's hard-coded to one fileName.  However, want a dynamic powershell script to pick up the parameter fileName from tRunJob call in Talend console.  

Anyone familiar with using Talend w/ powershell?  Anyone in general familiar with picking up a variable in powershell from a different program? 

Concatenating a variable into an argument

$
0
0

So a while back i was working on making a remote msi installer and got that to work, so i decided to one up myself and make it automated so it'll find any new msi's and install them to remote computers. Then I discovered that powershell doesn't like to have variables put into the arguments like such:

Invoke-Command -ComputerName $Computer -Authentication CredSSP -Credential $Credential -ScriptBlock { Start-Process -FilePath "msiexec.exe" -ArgumentList "/i C:\Windows\Temp\MsiFile.msi /qb MO_B_MOINSTALL=0 MO_B_QDBINSTALL=1 MO_B_SQLSVR_WINAUTH=$WinAuth MO_SQLSVR_USER=$SQLUser MO_SQLSVR_PWD=$SQLPass MO_SQLSVR_NAME=$ServerInstance MO_QDBNAME=$Database /l c:\ProgramData\pslog.log" -wait }

I tried to do some concatenation for the variables, but i seem to have some trouble getting that to work. Any suggestions?

SSAS Cube Annotations

$
0
0

Hi,   as you know that each SSAS database Cube has Annotations objects that contains things like, comments, list of SQL table names for mapping and lots of other objects, best way to see them is to.

goto SSMS-> open SSAS serv -> Select a SSAS DB -> right click -> select Script database as-> creat to -> new Query editor window ->

The part that I need is the Table name and its ID

Table name is always in the ToolTip in the id is always in the value section a good example is like

Example 1 :  look for tooltip="vwDate" And value="dbo_RptDate"

Example 2 :  look for tooltip="vwSales" And value=" dbo_vwInnerSale "

 

<ddscontrolcontrolprogid="DdsShapes.DdsObjectManagedBridge.3"tooltip="vwDate"left="29994……………….snaptogrid="0">

            <control>

              <ddsxmlobjectstreaminitwrapperbinary="000800005410000088130000"/>

            </control>

            <layoutobject>

              <ddsxmlobj>

                <propertyname="LogicalObject"value="dbo_RptDate"vartype="8"/>

              </ddsxmlobj>

            </layoutobject>

            <shapegroupshapeid="0"groupnode="0"/>

          </ddscontrol>

<ddscontrolcontrolprogid="DdsShapes.DdsObjectManagedBridge.3"tooltip="vwSales"left="79525"……….snaptogrid="0">

            <control>

              <ddsxmlobjectstreaminitwrapperbinary="000800007e11000088130000"/>

            </control>

            <layoutobject>

              <ddsxmlobj>

                <propertyname="LogicalObject"value="dbo_vwInnerSale"vartype="8"/>

              </ddsxmlobj>

            </layoutobject>

            <shapegroupshapeid="0"groupnode="0"/>

          </ddscontrol>

This may take 5-10min, finally it will show you the XMLA file/format of the  SSAS cube database.

What I am looking for is I want to Loop trough each Cube and then loop through read each Annotation and find the list of table names (tooltip) and its ID (value), my question is I know how to connect to SSAS to get the cubes but I don’t know how to work with the Annotation object, don’t know how to loop it if I need to and I don’t know how to get the table name and its tableID.

What I have is …….

#------------------------------------------------------------------------------------------

#  CONNECT TO SSAS

#------------------------------------------------------------------------------------------

        #Com: ----- Open SSAS and extract data -----

        Import-Module SQLASCmdlets

       

        #Create a server object of type AS

        $SSASServer = New-Object Microsoft.AnalysisServices.Server

        #$CubeAnnotation = New-Object Microsoft.AnalysisServices.Annotation

        #$AnnotationCollection = New-Object Microsoft.AnalysisServices.Annotation

       

        #Create a SSASserver instance variable       

        $SSASinstanceName = $ASServer

        $SSASServer.connect($SSASinstanceName)

       

        # Connect to only one CubeDatabase

        $CubeDB = $SSASDB

       

        #$CubeDatabase = $SSASServer.Databases.Item($CubeDBName)

        # OR US CAN USE (Next Line)......

        $CubeDatabase = $SSASServer.Databases.GetByName($CubeDB)

       

        #############################################

        #### Cubes

        $Cubes = $CubeDatabase.Cubes | Sort-Object Name       

 

#------------------------------------------------------------------------------------------

 

foreach ($Cube in $Cubes ) #| SELECT ID , Name , Annotations| Sort-Object Name)

{

    Write-Output ''

    Write-Output "------- Start Cubes"

    Write-Output $Cube.Name

    Write-Output "-------      Start Annotations"

 

 

THIS PART I DON’T KNOW WHAT TO DO

THIS PART I DON’T KNOW WHAT TO DO

I need the

tooltip="vwDate" And value="dbo_RptDate"

tooltip="vwSales" And value=" dbo_vwInnerSale "

a loop some how

 

}

 

creating a function on Invoke-SqlCmd and having Troubles with UserName / Password

$
0
0

Hi all, 

so im building some functions in powershell where i need to choose between Windows or SQL authentication, so im trying to put that into my scripts but having a couple of issues..  My current code is :

 

FUNCTION Get-Test {

    [CmdletBinding()]

    Param 

        (

           # List of server(s) to run against

           [Parameter(Mandatory=$true)]

           [string[]]

           $Servers

           ,

           # Define SQL Version you want to find 

           [ValidateSet("SQL","Windows")]

           [string]

           $Authentication

           ,

           # Query to run against server

           [Parameter(Mandatory=$true)]

           [string[]]

           $Query

           ,

           # if SQL Auth then enter UserName

           [Parameter]

           [System.Management.Automation.ParameterAttribute]

           $UserName

           ,

           # If SQL auth then enter password

           [Parameter]

           [Security.SecureString]

           $Password

        )

 

PROCESS {

 

            foreach ($s in $servers)

                {

                    IF ($Authentication -eq "Windows")

                        {

                            $results =  invoke-sqlcmd -ServerInstance $s -Query $query

                        } 

                    ELSE

                        {

                            $results =  invoke-sqlcmd -ServerInstance $s -Query $query -Username $UserName -Password $Password

                        }

 

                  }

         }

}

 

 

So When i run this with 

 

Get-Test -Servers  $servers -Query $query -Authentication SQL -UserName MyUserName  -Password myPassworld

I have the following problems: 

1: I get an error trying to use SQL auth 

 

Cannot process argument transformation on parameter 'UserName'. Cannot convert the "MyuserName" value of type "System.String" to type "System.Management.Automation.ParameterAttribute".

At line:1 char:78

 

2: Id like to hide the password being seen. If seen you can hide text -asSecureString and thought i had the right thing with what i have below: [Security.SecureString] but its not working.

 

3: is it possible to make the username and password not show up in the parameters options unless you use authentication sql ? 

 

Thanks for any advice! 

 

Syntax trouble when pulling data from a query in sql

$
0
0

The top portion of my code is working beautifully. For some reason I am have trouble with the code i have bolded below.

What I am trying to do is select the field called path from the sql server, then change the directory to that path. Then I am selecting the executable file from the sql table in the field called "EXE" and running it.

Foreach-object {CD $_.Path ; start-process -filepath $_.EXE; $_}    <-This code works when I have it set to run locally. My query is working perfectly as well. Do i need to be naming the .Path and .EXE something like: {CD dbo.Auto_Master.Path ; start-process -filepath dbo.Auto_MasterEXE; $_}   as opposed to using the "$_" ?

Any help would be greatly appreciated, thanks!

Here is the entirety of my code:

import-module C:\WORK\xMATCH\Invoke-Sqlcmd2.ps1
$query = "SELECT dbo.Auto_Master.PATH, dbo.Auto_Master.EXE  FROM dbo.Auto_Master WHERE (((dbo.Auto_Master.Active)='Y'));"
invoke-sqlcmd2 -serverinstance "$env:computername\" -Database SQL_TRIG -Query $query | Foreach-object {CD $_.Path ; start-process -filepath $_.EXE; $_}


Automated install of SQL Server, Workflows or DSC???

$
0
0

Hey all, 

Trying to improve my installs of sql server by automating it all with powershell. 

i had a basic idea of

  • running a bunch of checks before install, setting up things (format drives, create folders, add service account to local security)
  • then running an install / slipstream (use a config file). 
  • then running the standard post install scripts to configure the instance (create maintenace plans, add standard extra accounts, monitoring etc). 

So far im coming up with a lot of issues for keeping this simple.. 

namely. things like

to add a domain account to a local security group i need to turn off UAC. (Which needs a reboot)

Ive got a check to see if a reboot is needed (Our server team like to patch and not reboot!) but again if i reboot im starting from scratch again and re-running the script..

 

Looking at it. Workflows and DSC seem to be the answer. I was originally thinking DSC but i need to do so many checks before the install part.. Im starting to think workflows is more whats needed?!.... 

 

I've never done any work with either and maybe im running to buzz words for solutions? .. does anyone have any experience using either of them for there install builds? maybe not specific to SQL install but something else 

Any suggestions or input would be greatly appreciated! 

 

Pass SQl Query parameter for Powershell Script

$
0
0

Hi,

I have following parameters being passed from SQL Stored procedure to Powershell.

----------PowerShell Start

 param

(

      [string] $server = "SQL2",

     [string] $database  = ("Utils"),

    [string] $query ="Select * from xPM_Extract",

    [string] $extractFile = "C:\temp\csv2  export.csv"

)

 

Write-Host $server

Write-Host $database

Write-Host $query

Write-Host $extractFile

----------PowerShell END

 

Problem is that parameters for $query & $extractFile are cutoff at first encounter of space. I call my SP as

Exec usp_MYPS_Export2CSV 'Utils','Select * From Customers','C:\temp\csv2 out.csv'

Translates to

EXEC xp_cmdshell 'PowerShell -Command"C:\Util\PSScripts\SQL_Export2CSV2.ps1 -Server SQL3 -database Test -query Select * From Customers -extractFile "C:\temp\csv2  out.csv"'

Output from Powersehll is Shown below after executing above statement from SSMS.

SQL3

Test

Select

C:\temp\csv2

------------output Ends here

 

I want to see output as below.

SQL3

Test

Select * from xPM_Extract

C:\temp\csv2  export.csv

----------------------

 Please notice that Query is trimmed at Select and Output file name is trimmed at csv2.

 How to pass parameters with space in them?

 

 

Thanks.

Auto export database/tables from Local Sql Server to Azure.

$
0
0

Hi,

I'm new to powershell and currently we use a c# app on the local to export data from local to our azure db. I now want to explore other options for auto exporting
and have pegged looking at powershell for a while, after some initail investigations I have to admit I was surprised how much there was too it but I haven't been succesful in
tracking down specific'ish info or scripts on my requirement.

So I'm looking for some advice/pointers/scripts - anything that might help basically :)

Some of our clients run sql server 2005 and some 2008 (express editions). If need be we can probably upgrade the 2005 although I've noted 2005 can run powershell with some install's applied.

So my requirement really is the auto export of preferably just some tables but maybe the whole database from a local sql server/db to an azure sql server/db using powershell.

thanks,

Executing a SQL query using Powershell

$
0
0

I hope this is the place to ask "super basic" newbie questions because I have one which may have to do with script placement of the following sql query:

"USE DATABASENAME

GO

 

IF OBJECT_ID('tempdb..#mytemp') IS NOT NULL DROP TABLE #mytemp

GO

 

DECLARE @row_id int;

DECLARE @tableHTML  NVARCHAR(MAX) ;

DECLARE @Subject NVARCHAR(MAX);

DECLARE @AppID int; 

DECLARE @EmailTo NVARCHAR(MAX);

DECLARE @PassFail NVARCHAR(20);

 

set rowcount 0

SELECT 

ROW_NUMBER() OVER(ORDER BY AL.AppID) AS Row, AL.AppID, AL.AppName, AL.AppOwner, AL.AppAlertEmail, TD.TestCaseName, TD.TestCaseDescription, TR.TestResult, 

TR.TestStartTime, TR.TestEndTime, TR.TestResultDescription, TR.TestEnvironment, TR.TestBroswer

 into #mytemp from TestResults TR INNER JOIN

TestDetails TD ON TR.TestID = TD.TestID INNER JOIN

AppList AL ON TD.AppID = AL.AppID

WHERE

(TR.BatchID = (SELECT max(batchid) as MaxBatchID

FROM TestBatch where BatchEndTime is not null))

ORDER BY AL.AppID

 

set rowcount 1

 

select @row_id = Row from #mytemp

 

while @@rowcount <> 0

begin

    set rowcount 0

    select * from #mytemp where Row = @row_id;

 

    SET @AppID = (select AppID from #mytemp where Row = @row_id);

 

    SET @EmailTo = (select AppAlertEmail from #mytemp where Row = @row_id);

    --SET @EmailTo = 'me@mydomain.com';

 

    SET @PassFail = (select top 1 UPPER(TestResult) as TestResult from #mytemp where AppID = @AppID order by TestResult);

 

    SET @Subject = '***' + @PassFail + '*** ' + (select AppName from #mytemp where Row = @row_id) + ' Test Results ***' + @PassFail + '***';

 

    SET @tableHTML = 

    N'<H1>Results</H1>' +

    N'<table border="1">' +

    N'<tr bgcolor="#BDD8DA"><th>Name</th><th>Description</th>' +

    N'<th>Result</th><th>Start Time</th><th>End Time</th>' +

    N'<th>Result Description</th><th>Environment</th><th>Browser</th></tr>' +

    CAST ( ( SELECT TestCaseName as [td], '',

                    TestCaseDescription as [td], '',

                    (case when TestResult = 'Pass' then

                    '#00CC00' else '#FF0000' end)  AS [td/@bgcolor],

                    TestResult as [td], '',

                    TestStartTime as [td], '',

                    TestEndTime as [td], '',

                    TestResultDescription as [td], '',  

                    TestEnvironment as [td], '',

                    TestBroswer as [td]

              from #mytemp where AppID = @AppID

              ORDER BY TestResult

              FOR XML PATH('tr'), TYPE 

    ) AS NVARCHAR(MAX) ) +

    N'</table>' ;

 

    EXEC msdb.dbo.sp_send_dbmail

    @profile_name = 'SQL Mail',

    @recipients = @EmailTo,

    @body = @tableHTML,

    @subject = @Subject,

    @body_format = 'HTML' ;

 

 

    delete #mytemp where AppID = @AppID

 

    set rowcount 1

    select @row_id = Row from #mytemp

end

set rowcount 0

 

GO"

This sql query runs against a database and generates an email notification on the status of a set of applications as being up or down. 

 

I finally have a structure built but can't figure out where to place the sql query. Here's what I have as a reference:

$ServerInstance = "SQLSERVERNAME\INSTANCENAME "

$Database = "SQLDATABASENAME "

$ConnectionTimeout = 30

$Query = "CAN I PASTE SQL QUERY HERE"

$QueryTimeout = 120

 

#Establish database connection and execute query

$conn=new-object System.Data.SqlClient.SQLConnection

$ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout

$conn.ConnectionString=$ConnectionString

$conn.Open()

$cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)

$cmd.CommandTimeout=$QueryTimeout

$ds=New-Object system.Data.DataSet

$da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)

[void]$da.fill($ds)

$conn.Close()

$ds.Tables

 

Attempting to run this in PowerGui generates "unexpected token" errors so I figure I must be doing something wrong and could use some direction. 

Any responses appreciated.

Which class to export data from SQL Table to flat file?

$
0
0

Need to read 85 SQL tables and export them to a delimited flat file with a header.  I cannot use bcp or invoke sqlcmd. Has to work with SQL 2005 - 2014. Will execute from a SQL Agent job.

I have seen some partial examples with smo, serverconnection, sqlconnection with adaptor. Any others that I am missing.

What are the pros and cons of the various classes? Which is the most portable? The solution will be sent out to several clients and I have no control over their os, .NET, PS version. (I can force probably force the .NET and PS, but would prefer not to do it too often)

PowerShell using SMO - how to look at the query results?

$
0
0

This code worked well with PS 4.0, and .net 4 something. But when I try to execute it on another machine the FOREACH gets an indexing error.

Guess my first question is (1) after executing the ExecuteWIthResults, how do you look at the individual row/column values returned?  (2) what problems will I run into moving a SMO solution between different .NET versions?

 

[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
$sqlsvr
='fidev360x\fidev360x'
$dir
='c:\temp\pssmo\'
$database = '
aaatest'
$diagnostics = 1
$sqlserver = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlsvr)
$db = $sqlserver.databases[$database]
$Tables = $db.ExecuteWithResults("Select * FROM ifs_exporttables")
foreach ($DataRow in $Table[0].Tables[0].Rows)
    {
    $TableName = $DataRow[2].tostring()    # ifs_ExportTables.TableName
    $Delimiter = $DataRow[4].tostring()    # ifs_ExportTables.Delimiter
    $Header = $DataRow[5].tostring()       # ifs_ExportTables.ColumnHeaders
    if ($diagnostics = 1)
        {write-host -ForegroundColor Green "Creating Table $TableName to path $dir$TableName.csv" }
    $sqlserverR = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlsvr)
    $dbR = $sqlserverR.databases[$database]
    $TablesR = $dbR.ExecuteWithResults("Select * FROM $TableName")
    $result = $TablesR[0].tables.item(0)
    if ($Header -eq '
1')
    {$result |export-csv -Delimiter $Delimiter –notype -path $dir$TableName.csv  -Encoding ASCII}
    else
    {$result | ConvertTo-Csv -NoTypeInformation -Delimiter $Delimiter | Select-Object -Skip 1 | Out-File -FilePath $dir$TableName.csv  -Encoding ASCII}
    }

 

 

Can't deploy .dacpac by following technet documentation

$
0
0

Hi, 

I'm trying to follow the msdn documentation to deploy a dacpac on SQL Server 2012 which is installed on my local machine. Here's the link to the documentation: http://technet.microsoft.com/en-us/library/ee210569(v=sql.110).aspx

The script I try to execute is:

 

param (

[string]$dacpacPath = $(throw "-dacpacPath is required."),

[string]$dacName = $(throw "-dacName is required."),

[string]$serverName = $(throw "-servereName is required.")

)

 

$ErrorActionPreference = "Stop"

 

Push-Location

Import-Module sqlps -DisableNameChecking

Pop-Location

 

$srv = Get-Item "SQLSERVER:\SQL\$serverName"

 

## Open a Common.ServerConnection to the same instance.

$serverconnection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection($srv.ConnectionContext.SqlConnectionObject)

$serverconnection.Connect()

$dacstore = New-Object Microsoft.SqlServer.Management.Dac.DacStore($serverconnection)

 

## Subscribe to the DAC events.

$dacstore.add_DacActionStarted({Write-Host `n`nStarting at $(get-date) :: $_.Description})

$dacstore.add_DacActionFinished({Write-Host Completed at $(get-date) :: $_.Description})

 

## Delete previous DAC if exists and drop the database

$dacstore.Uninstall($dacName, [Microsoft.SqlServer.Management.Dac.DacUninstallMode]::DropDatabase)

 

## Load the DAC package file.

$fileStream = [System.IO.File]::Open($dacpacPath,[System.IO.FileMode]::OpenOrCreate)

$dacType = [Microsoft.SqlServer.Management.Dac.DacType]::Load($fileStream)

 

## Deploy the DAC and create the database.

$evaluateTSPolicy = $true

$deployProperties = New-Object Microsoft.SqlServer.Management.Dac.DatabaseDeploymentProperties($serverconnection, $dacName)

$dacstore.Install($dacType, $deployProperties, $evaluateTSPolicy)

$fileStream.Close()

 

## END SCRIPT

 

When I try to run the script from powershell console I get the following exception:

New-Object : Cannot find type [Microsoft.SqlServer.Management.Dac.DacStore]: verify that the assembly containing this type is loaded.

At C:\src\commerce\private\CommerceSearch\relevance\MTurkJudgmentSystem\Publish\deploy-db.ps1:19 char:13

+ $dacstore = New-Object Microsoft.SqlServer.Management.Dac.DacStore($serverconnec ...

+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException

    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

As the documentation states, calling Import-Module sqlps -DisableNameChecking should load all the assemblies automatically, but for some reason this doesn't happen.

I've tried installing packages from here http://www.microsoft.com/en-us/download/details.aspx?id=39976 but it didn't help.

What am I missing from reading the docs?

Thanks.

 

 

 


Error while running the PS script at first time

$
0
0

Hello,

 

When i execute below script in PS command line, first time this script will not execute and gives error.

Then in same command line window if I run the same script second time it will execute.

Can you please tell what could i need to add for running first time it self?

 

****************************************************

Param(

[String]$CentralServer 

)

 

Function Get-RSSQLInstance {  

 

    [cmdletbinding()] 

    Param (

        [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]

        [Alias('__Server','DNSHostName','IPAddress')]

        [string[]]$ComputerName

 

    ) 

 

    Process {

        ForEach ($Computer in $Computername) {

            $Computer = $computer -replace '(.*?)\..+','$1'

            Write-Verbose ("Checking {0}" -f $Computer)

            Try { 

                $reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer) 

                $baseKeys = "SOFTWARE\\Microsoft\\Microsoft SQL Server",

                "SOFTWARE\\Wow6432Node\\Microsoft\\Microsoft SQL Server"

                If ($reg.OpenSubKey($basekeys[0])) {

                    $regPath = $basekeys[0]

                } ElseIf ($reg.OpenSubKey($basekeys[1])) {

                    $regPath = $basekeys[1]

                } Else {

$q= "No RS Component installed on " +$Computer

write-output $q >> $filenamecompliance

                    Continue

                }

                $regKey= $reg.OpenSubKey("$regPath")

                If ($regKey.GetSubKeyNames() -contains "Instance Names") {

                    $regKey= $reg.OpenSubKey("$regpath\\Instance Names\\RS" ) 

                    $instances = @($regkey.GetValueNames())

                } ElseIf ($regKey.GetValueNames() -contains 'InstalledInstances') {

                    $isCluster = $False

                    $instances = $regKey.GetValue('InstalledInstances')

                } Else {

                    Continue

                }

                If ($instances.count -gt 0) { 

                    ForEach ($instance in $instances) {

                        $nodes = New-Object System.Collections.Arraylist

                        $clusterName = $Null

                        $isCluster = $False

                        $instanceValue = $regKey.GetValue($instance)

                        $instanceReg = $reg.OpenSubKey("$regpath\\$instanceValue")

                        If ($instanceReg.GetSubKeyNames() -contains "Cluster") {

                            $isCluster = $True

                            $instanceRegCluster = $instanceReg.OpenSubKey('Cluster')

                            $clusterName = $instanceRegCluster.GetValue('ClusterName')

                            $clusterReg = $reg.OpenSubKey("Cluster\\Nodes")                            

                            $clusterReg.GetSubKeyNames() | ForEach {

                                $null = $nodes.Add($clusterReg.OpenSubKey($_).GetValue('NodeName'))

                            }

                        }

                        $instanceRegSetup = $instanceReg.OpenSubKey("Setup")

                        Try {

                            $edition = $instanceRegSetup.GetValue('Edition')

                        } Catch {

                            $edition = $Null

                        }

                        Try {

                            $ErrorActionPreference = 'Stop'

                            #Get from filename to determine version

                            $servicesReg = $reg.OpenSubKey("SYSTEM\\CurrentControlSet\\Services")

                            $serviceKey = $servicesReg.GetSubKeyNames() | Where {

                                $_ -match "$instance"

                            } | Select -First 1

                            $service = $servicesReg.OpenSubKey($serviceKey).GetValue('ImagePath')

                            $file = $service -replace '^.*(\w:\\.*\\sqlservr.exe).*','$1'

                            $version = (Get-Item ("\\$Computer\$($file -replace ":","$")")).VersionInfo.ProductVersion

                        } Catch {

                            #Use potentially less accurate version from registry

                            $Version = $instanceRegSetup.GetValue('Version')

                              } Finally {

                            $ErrorActionPreference = 'Continue'

                        }

                        New-Object PSObject -Property @{

 

                            InstalledInstances = {

                                If ($Instance -eq 'MSSQLSERVER') {

                                    "$($Computer)"

                                } Else {

                                    "$($Computer)\$($instance)"

                                }

                            }.InvokeReturnAsIs()

 

                        } | export-csv -NoTypeInformation -path .\rsinstancelist.csv -Append -Force

 

                         }

                }

            } Catch { 

                Write-Warning ("{0}: {1}" -f $Computer,$_.Exception.Message) 

                 }  

        }   

    }

}

 

#-------------------------------------------------------------------------------------------------

# FUNCTIONS: Get all the SSRS instance details by calling the function Get-RSSQLInstance 

#-------------------------------------------------------------------------------------------------

Function Get-instance{

 

Invoke-Sqlcmd -Query "SELECT Server_name FROM TOOLS.dbo.v_ReportingServices_instances" -ServerInstance $CentralServer | export-csv -NoTypeInformation -path ".\rsserverlist.csv" -Append -Force

 

$FileExists = Test-Path ".\rsserverlist.csv"

If ($FileExists -eq $True){

(Get-Content ".\rsserverlist.csv" | foreach {$_ -replace '"'} | Set-Content ".\rsserverlist.txt") 

Remove-Item ".\rsserverlist.csv"

$cnt=(get-content ".\rsserverlist.txt").Count

$cnt=($cnt-1)

gc ".\rsserverlist.txt" | select-object -last $cnt | set-content ".\rsserverlist.txt"

}

 

$serverarray = get-content ".\rsserverlist.txt"

 

foreach($s in $serverarray){

 

 

Get-RSSQLInstance $s

}

 

#-------------------------------------------------------------------------------------------------

# FUNCTIONS: Clean up RS insatnce lsit file and bulk insert into table

#-------------------------------------------------------------------------------------------------

Function Get-instances {

 

$FileExists = Test-Path ".\rsinstancelist.txt"

If ($FileExists -eq $True){

Remove-Item ".\rsinstancelist.txt" }

 

$FileExists = Test-Path ".\rsinstancelist.csv"

If ($FileExists -eq $True){

(Get-Content ".\rsinstancelist.csv" | foreach {$_ -replace '"'} | Set-Content ".\rsinstancelist.txt")

Remove-Item ".\rsinstancelist.csv"

$cntrs=(get-content ".\rsinstancelist.txt").Count

$cntrs=($cntrs-1)

gc ".\rsinstancelist.txt" | select-object -last $cntrs | set-content ".\rsinstancelist.txt"

 

}

 

}

Get-instance

Get-instances

 

Pass username fro MySQL query into variable with field name meta data

$
0
0

Hi All,

I am new Powershell and MySQL and having some trouble with passing a username, returned by a query to a MySQL server, into a variable without the meta data of the field name being copied also.

The query responds with the following:

Login ----- test1

 

I want "test1" only to pass into variable $test. However I cannot work out the correct way to do this.

I am importing a module that I have created to store the MySQL query so that I can simple call the connection and pass a query to it in a separate script, the module is call mysqlconnection.psm1 and contains the following:

Function Run-MySQLQuery {

    Param(
        [Parameter(
            Mandatory = $true,
            ParameterSetName = '',
            ValueFromPipeline = $true)]
            [string]$query,   
        [Parameter(
            Mandatory = $true,
            ParameterSetName = '',
            ValueFromPipeline = $true)]
            [string]$connectionString
        )
    Begin {
        Write-Verbose "Starting Begin Section"        
    }
    Process {
        Write-Verbose "Starting Process Section"
        try {
            # load MySQL driver and create connection
            Write-Verbose "Create Database Connection"
            # You could also could use a direct Link to the DLL File
            # $mySQLDataDLL = "C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.3\Assemblies\v4.5\MySQL.Data.dll"
            # [void][system.reflection.Assembly]::LoadFrom($mySQLDataDLL)
            [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
            $connection = New-Object MySql.Data.MySqlClient.MySqlConnection
            $connection.ConnectionString = $ConnectionString
            Write-Verbose "Open Database Connection"
            $connection.Open()
            # Run MySQL Querys
            Write-Verbose "Run MySQL Querys"
            $command = New-Object MySql.Data.MySqlClient.MySqlCommand($query, $connection)
            $dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($command)
            $dataSet = New-Object System.Data.DataSet
            $recordCount = $dataAdapter.Fill($dataSet, "data")
            $dataSet.Tables["data"] | Format-Table
        }        
        catch {
            Write-Host "Could not run MySQL Query" $Error[0]    
        }    
        Finally {
            Write-Verbose "Close Connection"
            $connection.Close()
        }
    }
    End {
        Write-Verbose "Starting End Section"
    }
}

export-modulemember Run-MySQLQuery

This module is called in another script with the following:

$username = "test1"

Import-Module ActiveDirectory
Import-Module C:\Windows\System32\WindowsPowerShell\v1.0\Modules\MySQL\mysqlconnection_test.psm1

$test = run-MySQLQuery -ConnectionString "Server=test;Uid=root;Pwd=Password123;database=test;" -Query "select login from usr_data where usr_id = 226"

 

As state previously $test now contains:

Login
-----
test1

I am sure I am missing something simply, but I am stumped so far.

 

Powershell and MySQL are not part of my standard expertise so any help with this would be greatly appreciated!

Ryan

SQL powershell to query and update the tables

$
0
0

I have this script and I want to update one of table or datafield but it didn't work.

#> 

 

function SQL-Update {

 

param (

 

      [string]$server=SQL2012,

 

      [string]$database=Test,

 

      [string]$table=Works,

 

      [string]$datafield=Id;Name,

 

      [string]$datavalue=charvar,

 

      [string]$updateID= 'DEV123'

 

 

 

)

 

 

 

$sqlquery = @"

 

Update $database.$table

 

SET $dataField='$dataValue'

 

WHERE id=$UpdateID

 

"@

 

 

 

 

 

try {

 

     invoke-SQLcmd -ServerInstance $Server -Database $database -

 

Query $sqlquery

 

     }

 

     catch {

 

     }

Strange "Named Pipes Provider, error: 40" when accessing a class in an assembly

$
0
0

I have a PS script that is executed from a TSQL Agent Job. It uses ADO to retrieve SQL data and call SQL stored procs. That part all works well. But at the very end it calls a custom DLL and it chokes when trying to call a method in the class. It says that it cannot establish a connection to SQL Server, when I am trying to call a class in the DLL. And it allows the instantiation of the class but does not like the call. Very strange.

I have run at work on several differen SQL Servers and PS versions without issue. At the client's site they have SQL 2008 R2 and PS v2.0 - both of which I have tested on.

The relevant code is

[System.Reflection.Assembly]::LoadWithPartialName('System')
[System.Reflection.Assembly]::LoadWithPartialName('System.IO')
[System.Reflection.Assembly]::LoadWithPartialName('System.Security.Cryptography')
[System.Reflection.Assembly]::LoadWithPartialName('System.Text')

[System.Reflection.Assembly]::LoadFrom("$EncryptionDLLFilePath")

$SecureAES = new-object SecureAES ($parm1, $parm2,$parm3) 
$SecureText = $SecureAES.DecodeAndDecryptString($SecuritySetting, $SecureAES.GetKey())

The error  is ... Executed as user: HTC-SQL-02\SYSTEM. A job step received an error at line 257 in a PowerShell script. The corresponding line is '    $SecureText = $SecureAES.DecodeAndDecryptString($SecuritySetting, $SecureAES.GetKey()) '. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Exception calling "DecodeAndDecryptString" with "2" argument : "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"  '.  Process Exit Code -1.  The step failed.

Any help would be appreciated. We did enable Named Pipes for SQL Server Network Onfiguration, Protocols for MSSQLSERVER and restart the server. But the message seems so unlikely for trying to access a DLL.

Any help would be appricated. I don't even know where to start.

 

Use powershell to update / install exe

$
0
0

hello ate,

 

i want to write a ps script that will auto download exe file from suppliers site
(e.g. http://www.suppliers.com/file.exe)

then after the download the scripts will check if existing file on local computer has already same file version with new download – if it is, scripts will not continue to run the exe and end the command

else – the file.exe will continue install and update the current installed application on local computer – then output reports to c:\file.log

what i have done so far is below and im not positive after this

ps
(New-Object System.Net.WebClient).DownloadFile("http://www.suppliers.com/file.exe","C:\support\file.exe")
& 'C:\support.exe' /q

(Get-Command "C:\Program Files (x86)\Uni\Bin\Uni.exe").FileVersionInfo.Fileversion

 

thanks heaps!

Viewing all 10624 articles
Browse latest View live