Can you use MFA in powershell without using Exchange Online Powershell Module? - powershell

I've tried using "Send-MailMessage", but it looks like there isn't a parameter for authentifaction.
Can someone help here?

Send-MailMessage has a Credential parameter, see an example:
$smtpServer = 'smtp.office365.com'
$user = 'smtp#domain.com'
$pass = 'Password'
$creds = [pscredential]::new($user,($pass | ConvertTo-SecureString -AsPlainText -Force))
Send-MailMessage -SmtpServer $smtpServer -Credential $creds -To[...]
It's should work with MFA Enabled, if not, Generate an App Password and use it instead, See this link

Related

Import Password -credential

I am trying to send a file to email.
I found this code and it worked
but I want to add the password automatically
is there any solution ??
$MyEmail = "tests21#gmail.com"
$Password = "TEST2132"
$SMTP= "smtp.gmail.com"
$To = "TEST212#gmail.com"
$Subject = "LOG FILE!"
$Creds = (Get-Credential -Credential "$MyEmail")
$attachment = "C:\TEST.txt"
Start-Sleep 2
Send-MailMessage -To $to -From $MyEmail -Subject $Subject -Attachment $attachment -SmtpServer $SMTP -Credential $Creds -UseSsl -Port 587 -DeliveryNotificationOption never
Non-secure method
Here is how you create a credential object from a password string.
# Some email credentials
$username = 'Username'
$password = 'Password' | ConvertTo-SecureString -AsPlainText -Force
$Creds = [PSCredential]::New($username,$password)
As it was pointed in the comments, setting a password directly in the script is insecure since anybody that could get access to the script would see the password.
Secret management module method
This method requires a little bit of preparation but is the best in my opinion since the password is retrieved from a secret vault instead of being readily available in your script.
Prerequisites
Modules
Install the following modules
Install-Module Microsoft.PowerShell.SecretManagement
Install-Module SecretManagement.JustinGrote.CredMan
Vault
Create a vault to store the email credentials and possibly many others in the future.
Register-SecretVault -ModuleName SecretManagement.JustinGrote.CredMan -Name 'Default'
Save the credentials into the vault.
$username = 'Username'
$password = 'Password' | ConvertTo-SecureString -AsPlainText -Force
$Creds = [PSCredential]::New($username, $password)
Set-Secret -Name 'SomeEmailCreds' -Secret $Creds -Vault Default
How to use
Once every prerequisites is filled, you can get the credentials from the local vault by using the Get-Secret statement. The Set-Secret should be nowhere in your script and you should use it only if you need to update your credentials at some point.
$Creds = Get-Secret -Vault Default -Name 'SomeEmailCreds'
Notes
Note that the vault is "per user" and "per machine" so it should be created on the user and the machine it will run from.
SecretManagement also have other modules than the CredsMan one by Justin Grote which use all sort of different vault so there are implementation for Azure key vaults, 1password, etc

Add username and password to Powershell script

I'm trying to create a powershell script to allow my kids to reboot my Raspberry Pi from their Windows computer if need be. I've tested everything and have gotten it to work, but the only hitch is that it's prompting for a username and password. I realize the line that's doing it is:
New-SSHSession -ComputerName "myPi" -Credential (Get-Credential)
I've done some searching, but I can't seem to figure out if it's possible to replace the "(Get-Credential)" section to automatically enter the username/password.
And yes, I'm aware of the security risks. They could do much more damage to the Windows machine than they could ever do on the Pi, and the settings on the Pi are very easily restored, so no worries from my end.
Something like this should work:
$user = "someuser"
$pass = ConvertTo-SecureString -String "somepassword" -AsPlainText -Force
$creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$pass
New-SSHSession -ComputerName "myPi" -Credential $creds
You could also call a file that has the password encrypted in it. Note this can only be decrypted by the account it was generated on on the computer it was generated on.
$pass = "Password"
$Username = "Username"
$outfile = "c:\filelocation.xml"
$secureStringPwd = $pass | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($Username,$secureStringPwd)
$credential | Export-CliXml -Path $OutFile
Addressing Bill.
Correct, hard coding the password in the script is bad practice. Below is how I would change the first portion.
The above came from a custom script that's purpose was to create many cred accounts off a input json is why I wrote it that way.
$outfile = "c:\filelocation.xml"
Get-Credential | export-clixml -path $OutFile
You then can call the file in your script like so but this has to be done on the same user and computer that the creds file was generated on.
$Creds = Import-Clixml -Path "c:\file.xml"
New-SSHSession -ComputerName "myPi" -Credential $creds
Good point Edited -argumentlist.
Another option could be to do a 1 time setup with get-credential then convert the password to plaintext using convertfrom-securestring and then in the file you can take your password plaintext secure string and so something similar to the other answers:
$user = "someuser"
$pass = "YOUR LONG PASSWORD GUID FROM ABOVE" | convertTO-securestring
$creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$pass
New-SSHSession -ComputerName "myPi" -Credential $creds
This lets you do a one time setup, but avoids having multiple files or having your password appear in a readable way in the script.
If you go this way you need to do the setup FROM the account that will run the script ON the machine that will run the script, because it uses those for the encryption as far as I know.

Encrypting password or workaround

I am bit of a lazy guy, so I have created a script that opens many applications for me. Works fine as ISE opened with Administrator credentials, also opens apps with admin creds, however some of them need a different credentials.
Is it possible, to make powershell remember typed in password each time I log in and open it? (I know that variables are stored only till ps is opened)
Thing is - I cannot store a visible password in profile/text file or in a script, as this is a jump server used by many people. Is it somehow possible to type a password once, make PS encrypt it and each time I will open PS, it will decrypt it and use? or any workaround possible around this?
edit with code:
It's the only part I would like to change
$currentPW = "some password"
$credentials = New-Object System.Management.Automation.PSCredential ("domain\username",$CurrentPW)
start "c:\application.exe" -credential $credentials
It kinda works but it would require me, to input the password everytime I log in to device, so I could go for option like:
$currentPW = read-host "Provide your password"
$credentials = New-Object System.Management.Automation.PSCredential ("domain\username",$CurrentPW)
start "c:\application.exe" -credential $credentials
but this would require me to input the password each time I log in to system and open PS as it does not remember variables after restart.
So...is it even possible to make this work?^^
You can use ConvertTo-SecureString to encrypt the password using the users account key, then save this secure string to a file to load at a later time.
This assumes you are the only one with access to the logon account (not an account with shared credentials), as anyone who can logon as the account can decrypt the file.
$username = "domain\username"
$passwordFile = "C:\folder\EncryptedPassword.txt"
#if password file exists: populate $securePwd from file contents
If (Test-Path $passwordFile) {
$pwdTxt = Get-Content $passwordFile
$securePwd = $pwdTxt | ConvertTo-SecureString
}
#if no file: prompt for password, create file and populate $securePwd
Else {
$password = Read-Host "Provide your password"
$securePwd = $password | ConvertTo-SecureString -AsPlainText -Force
$securePwd | ConvertFrom-SecureString | Set-Content $passwordFile
}
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePwd
Start-Process "c:\application.exe" -Credential $credentials
If you have PowerShell 3.0 or newer, you can also combine Get-Credential with Export-CliXml to export a PSCredential object as an XML file. Example:
Get-Credential | Export-CliXml "C:\XML Files\credential.xml"
You can then import the credentials using Import-CliXml. Example:
$credential = Import-CliXml "C:\Xml Files\credential.xml"
Note that the password is encrypted using DPAPI, so you can only import the credentials using Import-CliXml on the same computer using the same user account that was used to export the credentials using Export-CliXml.

PowerShell Invoke-Webrequest / provide password and skip promt

I made a script accessing an API which requires authentication. The this is working if I enter the credentials (email+pw) into the prompt:
$cred = Get-Credential
$web = Invoke-WebRequest -Uri $srcURI -Credential $cred
But this does not allow me to automate this setup, as a prompt is always coming up asking for Username/PW.
I tried several different ways, but none seems to be working:
For me the most logical was:
$username="user"
$password="password1"
$PScredOBJ = New-Object -TypeName System.Management.Automation.PSCredential($username,$password)
$cred2 = Get-Credential -Credential $PScredOBJ
Result: Still an empty prompt showing up.
Anybody knows how to handle this?
Thx
This has been covered in a lot of places, a google search would give an answer. Here's the first one I found using "automate ps credential" as my search terms. To reiterate:
$password = "password" | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential "username",$password

Email credentials when using send-mailmessage command

I have searched through many many forums and they do explain how to do this but the technical language is just too difficult to understand as I'm very new to powershell. I would like this explained to me step by step (baby steps). I would like to run this powershell command in a batch file (.bat). I have a batch file that does robocopy backups weekly and I want the batch file to send me a email when the backup is complete. The only issue I have is the credentials, I get a pop-up box asking for the user name and password. When I eneter this information the email will send successfully. Here is what I have;
Using: powershell V2.0 Windows 7 Ultimate
Powershell -command send-mailmessage -to emailadress#provider.com -from emailaddress#provider.com -smtp smtp.broadband.provider.com -usessl -subject 'backup complete'
$from = "example#mail.com"
$to = "example#mail.com"
$smtp = "smtpAddress.com"
$sub = "hi"
$body = "test mail"
$secpasswd = ConvertTo-SecureString "yourpassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($from, $secpasswd)
Send-MailMessage -To $to -From $from -Subject $sub -Body $body -Credential $mycreds -SmtpServer $smtp -DeliveryNotificationOption Never -BodyAsHtml
You could pass the credential object in your same command - which would avoid the popup:
Powershell -Command 'Send-MailMessage -to "emailadress#provider.com" -from "emailaddress#provider.com" -smtp "smtp.broadband.provider.com" -usessl -subject "backup complete" -credential (new-object System.Net.NetworkCredential("user","pass","domain"))'
I'd recommend storing the username/password in a somewhat more safer format, but this should do your trick.
I'm not sure you can do SMTP authentication using the send-mailmessage command. But, you can send a message through an SMTP server that requires authentication using the Net.Mail.SmtpClient object and the System.Net.Mail.MailMessage object. See How to pass credentials to the Send-MailMessage command for sending emails for a good example.
look at the last exemple of send-mailmessage helppage
you will see you can pass credential whith the parameter -credential domain01\admin01
look here Using PowerShell credentials without being prompted for a password if you dont want any prompt (save your cred in a text file)