never ending Powershell script when executed from SQL Server Agent - powershell

My PowerShell script is unable to create a PS-Session when executed through SQL Server Agent Job,
On the other hand when I tried to execute the script from powershell editor it is running fine.
I tried to catch output into a text file which shows script is executing fine until-------
echo "Credentials received" >> C:\Users\username\Desktop\ABC.txt
#Set Execution policy for the first run
#Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
#This is better for scheduled jobs
$User = "xyz#abc.com"
$pass = "0100skdhfsdhlfsj7eb0100000044afdcf1458d41449af94347f8d9d962000012464664603660000c000000010000000cb11e38eb73dd5d612111f4461d953e90000000004800000a00000001000000085512ba758402a4c5f4504af6f407ba3180000003bf98f386b5341815358f54166f931802814a6154f86daf8140000009a3c5af0588baa420ed836dc0ac1d1f4d0fb4649"
$PWord = ConvertTo-SecureString -string $pass
$UserCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
echo "Credentials received" >> C:\Users\username\Desktop\ABC.txt
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
echo "Session" >> C:\Users\username\Desktop\ABC.txt
Import-PSSession $Session -AllowClobber
echo "Session set up" >> C:\Users\username\Desktop\ABC.txt
Remove-PSSession -Id $Session.Id
exit
When I run the same piece of code from powershell editor, it is getting executed correctly.
I am the expecting same behavior when it is scheduled from SQL Agent.

As encryption is user specific we should create a proxy account at sql agent jobs for a user with whom password is encrypted. And then run the job with particular proxy. It works.
Encryption Technique used:
$password = read-host -prompt "Enter Password"
write-host "$password is: "
$secure = ConvertTo-SecureString $password -force -asPlainText
$bytes = ConvertFrom-SecureString $secure
#Encrypted Password
echo $bytes
Note:- enter code here Above mentioned technique is user and system specific.
Please encrypt the password on the same machine from where you will be running the script in which you will be using the password.

Related

How to run PS1 file on a Server 2016 from a remote computer?

i wrote a script for Exchange Management Shell. i've saved the script on the server.
my question is: how can i run the script from a remote windows 10 Computer?
*regarding to server authentiication - it's O.K for me to write my server Credentials on the script
i've try this script, but it's asking for user and password every time and cannot exeute the file.
$UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mailserver/PowerShell/ -Authentication Kerberos -Credential $UserCredential
Import-PSSession $Session
Invoke-Command -ComputerName mailserver -FilePath \\mailserver\c$\Script\MPC3.ps1
EDIT:
i want to be able to open the following PS on my Windows computer:
Thanks for helping me !
I do not recommend to store credentials inside a script. But here a way of doing it:
$Username = 'username'
$Password = 'passwd' | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object -TypeName 'System.Management.Automation.PSCredential' -ArgumentList $Username, $Password

Running powershell script fails on windows server salve

I have the below code which runs from Jenkins on windows server 2019 slave:
$Username = $args[0]
$Password = $args[1]
$Env = $args[2]
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
echo "******** Start SQL Deploy ********"
Start-Process -FilePath msbuild -ArgumentList '"Database Services\Database Services.sqlproj"','/t:deploy', '/p:Configuration=Release', '/p:TargetConnectionString=$Env', '/p:BlockOnPossibleDataLoss=True', '/p:TargetDatabase="test_fsdb"','-fl','-flp:logfile=msbuild.log' -wait -LoadUserProfile -credential $cred
Get-Content msbuild.log
echo "******** End SQL Deploy ********"
The parameters comes form Jenkinsfile. I'm using applicative user.
The error is:
Start-Process : This command cannot be run due to the error: The service cannot be started, either because it is
disabled or because it has no enabled devices associated with it.
I was able to run it locally, so I wonder if it's kind of permission issue on the salve...

Jenkins Deployment - Powershell SCP Script

Good evening,
I'm trying to write a Powershell script that will connect to a remote server via SCP and upload or download files/folders. Ultimately this is the script that I would like Jenkins to run.
So far I'm using Posh-SSH and having good success. The only issue is, no matter what I have tried so far, it will always prompt me for my credentials. This, obviously, makes it not entirely automatic.
I have attached a few things I've tried. Hopefully someone can help me out with this!
The basic command I'm testing with:
get-scpfolder -computername '111.111.111.111' -credential $credential
-remotefile "/var/myFolder" -localfile 'C:\Users\Me\destFolder'
Again, this works, but it requires me to enter my credentials.
I saw this command online:
$Password = "pass"
$User = "admin"
$ComputerName = "111.111.111.111"
$Command = "get-scpfolder -computername $ComputerName -credential $Credentials -localfolder 'C:\Users\Me' -remotefolder '/var/destFolder"
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)
$SessionID = New-SSHSession -ComputerName $ComputerName -Credential $Credentials #Connect Over SSH
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command # Invoke Command Over SSH
However this returns ExitStatus 1 and nothing happens. I have tried a few variations of the $Command including the credentials or not, for example, and I can't get any of it to work.

PowerShell Computer StartUp-Script - Switch user-context?

Through Microsoft Group Policy I did define to run a Powershell-Script on Computer Start-Up. Also I have the requirement to run a Powershell-Script as Scheduled Task without saving credentials.
On both scenarios I have the same problem ...
I want to run a Citrix Powershell-Command (PSSnapIn) like:
Set-BrokerMachine -MachineName "domain.local\$env:COMPUTERNAME" -AdminAddress "RemoteServer.domain.local" -InMaintenanceMode $True
Manual: https://citrix.github.io/delivery-controller-sdk/Broker/Set-BrokerMachine/
Of course only users who have the permission could run those Citrix-commands. I would be able to give a domain-user the permission to run the command "Set-BrokerMachine", but in the mentioned scenarios the PowerShell-scripts run in context of the system-user.
I did simulate the system-user by PSExec:
Error running as System-User
My scripts do other things of course and I want to keep them running as System-User, but now I am looking for a clean solution to get those Citrix-commands running.
If possible, I don't want to save credentials in my scripts.
EDIT #1:
I would be able to workaround with the following code:
$Username = "MySpecialUser"
$Password = 'MyPassword'
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePassword
$Result = Invoke-Command -Session ( New-PSSession -ComputerName "RemoteServer.domain.local" -Credential $Credential ) -ScriptBlock {
Add-PSSnapin Citrix*
Set-BrokerMachine -MachineName "domain.local\$args" -InMaintenanceMode $True
} -ArgumentList $env:COMPUTERNAME -HideComputerName
Remove-PSSession -InstanceId $Result.RunspaceId
I don't like this because:
The code has to contain credentials (ofc I could encrypt it ...)
I have to create a permission-system for this special user in Citrix
I have to put the special-user into a local-group on every server, to allow the remote-administration (security-risk)
I don't like to use PSSession
...
Is there a better/cleaner solution? Any ideas?

Need to connect to remote server and execute ps1 script using jenkins

I created a Jenkins job that needs to connect to a remote machine and execute a ps1 script.
$pw = convertto-securestring -AsPlainText -Force -String "4444"
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "eeeee\eee",$pw
$sess = New-PSSession -ComputerName server1 -Credential $cred
Enter-PSSession $sess
Looks like you may be better served with Invoke-Command than Enter-PSSession.
https://technet.microsoft.com/en-us/library/hh849719.aspx
Something along the lines of:
Invoke-Command -Credential $creds -ComputerName $server -FilePath $scriptname -ArgumentList $arg1, $arg2
Add the remote machine as a slave, then run your script from 'execute windows Batch command' or install Powershell plugin and 'Run powershell script'.
Links:
Add windows slave: https://wiki.jenkins.io/display/JENKINS/Step+by+step+guide+to+set+up+master+and+agent+machines+on+Windows
Powershell plugin: https://wiki.jenkins-ci.org/display/JENKINS/PowerShell+Plugin