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
Related
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.
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
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
EDIT:
I want to retrieve session data from a specific account using
PowerShell. According to this documentation:
https://learn.microsoft.com/en-us/powershell/module/skype/get-csusersession?view=skype-ps
Get-CsUserSession command is able to do this. I am using this
command according to the upper's link example
Get-CsUserSession -User account#companyX.onmicrosoft.com -StartDate "6/1/2018 07:00 PM"
and then I am getting the following error:
A parameter cannot be found that matches parameter name 'StartDate'.
+ CategoryInfo : InvalidArgument: (:) [Get-CsUserSession], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.Rtc.Management.Hosted.Data.GetCsUserSessionCmdlet
+ PSComputerName : admin1e.online.lync.com
What is wrong with that and what is the correct declaration?
I am making a connection to Skype for business service with the following script:
$credential = Get-Credential
Import-Module MSOnline
Connect-MsolService -Credential
$credential Import-Module SkypeOnlineConnector
$lyncSession = New-CsOnlineSession -Credential
$credential Import-PSSession $lyncSession
What I would like to do is to set using a particular static account and password from the PowerShell script (using some sort of declaration variable strings), instead of running this command and have to type the credentials in a separate window. Meaning that I want to avoid using $credential = Get-Credential command. Is this possible?
As stated in documentation you linked (only at the top paragraph though), you have to use StartTime not StartDate. The error you receive is the typical symptom that you either has a typo in parameter name or this parameter doesn't exist for that function.
I'll request to change the example in the docs a bit later, seems like someone who wrote them were mixing up with another cmdlet.
Edit: to store credentials you can export your password like this:
"P#ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File C:\Users\username\password2.txt
And then import like this:
$password = Get-Content -Path "C:\Users\USUARIOPC\password2.txt" | ConvertTo-SecureString -String $password
$credential = New-Object System.Management.Automation.PsCredential("yourlogin#domain.com", $password)
In the meantime, I tried the following query. Probably is not too safe to use a password in a script but for us who want to do it like this is a nice solution.
$username = "account1#companyX.onmicrosoft.com"
$password = "abcdefg"
$secstr = New-Object -TypeName System.Security.SecureString
$password.ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $secstr
$credential = $cred
Import-Module MSOnline
Connect-MsolService -Credential $credential
Import-Module SkypeOnlineConnector
$SFBSession = New-CsOnlineSession -Credential $credential
Import-PSSession $SFBSession
I am using following code for running exe from PowerShell. However, it is throwing the error mentioned in the subject.
$uid = "ABCDomina\builder"
$pwd = "password"
$Args = "-Verb RunAs -Wait -passthru"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($uid,(ConvertTo-SecureString -String $pwd -AsPlainText -Force))
Start-Process -FilePath C:\windows\system32\system32\notepad.exe -Credential ($cred) -Argumentlist $Args
Error:
Start-Process : This command cannot be run due to the error: Logon failure:
unknown user name or bad password.
At C:\CD_Clinical\Nightly\DataLabs\Untitled1.ps1:5 char:1
+ Start-Process -FilePath C:\windows\system32\system32\notepad.exe -Credential ($c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Why not use -Credential Get-Credential? it seems a bit pointless as well trying to convert an item to a secure string if you are displaying it plain text, this will mean it gives you a prompt for username and password.
But if thats the route you want to go down then this should work.
$MyCredential=New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $Uid, ($pwd | ConvertTo-SecureString -AsPlainText -Force)