I have to send an email using a pre-defined account, I have all the information, smtp server name, email address, user, password. This account uses TTL.
How to create the script to send this email using VBA.
I'm having problems with the Credential parameter, I don't know how to put the username and password
"Send-MailMessage -To 'xxxx#yyy' -from 'kkk#yyyy' -subject 'Teste' -body 'Testando o envio' -stmpserver 'smtp.gmail.com' -UseSSL -Port 587 -Credential (I don't know how to make this parameter) "
See this SO post how to convert a username-password-pair into a PowerShell credential:
$userName = 'test-domain\test-login'
$password = 'test-password'
$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $pwdSecureString
Send-MailMessage -Credential $credential ...
Note: Try to avoid putting passwords into your scripts. Store it somewhere safely, or let the user input it with Read-Host or Get-Credential.
Related
I have a SQL script which I need to execute with credentials that I retrieve from registry.
To store them in the registry
$secureCredential = Get-Credential -Message "Enter service account credential as DOMAIN\Username format."
$credentialName = Read-Host "Enter a name for this credential"
$securePasswordString = $secureCredential.Password | ConvertFrom-SecureString
$userNameString = $secureCredential.Username
New-Item -Path HKLM:\Software\$OrgName\Credentials\$credentialName
New-ItemProperty -Path HKLM:\Software\$OrgName\Credentials\$credentialName -PropertyType String -Name UserName -Value $userNameString
New-ItemProperty -Path HKLM:\Software\$OrgName\Credentials\$credentialName -PropertyType String -Name Password -Value $securePasswordString
To Retrieve
$secureCredUserName = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name UserName
$secureCredPassword = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name Password
$dbCreatorUserName = $secureCredUserName.UserName
$dbCreatorPassword = ConvertTo-SecureString -String $secureCredPassword.Password
Due to DB permission the script has to be executed with these credentials. So
I retrieve them from the registry:
$secureCredUserName = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name UserName
$secureCredPassword = Get-ItemProperty -Path HKLM:\Software\MyCompany\Credentials\TfsBuildAgent -Name Password
$dbCreatorUserName = $secureCredUserName.UserName
$dbCreatorPassword = ConvertTo-SecureString -String $secureCredPassword.Password
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $using:dbCreatorUserName, $using:dbCreatorPassword
Then attempt to execute sqlcmd using Invoke-Command so that I can provide the domain credentials:
Invoke-Command -ComputerName $env:ComputerName -EnableNetworkAccess -Credential $credential -Authentication Default {sqlcmd.exe -b -S 'db-systest' -i C:\Database\Database_Package.sql -E -v }
But get Error:
Microsoft ODBC Driver 11 for SQL Server : Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'..
I have tried both -Authentication Default and -Authentication Negotiate,
the server does not support Kerberos and CredSSP is prohibited by domain policy.
Does anyone know how to pass Get-Credentials to a SQL login using powershell?
I have tried many different ways but no success.
This needs to run in winpe - i can get the credentials using Get-Credential but i need to use those to connect to SQL DB - i keep getting.
Login failed for 'NT AUTHORITY\ANONYMOUS LOGIN' The below code works fine in Windows - I am logged on as the user though so it must not be passing the credentials. if i remove the trusted_connection=true; i get the failed login and this is the best test for WINPE as no one is logged on. Is there a way to pass those Get-Credentials to SQL?
Either that or the same code does not work in WINPE - not sure why though?
$Cred = Get-Credential
Function SQL_CONNECT ($Query){
$ConnectionString = "server=VM855;database=LDMS2016;user id=$Cred.Username;password=$Cred.Password;trusted_connection=true;"
$SqlConnection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.Connection = $SqlConnection
$SqlCmd.CommandText = $Query
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$a = $SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
}
$Owners = SQL_CONNECT "Select Task_Name, Task_owner, first_action_query_date from PROV_HISTORY_TASK" | Select-Object Task_Owner, first_action_query_date
$Owners
SQL connections use either:
Windows Authentication ("Trusted_Connection=True")
or
SQL Authentication ("User Id=myUsername;Password=myPassword;")
You cannot have both "Trusted_Connection" and "User ID/Password", you have to pick one.
In order to use Windows Authentication, the PowerShell process must be running as the user that has access to the database. i.e. you have to launch the PowerShell process as impersonating that user, and run your code.
Rough example will look something like this:
# Get the other user's credentials
$credential = Get-Credential
# Execute a scriptblock as another user
$commands = #'
#....code....
$ConnectionString = "server=VM855;database=LDMS2016;trusted_connection=true;"
#.....etc....
'#
Start-Process -FilePath Powershell.exe -LoadUserProfile -Credential $credential -ArgumentList '-Command', $commands
Or, the easier method is to just use SQL authentication, and hard code the username/password.
$ConnectionString = "server=VM855;database=LDMS2016;user id=Username;password=Password;"
Or at the very least you will have to use Read-Host to read in the username and password because $Cred.Password returns System.Security.SecureString and not the password in plain text.
For ex.
$Username = Read-Host "User:"
$Password = Read-Host "Password:"
$ConnectionString = "server=VM855;database=LDMS2016;user id=$Username;password=$Password;"
I made a script in powershell to make a .REQ from a .INF file. This file (the .REQ) must then be imported into the PKI, which then generates a .CERT.
My problem is that I do not know how to authenticate myself to the PKI from Powershell. Second question if I may ask, how do I choose the certificate Template (in the PKI online screen, I have a choice box in which I choose my template (for eg Wifi client").
Here is my code so far, of course I don't know how to authenticate, that is my main question here. I precise that I know the login and the password (I successfully connect myself using RDP).
# Generate Request File .req
Write-Host " This script generates a .REQ (step 1/3 in certificate creation)"
Write-Host " "
Write-Host " Step 1/3: create .INF file with Key length and other parameters, create a .REQ file"
Write-Host " Step 2/3: import the .REQ file into the Intermediate PKI and generate a .CER"
Write-Host " Step 3/3: from the .CER file, create a .PFX with the exportable key"
# Variables declaration
#
# UID = nom du PDA ou son numero de serie
# $Login = login sur la PKI intermediate
# $Pass = Password sur la PKI intermediate
$Date = (Get-Date).ToString('ddMMyyyy')
Write-Host " "
[string]$UID = read-host "Please enter the Device Name (or Serial Number)"
$Path = "C:\users\youcef\Desktop\Julie\"
$Login = "me"
$Pass = "pass"
# INF File content
$ReqFile = "$UID" + "_" + "$Date" + ".req"
$InfFile = #"
[NewRequest]`r
Subject = "CN=$UID"`r
KeySpec = 1
Exportable = TRUE
RequestType = PKCS10
[PolicyStatementExtension]
Policies=InternalPolicy
[InternalPolicy]
OID= 1.2.3.4.1455.67.89.5
Notice="Legal Policy Statement
[Certsrv_Server]
RenewalKeyLength=1024
RenewalValidityPeriod=Years
RenewalValidityPeriodUnits=2
CRLPeriod=weeks
CRLPeriodUnits=52
CRLDeltaPeriod=Days
CRLDeltaPeriodUnits=0
LoadDefaultTemplates=1
AlternateSignatureAlgorithm=0
"#
# Generate Request File from INF File
Write-Host "Generating Certificate Request file..." -ForegroundColor Yellow;
$MYCERTNAME = "$UID" + "_" + "$Date" + ".inf"
New-Item $MYCERTNAME -type file -value $InfFile
certreq -new $path\$MYCERTNAME $path\$ReqFile
Write-Host " "
Write-Host "Certificate request file for $UID successfully generated!" -foregroundcolor DarkGreen;
# Authentication on PKI: HERE I AM TOTALLY LOST
Connect-CertificationAuthority -ComputerName ca01.company.com
$password = ConvertTo-SecureString "password" -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $Login, $Pass
$serverNameOrIp = "192.168.1.1"
Restart-Computer -ComputerName $serverNameOrIp `
-Authentication default `
-Credential $cred
<any other parameters relevant to you>
$cred = new-object -typename System.Management.Automation.PSCredential `
-argumentlist $username, $password
$serverNameOrIp = "https://pki.mycompany.fr/certsrv/certrqxt.asp"
Restart-Computer -ComputerName $serverNameOrIp `
-Authentication default `
-Credential $cred
<any other parameters relevant to you>
certreq -submit -config "https://pki.mycompany.fr/certsrv/certrqxt.asp" $path\$ReqFile $path\$UID.cer
#certreq -submit -config "https://pki.mycompany.fr\certsrv" $path\$ReqFile $path\$UID.cer
certreq -accept $path\$UID.cer
certutil -exportpfx -p "Welcome123" MY $UID $path\clientcerts\$UID.pfx
I solved my issue in launching my script directly on the server.
Not the best solution, but I neevr managed to use Remote Session in Powershell
I've written a powershell script that creates a new sql server database and login, and then sets the database owner to the newly created user. This is successful. However, I get a login failed exception when attempting to login within the same script. If I use SQL Server Management Studio the login works.
Here's the script:
$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database($server, 'TestDB')
$db.Create()
$login = new-object Microsoft.SqlServer.Management.Smo.Login("(local)", 'TestUser')
$login.LoginType = 'SqlLogin'
$login.PasswordPolicyEnforced = $false
$login.PasswordExpirationEnabled = $false
$login.Create('Password1')
$server = new-Object Microsoft.SqlServer.Management.Smo.Server("(local)")
$db = New-Object Microsoft.SqlServer.Management.Smo.Database
$db = $server.Databases.Item('TestDB')
$db.SetOwner('TestUser', $TRUE)
$db.Alter()
Invoke-Sqlcmd -ServerInstance localhost -Database 'TestDB' -Username 'TestUser' -Password 'Password1' -Query "SELECT * FROM sysusers"
I've tried adding a Start-Sleep (up to 5mins) to no avail, and I've tried Restart-Service mssqlserver -Force, also to no avail.
Any ideas?
This isn't an answer to the problem I was encountering, just a work around. The script is being run as part of an automated deployment, the overall scripts are run under the "NT AUTHORITY\SYSTEM" username, so to get around my logging in issue I'm simply using Integrated Security=true.
I think your final line should read:
Invoke-Sqlcmd -ServerInstance '(local)' -Database 'TestDB' -Username 'TestUser' -Password 'Password1' -Query "SELECT * FROM sysusers"
Notice the use of '(local)' rather than 'localhost'.
follow the codes below
$SqlServer = "servar.site.com Or server ip with port"
$SqlDBName = "dbName"
$sqlConnection = New-Object Microsoft.SqlServer.Management.Common.ServerConnection
$sqlConnection.ServerInstance=$SqlServer
$sqlConnection.LoginSecure = $false
$sqlConnection.Login = "userid if you have"
$sqlConnection.Password = "password if is needed to connect to sql server"
Add-Type -Path "C:\Program Files\Microsoft SQL
Server\140\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($sqlConnection)
# get all of the current logins and their types
$server.Logins |
Select-Object Name, LoginType, Parent
# create a new login by prompting for new credentials
$NewLoginCredentials = Get-Credential -Message "Enter credentials for the new login"
$NewLogin = New-Object Microsoft.SqlServer.Management.Smo.Login($server,
$NewLoginCredentials.UserName)
$NewLogin.LoginType = [Microsoft.SqlServer.Management.Smo.LoginType]::SqlLogin
$NewLogin.Create($NewLoginCredentials.Password)
# create a new database user for the newly created login
$NewUser = New-Object
Microsoft.SqlServer.Management.Smo.User($server.Databases[$SqlDBName],
$NewLoginCredentials.UserName)
$NewUser.Login = $NewLoginCredentials.UserName
$NewUser.Create()
$NewUser.AddToRole("db_datareader")
I'm writing a webservice with PowerShell commands where I want to start and stop services on the local computer and also on remote computer.
It's not a problem to start and stop the services on remote computers. I do this with an WmiObject as you can see below.
If I want to start a local service it says that I don't have the permissions.
I can't use an WmiObject with Credentials if I want to start an local service.
What can I do to start the service with admin rights?
My Script (strScriptText):
$username = "domain\administrator"
$pw = convertto-securestring "password" -asplaintext -force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $pw
$computername = "serverAB"
if ( $computername.Contains("serverAB")){(Get-WmiObject -class Win32_Service -filter "name='AppIDSvc'").startservice().returnvalue}
else {(Get-WmiObject -class Win32_Service -ComputerName $computername -Credential $cred -filter "name='AppIDSvc'").startservice().returnvalue}
vb:
runspace = RunspaceFactory.CreateRunspace()
runspace.Open()
pipeline = runspace.CreatePipeline()
pipeline.Commands.AddScript(strScriptText)
pipeline.Commands.Add("Out-String")
Can't you try to use the old .NET method through PowerShell.
# Create an authentication object
$ConOptions = New-Object System.Management.ConnectionOptions
$ConOptions.Username = "dom\jpb"
$ConOptions.Password = "pwd"
$ConOptions.EnablePrivileges = $true
$ConOptions.Impersonation = "Impersonate"
$ConOptions.Authentication = "Default"
# Creation of a rmote or local process
$scope = New-Object System.Management.ManagementScope("\\dom.fr\root\cimV2", $ConOptions)
$ObjectGetOptions = New-Object System.Management.ObjectGetOptions($null,
[System.TimeSpan]::MaxValue, $true)
$proc = New-Object System.Management.ManagementClass($scope,
"\\dom.fr\ROOT\CIMV2:Win32_Process", $ObjectGetOptions)
# Equivalent to :
# $proc = [wmiclass]"\\.\ROOT\CIMV2:Win32_Process"
# $res = $proc.Create("cmd.exe")