Powershell script not executed on windows instance launched by AWS Autoscaling - powershell

I have a script scheduled in task scheduler and triggered at "System Startup".
The script does the following:
adds a remote machine to domain,
move it to specific organizational unit,
add it to group,
then add it to elastic load balancer
and restart the computer.
I want the instances launched by autoscaling to execute this script at system start up and get configured automatically as specified above.
This script executed on all test machines but the execution failed on instances launched by Auto Scaling. When i stopped the same machine and restarted it, the script executed.
Here is my script:
if ((gwmi win32_computersystem).partofdomain -eq $true) {
}
Else{
$name=gc env:computername
$secpasswd = ConvertTo-SecureString "Password" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential("abc\user",$secpasswd)
Add-Computer -DomainName abc.com -OUPath "OU=POC,DC=abc,DC=com" -Credential $mycreds -force
add-adgroupmember -id POCGroup -members "CN=$name,OU=POC,DC=abc,DC=com" -Credential $mycreds
Set-AWSCredentials -AccessKey ************* -SecretKey ***************
$id=(New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")
Register-ELBInstanceWithLoadBalancer -LoadBalancerName "loadbalancer" -Instances "$id" | out-file elbInstance.txt
Restart-Computer
}
i don't think that there is anything to do with the script as it worked when i manually stopped and started the machine in AWS.
Please guide me. Am i missing something?
I searched but could not find anything similar to this.
Any help will be greatly appreciated.
Thanks in advance!

Given that you have specified that you are confident about the Script. The chances are the problem is with the AMI - while you create the AMI; you need to explicitly enable the "User Data Execution" - in EC2 Config Service.
Detailed information of how to do is here in this link - http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/UsingConfig_WinAMI.html

Related

Is it possible to host an "always running" powershell remoting process?

I'm researching whether it's possible to host an always-running Powershell remoting process.
By default, PSRemoting will start a process as the authenticated user.
However, using custom PS Session Configurations, it's possible to set a "run as account" that will ensure that the remote process (on the server, so to speak) always runs as a "known" user, regardless of the identify of the connecting client.
The reason for me researching this, is that I notice that Ansible runs quite slowly against windows servers, and I suspect this is due to the fact that the remoting process on the server gets spun up with each command Ansible sends. I'd like to see if it's possible to have an always-running process that is "ready" in order to speed up executions.
This is as far as I've gotten:
$ansiblecred = get-credential
New-PSSessionConfigurationFile `
-path "C:\sessionconfig.pssc" -SessionType Default `
-RequiredGroups #{ And = 'Administrators' }
Unregister-PSSessionConfiguration -Name ansible -force
Register-PSSessionConfiguration `
-Path "C:\sessionconfig.pssc" -Name ansible `
-RunAsCredential $ansiblecred -AccessMode Remote `
-UseSharedProcess -ThreadOptions ReuseThread
restart-service winrm
$remotecred = Get-Credential
$i = 0
while ($i -lt 10)
{
#This is slow because the remoting session is setup/teard down every time
Invoke-Command -ComputerName "localhost" -Credential $remotecred -Authentication Basic -ScriptBlock {$env:computername} -ConfigurationName ansible
$i ++
}
Even tho I'm connecting to the session with a different credential, the actual process runs as the "service" credential, so that part's good.
However, it seems to be still spinning up and down the process on each execution.
Just for clarification: The client here is not regular Powershell, it's client which will interact directly with the wsman service over http. So while I appreciate all responses, suggestions based around client-side Powershell code (such as new-pssession, invoke-command etc) are not gonna help :-|
Any pointers would be appreciated here, I'm trying to get to a place where the remoting process simply lives regardless of sessions being executed or not. Is this possible?
Create a session outside and use it in the loop.
$Session = New-PSSession -ComputerName $Server -ConfigurationName MyConfiguration
While(1){
Invoke-Command -Session $Session -Credential $remotecred -Authentication Basic -ScriptBlock {'my code'}
sleep 10
}

Start-job results in "The background process reported an error with the following message: ."

I have a simple Powershell script (that's being run in a step in Octopus deploy) that I'm trying to run as another user. We need it for future steps (each application on our platform runs as its own user account, and I need to be able to run an arbitrary script as that user during the deployment process).
The problem is that even the simplest script fails with completely unhelpful error messages, such as this:
$secpasswd = ConvertTo-SecureString $OctopusParameters["runAsPassword"] -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($OctopusParameters["runAsUsername"] , $secpasswd)
$job = Start-Job -scriptblock {
whoami
} -credential $credential
$job | Receive-Job -Wait
Which fails with the message:
The background process reported an error with the following message: .
The Octopus tentacle is running as a domain account with admin privileges on the machine.
I've completely exhausted all avenues of investigation now, but we really need to get this working. I think if we can't run a deployment script as a certain user then we're completely screwed.
Nearly three years later I have the same issue... I tried writing the code to a temporary file and using Start-Process, but couldn't get that to work either.
In the end, I wrote the code to file, and then ran it through the Windows task scheduler.

How can I successfully run my script with administrator permissions?

I've been working on a small, redeployable .ps1 script that will be used to automate the clearing of the end user's print spooler and clearing of the printing queue, with more features in future implementation. Here's a snippet of some of the commands that require elevation.
net stop spooler
Remove-Item C:\Windows\System32\spool\PRINTERS\* -Force
net start spooler
In order to successfully run this script on end user's computers, I've created a Powershell credential object like so. (It doesn't matter if the administrator credentials are in clear text, since it is executed in the background over RMM).
$password = "adminpassword" | ConvertTo-SecureString -asPlainText -Force
$username = "adminusername"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
However, when I try to run any command with the newly made variable like this,
net stop spooler -credential $credential
I get some sort of complication, such as the PS window only returning the syntax of the command instead of actually running it. I'm relatively inexperienced in the Powershell automation; If someone could offer up a solution as to how to best integrate the newly made credential object into my script so that it will run with elevated permissions in its entirety, It'd be much appreciated.
net stop is not a PowerShell command and won't take a credential object.
Here is an example of how to do this if you are running locally elevated:
stop-service -Name spooler

Powershell 5.0 Invoke-Command Start Service with Credential

We have a problem with a Service on a Server. So we decided to write a PS-Script that a "normal" User without Admin privileges can start this Service. I have practiced now 2 Day's on this little Script. I'm a newbie (Apprentice) in PS but im glad that it works when I run it as an Admin. But why the heck not as an User?
I have generated the "Secure" Password as follow:
"P#ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Temp\Password.txt"
I took the SecureString and pasted it in my Script that looks like this:
$User = "DOMAIN\USER"
$PwHash = "01000000d08c9ddf0....."
$MyCredential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, ($PWHash | ConvertTo-SecureString)
Invoke-Command -ComputerName "MyServer" -ScriptBlock {Get-Service -Name "MyService" | Set-Service -Status Running} -Credential ($MyCredential)
The failure pops up by the $MyCredential row:
ConvertTo-SecureString: Key in specific Status is not valid.
I have nowhere read that for an ConvertTo... cmd are Admin rights needed.
Enable-PSRemoting is active on the specific Server.
Thanks for your time and engagement
Dirty.Stone
IMHO, you're going about this all wrong. This is an example of the kind of task you would use JEA (Just Enough Admin) for. Create a constrained, delegated session on the target server, configured with a function for starting or restarting that service and running under a local account that has permission to control the service, and then grant the non-admin users permission to use that session.

How do I execute a powershell script under a specified credential without a prompt?

I'm writing an 'Action Script' in VMWare AppDirector 'AppD' which installs MS Dynamics. (My action script is actually a powershell script). The way this works is that AppD will execute a powershell script on a newly deployed server, using a builtin administrator account. This script is one of the last steps in a highly orchestrated deployment. At this stage my SQL server has been deployed, the databases loaded, and I'm performing the final deployment.
When I run my script logged in as myself, everything works great. But of course that's executing under 'mydomain\myusername' which has access to the SQL server etc. However, when AppD executes this script under a local builtin account, it doesn't have the credentials needed by setup to authenticate against SQL, and make proper connections for install to succeed.
My first attempt was to just call a script, that invokes my actual deployment script, so I can pass credentials;
$user = "mydomain\myusername"
$pword = ConvertTo-SecureString -String "mypassword" -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $pword
Invoke-Command -FilePath "C:\Scripts\DeployAOS.ps1" -Credential $credential -Computer localhost
This looked like it might have worked, but when reviewing the install log I see the following error;
2015-03-09 13:15:19Z Property DbSqlServer set to: 'SQLSERVER001'
2015-03-09 13:15:23Z Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
My original DeployAOS.ps1 script contains this line, which kicks off the install;
# Perform AOS Installation
Start-Process -FilePath $exeAOSSetup -ArgumentList $cfgAOS -Wait
I have also tried just modifying my DeployAOS.ps1 to set the 'System.Management.Automation.PSCredential' object w\ Username\Password, and doing something like this;
# Perform AOS Installation
Start-Process -FilePath $exeAOSSetup -ArgumentList $cfgAOS -Credential $credentials -Wait
And it really didn't like that. It feels like the AOS setup needs to be executed under a domain user, that has access to the SQL server, and maybe even have a user profile loaded while setup runs (So it can create a desktop shortcut, etc.)
Any ideas how I might go about solving this problem? I'm fairly new to scripting in powershell, so any help would be appreciated.