Using database mail (sp_send_dbmail) in Powershell - powershell

Before this I was using AutoIT and it works but I want to learn Powershell.
Now I am trying to use Powershell to send email by using dbmail with SQL account.
But I got 'Failed to login.. ' with these description:
CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd], SqlException
CategoryInfo : ParserError: (:) [Invoke-Sqlcmd], ParserException
This is my script:
$recipients = 'abc#def.com'
$username = 'abc'
$passwordFile = "E:\Users\Password.txt"
$password = Get-Content $passwordFile | ConvertTo-SecureString
#(Get-Credential).Password | ConvertFrom-SecureString | Out-File "E:\Users\Password.txt"
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($username, $password)
$query =
"EXEC database.dbo.sp_send_dbmail
#profile_name = 'abc',
#recipients = $recipients,
#body_format = 'HTML',
#body = 'Dear all,<BR><BR>Success.<BR><BR>Regards,<BR>me',
#subject = 'SUCCESS-'$datetime"
Invoke-Sqlcmd -ServerInstance "server" -Database 'database' -Username $username -Password $credential -Query $query
I tried to change the -ServerInstance format into instance\server but it will return the server was not found.

Related

Excute Shell Script remotely to Azure Linux VM

i'am trying to excute a shell script to an azure linux virtual machine using powershell
Why I'm i using powershell? :
The virtual machine has a Copied VHD from storage account which means it doesn't have Azure VM agent
so i can't use :
azure vm extentions
azure vm Runs
i tried also using an automation runbook with the ssh module and got those errors :
Exception calling "Connect" with "0" argument(s): "Server HMAC algorithm not found" At C:\Modules\User\SSH\SSH.psm1:68 char:5 + $SSHConnection.Connect() + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
and
Exception calling "RunCommand" with "1" argument(s): "Client not connected." At C:\Modules\User\SSH\SSH.psm1:69 char:5 + $ResultObject = $SSHConnection.RunCommand($ScriptBlock.ToString() ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : SshConnectionException
which is based on my understanding caused by the vm that is missing KexAlgorithms to describe which methods are supported by the SSH daemon
What i'm trying to do now is to ssh into the vm and excute the command using powershell
here is what i got now (a Powershell scripot to ssh into the vm and excute a command):
$Password = "pwd"
$User = "pwd"
$ComputerName = "ip adress"
$Command = "touch tst.txt"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials #Connect Over SSH
echo 'Executing...'
$output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Output
Remove-SSHSession -Name $SessionID | Out-Null
im getting this error :
Invoke-SshCommand : A parameter cannot be found that matches parameter name 'Index'.
At C:\Users\octoadmin\Desktop\sign in.ps1:11 char:30
+ $output = (Invoke-SSHCommand -Index $SessionID -Command $Command).Out ...
+ ~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-SshCommand], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Invoke-SshCommand
i looked in the internet but couldn't find anything.
apparently the ssh invoke command can't find a session with the index $SessionID
but i don't know where exactly is the problem
hope someone can guide me to the right direction.
Updating Posh-SSH worked for me with this code :
to install Posh-SSH :
Install-Module -Name Posh-SSH -RequiredVersion 2.1
The Script:
$Command = "fetch $scripturl; sh script.sh"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$ComputerName = Get-AzPublicIpAddress -ResourceGroupName $RG -Name $IPName | Select-Object -ExpandProperty ipAddress
echo 'ip is : '
echo $ComputerName
echo 'logging...'
$SessionID = New-SSHSession -ComputerName $ComputerName -AcceptKey -Credential $Credentials
echo 'Exucuting...'
$Query = (Invoke-SshCommand -SSHSession $SessionID -Command $Command).Output
echo $Query
Remove-SSHSession -Name $SessionID | Out-Null

Invoke-ProcessTable : The provided application id is invalid

This is what I've got in my Invoke-ProcessTable powershell script (snippet)
# create pscredential object
$credObject = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $ServicePrincipal, $secStringPassword
#Get App Id for Service Principle
$SPDetails = Get-AzADServicePrincipal -DisplayName $ServicePrincipal
$SP_AppId = ($SPDetails).AppId
Invoke-ProcessTable `
-TableName $TableName `
-DatabaseName $DatabaseName `
-RefreshType Full `
-Server $Server `
-ServicePrincipal `
-Credential $credObject `
-TenantId $TenantId `
-ApplicationId $SP_AppId
$TenantId is hard coded in the script.
and this is the error I'm getting
Invoke-ProcessTable : The provided application id 'app:"service
principle name"#6"tenant id"5' is invalid. Parameter name: id At
C:\temp\powerrshell\invoke-processtable.ps1:25 char:1
Invoke-ProcessTable `
+ CategoryInfo : NotSpecified: (:) [Invoke-ProcessTable], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.AnalysisServices.PowerShell.Cmdlets.ProcessTable
I wasn't expecting the Application Id to be in the format that is being shown in the error message.
Anyway, where am I going wrong?
School boy error
I was passing in the wrong parameter to the $credObject object
I was sending in the ServicePrincipleName ($ServicePrincipal) instead of the Application Id ($SP_AppId).
Once I did this all worked.
#Get App Id for Service Principle
$SPDetails = Get-AzADServicePrincipal -DisplayName $ServicePrincipal
$SP_AppId = ($SPDetails).AppId
# create pscredential object
$credObject = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $SP_AppId, $secStringPassword

Get-Credentials error in PowerShell 'Cannot find an Overload for "PSCredential"'

I'm new to PowerShell. I am trying to make it so I can setup a new computer connecting to the network to allow me to do certain tasks. When I run this:
$domain = "mydomain.com"
$mycred = get-credential
$credential = New-Object System.Management.Automation.PSCredential("$($domain)\$($mycred.Username)","$($mycred.Password)")
$compName = Read-Host -Prompt "Enter new computer name"
Add-Computer -DomainName $domain -newname $compName -Credential $credential -Restart
Pause
I get the error:
New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At C:\Users\entername\Downloads\1-JoinDomainCred.ps1:7 char:15
... redential = New-Object System.Management.Automation.PSCredential("$($ ...
CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Where am I going wrong?
Get-Credential aready returns a proper credentials object. Just use that:
$mycred = Get-Credential; Add-Computer ... -Credential $mycred
PowerShell is not C#, pass the arguments as an array without the ():
$credential = New-Object System.Management.Automation.PSCredential "$($domain)\$($mycred.Username)",$mycred.Password

Using powershell function Send-MailMessage getting an error: Cannot find an overload for "PSCredential"

I want to send an email via powershell using function Send-MailMessage.
My smtp server requires UserName and Password.
I am passing it as parameters, however getting an error.
$CredUser = "123UserPass"
$CredPassword = "1234/5678/999"
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $CredUser, $CredPassword
Send-MailMessage -SmtpServer "smtp.amazonaws.com" -Port 587 -Credential $Credential -UseSsl -From 'DBATeam#email.com' -To 'me#email.com' -Subject 'TEST'
Error message:
New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At line:3 char:16
+ ... redential = New-Object -TypeName System.Management.Automation.PSCrede ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Send-MailMessage : Cannot process argument transformation on parameter 'Credential'. userName
At line:4 char:90
+ ... tp.us-east-2.amazonaws.com" -Port 587 -Credential $Credential -UseSsl ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingArgumentTransformationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.PowerShell.Commands.SendMailMessage
I tried to use ConvertTo-SecureString -String "mypassword" but also getting a conversion error.
Try:
$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force
Provided you are using version 5.1 or later you can also use the ::new() static method in place o f New-Object (totally optional).
$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )
Send-MailMessage -SmtpServer "smtp.amazonaws.com" -Port 587 -Credential $Credential -UseSsl -From 'DBATeam#email.com' -To 'me#email.com' -Subject 'TEST'
You can incorporate splatting if you want to add some readability:
$credpassword = ConvertTo-SecureString -AsPlainText "mypassword" -Force
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )
$SMTPParams = #{
SmtpServer = 'smtp.amazonaws.com'
Port = 587
Credential = $Credential
UseSsl = $true
From = 'DBATeam#email.com'
To = 'me#email.com'
Subject = 'TEST'
}
Send-MailMessage #SMTPParams
Note: some may frown on a password being visible. You can store the password securely in a file, then call it back for use. As long as it's by the same user on the same machine.
$SecurePassword = Read-Host -Prompt "Enter Password" -AsSecureString
$SecurePassword | ConvertFrom-SecureString | Out-File C:\temp\SecurePasswword.txt
$CredPassword = Get-Content C:\temp\SecurePasswword.txt | ConvertTo-SecureString
[System.Management.Automation.PSCredential]::new( $CredUser, $CredPassword )
Obviously you'll want to change the path to the file, so as not to advertise it. Establish the password file with the first 2 lines. Then use the second 2 in your current script to set up the creds for your SMTP command...
Documented here

Credential connection doesn't work

I'm attempting to use credential connection in a powershell script. I tried :
$credential = Get-Credential
and
$credential = $host.ui.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "Domain")
But when I execute a query, I get the following message :
Invoke-SqlQuery -Query $Query -Server $SERVER -database $DataBase -credential $credential
Exception calling "Open" with "0" argument(s): "Login failed for user '\sa'."
\Modules\InvokeSqlQuery\InvokeSqlQuery.psm1:155 char:14
+ $cnn.Open <<<< ();
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Even if I use the correct Credential, it fails. Has anyone had the same problem ?
Invoke-SqlQuery calls
$cnn = New-SqlConnection $Server $Database $Credential $ConnectionTimeout
which creates the error.
By the way, I would like to know how to load this assembly :
new-object [System.Management.Automation.PSCredential]
New-Object : Cannot find type [[System.Management.Automation.PSCredential]]: make sure the assembly containing this type is loaded.
Thanks.
To answer your second question :-), the assembly containing PSCredential is already loaded. It is an assembly required by PowerShell. Try this:
$username = ConvertTo-SecureString username -AsPlainText -Force
$password = ConvertTo-SecureString pass!word -AsPlainText -Force
$cred = new-object management.automation.pscredential $username,$password
try this (PsSnapin: SqlServerCmdletSnapin100):
$pwd = read-host -AsSecureString -Prompt "Password"
Invoke-Sqlcmd -Query $Query -Serverinstance $SERVER -database $DataBase –Username “MyLogin” –Password $pwd