Cannot save credentials - powershell-4.0

I'm trying to save the credentials using code like this:
$user = "test#mail.ru"
$password = Get-Content pass.txt | ConvertTo-SecureString
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user,$password
Send-MailMessage -To test#mail.ru -Subject Test -Body Check -SmtpServer smtp.domen.ru -From test#mail.ru -Credential $credentials
Now when you run the PowerShell script - generates a form input password "Windows PowerShell credentials request". How to get rid of this query, because the credentials are stored?

Related

Function to copy file on a remote service

I have written the below function to copy file on a remote server
Function deploy-file{
PARAM(
[Parameter(Mandatory=$true,Position=0)][STRING]$cred,
[Parameter(Mandatory=$true,Position=1)][STRING]$server,
[Parameter(Mandatory=$true,Position=2)][STRING]$destdir,
[Parameter(Mandatory=$true,Position=3)][STRING]$file
)
$parameters = #{
Name = $server
PSProvider = "FileSystem"
Root = $destdir
Credential = $cred
}
new-psdrive #parameters
$d=$server + ":\"
copy-item $file $d -force
remove-psdrive $server -ErrorAction SilentlyContinue
}
Now, I am calling the above function from the main file as below:
$sn=abc.com
$server=($sn -split "\.")[0]
$destdir = 'e:\folder'
$file = 'file.zip'
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $usr, $pa
deploy-file $cred $server $destdir $file
There is no issue with credentials.
My script keeps running and not even throwing any error. What is wrong with the script?
Copying a file to a remote host using a PSSession would be as follows:
function Deploy-File {
[cmdletbinding()]
param(
[Parameter(Mandatory, Position=0)]
[securestring] $cred,
[Parameter(Mandatory, Position=1)]
[string] $server,
[Parameter(Mandatory, Position=2)]
[string] $destdir,
[Parameter(Mandatory, Position=3)]
[string] $file
)
try {
[IO.FileInfo] $file = Get-Item $file
$session = New-PSSession -ComputerName $server -Credential $cred
Copy-Item -Path $file -Destination $destdir -ToSession $session
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}
finally {
if($session) {
Remove-PSSession $session
}
}
}
By looking at your code is hard to tell what could be failing aside from what we know for sure is incorrect, the parameter $cred is being constrained to [string] when it actually should be [securestring]. By doing so you're rendering your PS Credential object unusable.

How to enter password text string in Host.UI.PromptForCredential Powershell Windows 10

I am trying to create a custom task in Windows task scheduler using powershell.
I have created a script that will open a UIBox with two input fields.
1. user field
2. password field
I am able to automatically insert text into the 1. user field box when the box is generated but am having trouble finding a way to insert my password into the 2. password field..
Any idea's on how I can insert my password automatically?
Below is full script so far.
$jobname = 'start_ahk_multiple_hotkeys'
$script = '-ExecutionPolicy Bypass -file C:\script.ps1'
$action = New-ScheduledTaskAction -Execute '"C:\Program Files\AHK\AutoHotkey.exe"' -Argument '%OneDrive%\Documents\01_Scripts\Hotkeys_1.ahk'
$trigger = New-ScheduledTaskTrigger -AtLogOn
$Description='This task will keep ???'
$msg = 'Enter the username and password that will run the task';
$credential = $Host.UI.PromptForCredential('Task username and password',$msg,'COMPUTERNAME\USERNAME',$env:userdomain)
$username = $credential.UserName
$password = $credential.GetNetworkCredential().Password
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -DontStopOnIdleEnd
Try{
$ErrorActionPreference='stop'
Register-ScheduledTask -TaskName $jobname -Action $action `
-Trigger $trigger -RunLevel Highest -User $username -Password $password -Settings $settings -Description $Description|Out-Null
}
Catch{
Write-Warning $_
}
$find=Get-ScheduledTask -TaskName '*Name of task*'
If($find){
Write-Host 'Task has been created sucessfully' -BackgroundColor DarkBlue
I'm stuck around this part specifically:
$credential = $Host.UI.PromptForCredential('Task username and password',$msg,'COMPUTERNAME\USERNAME',$env:userdomain)

ec2 user-data skips block of Powershell

I have this script baked into an AWS-AMI, running the script logged into an ec2-instance works, but when calling from userdata the Join AD with newname part gets skipped.
# Get Credentials from SSM
echo $new_name
$domain = "xxxx"
$username = (Get-SSMParameterValue -Name ad_domain_user).Parameters[0].Value
$password = (Get-SSMParameterValue -Name ad_domain_password -WithDecryption $True).Parameters[0].Value | ConvertTo-SecureString -asPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
# Get VPC Tags for OU Name
$vpc_id=(Invoke-RestMethod -uri http://169.254.169.254/latest/meta-data/network/interfaces/macs/$mac/vpc-id)
$env_name=(aws ec2 describe-vpcs --vpc-ids $vpc_id --query 'Vpcs[*].[Tags[?Key==`Name`] | [0].Value]' --output text)
echo "Attempting to join AD for env_name:$env_name" | Out-File "C:\Program Files\Amazon\Ec2ConfigService\Logs\pslog.txt" -Append
# Join AD with newname
Try {
if ("$env_name" -match "xxxx*") {
Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop'
} elseif ("$env_name" -match "xxxx-xxxx-*") {
$oupath = "OU=Member Servers,OU=xxxx-xxxx,OU=xxxx,DC=aws,DC=ABC,DC=ORG"
Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop' -OUpath$oupath
} elseif ("$env_name" -match "xxxx-xxxx-*") {
$oupath = "OU=Member Servers,OU=xxxx-xxxx,OU=xxxx,DC=aws,DC=ABC,DC=ORG"
Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop' -OUpath $oupath
}
} Catch {
echo $_.Exception | Out-File "C:\Program Files\Amazon\Ec2ConfigService\Logs\Error-JoinDomain.txt" -Append
}
## If Error File Exists try again
Try{
If (Test-Path "C:\Program Files\Amazon\Ec2ConfigService\Logs\Error-JoinDomain.txt" -PathType Leaf) {
if ("$env_name" -match "xxxx*") {
Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop'
} else {
Add-Computer -DomainName $domain -ComputerName $env:computername -newname $new_name -Credential $credential -Force -Restart -ErrorAction 'Stop' -OUpath $oupath
}
}
} Catch {
echo $_.Exception | Out-File "C:\Program Files\Amazon\Ec2ConfigService\Logs\Error-JoinDomain.txt" -Append
echo $_.Exception | Out-File "C:\Program Files\Amazon\Ec2ConfigService\Logs\pslog.txt" -Append
}

Foreach Nested loops issue in powershell

What I need to do is to compare the Licence attribute associated with each Username from $O365Users with Enabled attribute using the matching Employee ID in $userID (if it exists). With the standard nested ForEach (above) We use this script to help manage our local Active Directory and MSOL (Microsoft Online – Office 365) objects. My question is : I have got an issue related to the foreach loop so same object returns multiple (forever) I want to do it line-by-line for each user
Import-Module ActiveDirectory
Import-Module MSOnline
$password = ConvertTo-SecureString 'PASSWORD' -AsPlainText -Force
$LiveCred = New-Object System.Management.Automation.PSCredential ("username#domain.com", $password)
New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Connect-MsolService -Credential $Livecred
$O365Users = Get-MsolUser -All
ForEach ($O365User in $O365Users)
{
$userID = Import-CSV "c:\Export\list.csv"
$ADuser = Get-ADUser -Filter "EmployeeID -eq $($userID.EmployeeID)" -Properties whenCreated, Enabled, SAMAccountName
If (($ADUser.Enabled -eq $True) -and ($O365User.isLicensed = $true))
{
Get-MsolUSer -UserPrincipalName $ADuser.UserPrincipalName
Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"
}
}
CSV file :
EmployeeID
52576
1234
8599
Here you go this should work
$userID = Import-Csv "c:\export\list.csv"
foreach ($user in $userID){
$ADuser = Get-ADUser -Filter "EmployeeId -eq $($user.EmployeeID)" -Properties whenCreated, Enabled, SAMAccountName
$O365User = Get-MsolUser -UserPrincipalName $ADuser.UserPrincipalName
if(($ADuser.Enabled -eq $true) -and ($O365User.isLicensed -eq $true)){
Get-MsolUSer -UserPrincipalName $ADuser.UserPrincipalName
Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"
}
}
Regarding the follow-up question on performance (just what i think might increase performance, no warranty and not tested):
$userID = Import-Csv "c:\export\list.csv"
$adusers = Get-ADUser -Filter * -properties EmployeeID,whenCreated,Enabled,SAMAccountname
$msolusers = Get-MsolUser -All
foreach ($user in $userID){
$ADuser = $adusers | where {$_.EmployeeID -eq $user.EmployeeID}
$O365User = $msolusers | where {$_.UserPrincipalName -eq $ADuser.UserPrincipalName}
if(($ADuser.Enabled -eq $true) -and ($O365User.isLicensed -eq $true)){
Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"
}
}
Depending on how many of the AD / MSOL users there are and you have to match this might de- or increase the execution time, you will have to test since i cant.
I also removed the get-msoluser in your if statement since it´s only function is generating (unnecessary?) output. If there are any problems with my "improvements" let me know and we can see what we can do ;)
Please try:
Import-Module ActiveDirectory
Import-Module MSOnline
$password = ConvertTo-SecureString 'PASSWORD' -AsPlainText -Force
$LiveCred = New-Object System.Management.Automation.PSCredential ("username#domain.com", $password)
New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred -Authentication Basic -AllowRedirection
Connect-MsolService -Credential $Livecred
$userIDs = Import-CSV "c:\Export\list.csv"
$O365Users = Get-MsolUser -All
ForEach ($O365User in $O365Users)
{
foreach ($userID in $userIDs)
{
$ADuser = Get-ADUser -Filter "EmployeeID -eq $($userID.EmployeeID)" -Properties whenCreated, Enabled, SAMAccountName,ObjectGUID
$valuetoconvert=$ADuser.ObjectGUID
$guid = [GUID]$valuetoconvert
$bytearray = $guid.tobytearray()
$ImmutableID = [system.convert]::ToBase64String($bytearray)
If (($ADUser.Enabled -eq $True) -and ($O365User.isLicensed = $true) -and ($ImmutableID -eq $O365User.ImmutableID ) )
{
Get-MsolUSer -UserPrincipalName $ADuser.UserPrincipalName
Set-MsolUserLicense -UserPrincipalName $ADuser.UserPrincipalName -RemoveLicenses "company:ENTERPRISEPACK"
}
}
}

Email Signatures in Office365

I want to build a email signature application . In that these are the main functionalities
a) Display a list of email signature templates
b) Customer will select any one of the template and will modify the text
c) Customer will add that signature to their office365 account by clicking on confirm button
Here my requirement is i want to know how to generate a email signature to the office365 account through API in C# code?
Collection<PSObject> psresult;
using (Runspace myRunSpace = RunspaceFactory.CreateRunspace())
{
myRunSpace.Open();
PowerShell powershell = PowerShell.Create();
powershell.Runspace = myRunSpace;
using (powershell)
{
powershell.AddScript("$Username = 'username'; $Password = ConvertTo-SecureString 'password' -AsPlainText -Force; $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password; $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri 'https://outlook.office365.com/powershell-liveid/' -Credential $cred -Authentication Basic -AllowRedirection; Import-PSSession $Session; Set-Mailboxmessageconfiguration -identity 'user' -signaturehtml 'SignatureInHTML' -autoaddsignature $true ; Remove-PSSession $session");
psresult = powershell.Invoke();
}
powershell = null;
myRunSpace.Close();
}

Resources