WebAdministration module not loading when ran from Scheduled Task - scheduled-tasks

I am running into an issue with a script where a cmdlet from an imported module is not being executed when running from a scheduled task.
I created a basic test script which uses the Stop-Website cmdlet and added a try/catch to trap any errors from the cmdlet.
When I run this code from the ISE or Cmd line it works as expected; Website1 gets stopped.
When I run this from the scheduled task GUI, WebSite1 does not get stopped and the following error is caught by the catch:
The cmdlet error is: Cannot find drive. A drive with the name 'IIS' does not exist.
From what I've read this is just means the cmdlet is not available.
I've confirmed the module is installed.
On the Action tab I'm passing
powershell -ExecutionPolicy ByPass -NoProfile -file "D:\temp\stop_site.ps1"
Import-Module WebAdministration
try {
Stop-Website -Name Website1 -ErrorAction Stop
} catch {
$ErrorMessage = $_.Exception.Message
Write-Host "The cmdlet Error is: $ErrorMessage"
}
I'm looking for any suggestions on how I can get the Stop-Website cmdlet to work when running it from a scheduled task.

I found the issue to the problem. The user account that was launching the task did not have the appropriate user permissions. When I used an account from the Local Admin group it worked.

Related

VMWare PowerCLI Invoke-VMScript

I would like to Invoke a command on a Remote VM using PowerShell with PowerCLI.
Invoke-VMScript -ScriptText "cmd /c calc" -ScriptType Bat -VM $VMName -GuestCredential $Credential -Confirm:$false -ea SilentlyContinue
Sadly everytime when my command get's invoked an Popup appears telling me "A Program running on this computer is trying to display a message" If click manually on that Popup my Script runs fine, but how can I automate this, so that I can use PowerCLI for this.
The goal is to execute a Binary in Interactive Mode, that processes Automated Tasks, when the Script get's invoked by "Invoke-VMScript"
This is an issue with Interactive Services Detection. Your script is trying to run as interactive in Session 0.
The standard workarounds are creating a schedule task and then triggering it. Or invoking psexec.exe to the user session with -i.

WASP Powershell Local Instance from Task Scheduler

I am trying to get a specific restart command to a cmd.exe window at a particular time in the day everyday in order to restart the server it is running.
My Action in Task Scheduler is currently:
Powershell.exe -ExecutionPolicy Bypass -File C:\Rustide\restart.ps1 -verbose >> C:\Rustide\myscript.log 2>&1"
It does not actually create the log, so I do not think that powershell is getting launched. Since I need the command to run and find a window on my profile, it is set to run off my profile. The script works perfectly when I execute it on my own. Is there a reason or security measure that is built in to task scheduler that is not letting me do this? If so, is there a good alternative?
I have tried this with the only when user is logged on, whether user is logged on or not, with highest privileges, etc. Nothing seems to work.
PowerShell Code
Start-Transcript -Path C:\Rustide\restart.log
Import-Module WASP
Select-Window | Where { $_.Title -Like '*OSF*Oxide' } | Set-WindowActive | Send-Keys 'restart'
start-sleep -seconds 2
Log from executing through task scheduler.
**********************
Windows PowerShell transcript start
Start time: 20160725080935
Username: OSF-WS2012\OSF
RunAs User: OSF-WS2012\OSF
Machine: OSF-WS2012 (Microsoft Windows NT 6.3.9600.0)
Host Application: Powershell.exe -ExecutionPolicy Bypass -File C:\Rustide\restart.ps1 Start-Transcript -Path C:\Rustide\restart.log
Process ID: 10588
**********************
Transcript started, output file is C:\Rustide\restart.log
PS>$global:?
True
**********************
Windows PowerShell transcript end
End time: 20160725080937
**********************

How do I troubleshoot Powershell user data scripts on AWS EC2?

I am trying to run a powershell script from the user data box when creating an ec2 instance from a custom AMI. I have enabled user data execution on the config before creating the ami.
This is what i put into user data
<powershell>
c:\scripts\github-download.ps1 someuser somepassword
</powershell>
The script it is calling is shown below.
Param($gituser, $gitpass)
C:\Users\Administrator\AppData\Local\GitHub\shell.ps1
git clone https://"$gituser":"$gitpass"#github.com/somegitrepo |out-null
I have no idea why this isn't working. Am i doing something wrong here? Any help really appreciated.
Instead of calling the user data using the <powsershell> tag, call PowerShell itself using the <script> tag. You gain command line control over its invocation, and can control execution policy and other command line settings directly:
<script>
PowerShell -ExecutionPolicy Bypass -NoProfile -File c:\scripts\github-download.ps1 -user USER -password PASSWORD
</script>
In your script, setup the beginning and end sections of your script as below:
# Server script called from userdata in this format
# <script>
# PowerShell -ExecutionPolicy Bypass -NoProfile -File c:\scripts\github-download.ps1 -user USER -password PASSWORD
# </script>
param (
[string]$user = $(throw "-user is required."),
[string]$password = $(throw "-password is required."),
)
Start-Transcript -Path C:\userscriptlog.txt
Import-Module WebAdministration
if ([System.Diagnostics.EventLog]::SourceExists("Userdata") -eq $False) {
New-Eventlog -Logname Application -Source 'Userdata'
}
Write-Eventlog -Logname Application -Source 'Userdata' -EventId 1 -EntryType Information -Message 'Begining post-deployment configuration script'
-- YOUR MAIN SCRIPT HERE --
Write-Eventlog -Logname Application -Source 'Userdata' -EventId 1 -EntryType Information -Message 'Post-deployment configuration script complete'
Stop-Transcript
For error handling in your script, you need to use robust exception handling and logging for each command, again to make troubleshooting and debugging easy. This block simply gets the current instance ID, but note the exception handling and logging built in:
# get instance-id
try {
$InstanceId = (Invoke-WebRequest http://169.254.169.254/latest/meta-data/instance-id).content
} catch {
$_.Exception.message | out-file c:\InstanceId_error.log
Write-Host "FATAL: InstanceId exception"
Exit
}
if (!$InstanceId) {
Write-Host "FATAL: InstanceId is null"
Exit
} else {
$InstanceId | out-file C:\InstanceId.txt
Write-Host "InstanceId: $InstanceId"
}
Try that approach to any command or shell invocation that you need to implement.
This powershell script 'wrapper' for user data scripts allows optional command line parameters, produces a transcript of execution, and logs events to the Windows event log, to confirm basic execution of the script.
It will provide a flexible framework for any Powershell based user data script, allow for easy debugging and testing.
| out-null silences any errors that could be happening with git clone so you won't know what is wrong unless you pipe the error somewhere else or just don't use | out-null.
I would manually run the command on the EC2 instance without the | out-null before you try and use user data to automate anything.

teamcity powershell - unable to run batch file

I've spent quite a bit of time banging my head on this one. A little StackOverflow help please, good folks!
Scenario: We are trying to run a custom .bat file located on the CI server via the TeamCity Powershell step.
When powershell script is run on local box manually, it kicks off .bat file correctly.
When powershell script is run through TeamCity, it successfully 'sees' the .bat file (validated by receiving a 'cannot find file' response when I rename the .bat file it is expecting)
HOWEVER, we have not seen any indication that the .bat file was actually kicked off.
What we've tried:
We've added the 'RedirectStandardOutput' and 'RedirectStandardError' for attempt to diagnose, but although the log file is created, it is returned blank.
We've granted filepath permissions and tried two different credentials including the credential of the TC build agent
Added "-wait" at one point to see if we needed to 'tell' PS to wait on the .bat file.
Two questions...
What is preventing us from running this .bat file?
How do we diagnose issues like this? ATM it is a 'blackbox' to us.
TeamCity Powershell settings:
Powershell Run Mode: Version 1.0; Bitness x64 (tried x86 as well)
Working Directory: Tried as blank, and specific filepath of .bat file (so, 'D:\folder\folder2\')
Script: Source Code
Script Execution: Execute .ps1 from external file (tried with 'Put script into PowerShell stdin with "-Command -" argument' as well)
Add -NoProfile argument (tried both)
Powershell script:
#Predefine necessary information
$Username = "DOMAIN\username"
$Password = "password"
$ComputerName = "CI Build Server Name"
#Create credential object
$SecurePassWord = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $Username, $SecurePassWord
#Start batch file
Start-Process "testbat.bat" -WorkingDirectory D:\file\path\ -Credential ($Cred)-NoNewWindow -RedirectStandardError stderr.txt -RedirectStandardOutput stdout.txt
Write-Host "Executed powershell."
UPDATE 1: If we remove the '-Credential ($Cred)' portion we are able to kick off the testbat.bat file from TeamCity, as expected. The problem must lie with that "-Credential ($Cred)" argument, somehow. Any thoughts?
UPDATE 2: If we set the '-Credential ($Cred)' portion to the credential of the build agent user we are able to kick off the test.bat file from TeamCity. The problem only occurs when we set the credential to a user other than the one running the build agent. This seems to indicate that credential syntax is fine.
UPDATE 3: Tried running with PowerShell executionpolicy set to 'RemoteSigned' and 'Unrestricted'. Problem persists.
UPDATE 4: Gave the BuildAgent user, and the user of whom we want to run this as, full permissions to powershell via 'Set-PSSessionConfiguration'. Problem persists.
$credential = New-Object System.Management.Automation.PsCredential(".\user", (ConvertTo-SecureString "pass" -AsPlainText -Force))
Start-Process powershell -Credential $credential -ArgumentList '-noprofile -command &{Start-Process D:\file\path\test.bat -NoNewWindow -RedirectStandardError stderr.txt -RedirectStandardOutput stdout.txt }'
note:
first i get credential "user" ur user then convert your pass to plain text
then start-process with your credential set
If agent is running as service under Local System account, then it's not possible to run PowerShell under specified account. The workarounds are:
Run agent via command line.
Try to run agent service under another account (not Local System) with administrator rights, probably it will help.
Try RunAs plugin. It provides an ability to run builds under the specified user account.

Why can't I get the Jenkins Powershell plugin to work?

Why can't I get the Jenkins "Powershell plugin" to work?
I can run a powershell script on Jenkins using a "Execute windows batch command" build step with the following command:
powershell -ExecutionPolicy ByPass -File script.ps1
But I am unable to run a powershell script with the Jenkins "Powershell plugin" using the "Windows Powershell" build step and this command, because of a Windows Execution policy not set error disallowing it to run:
script.ps1
Does anyone know the proper arg to give the Jenkins "Powershell Plugin" for it to succesfully run a script? Otherwise, I will just use the batch script work-around.
The correct thing to do is to set an execution policy on your machine (a one-time action), at which point you won't need to bypass it every time, and the Jenkins plugin should "just work". Are you unable to?
A reasonable starting setting would be RemoteSigned, which will allow you to execute local scripts fine but would still disallow scripts downloaded from the internet.
From an elevated PowerShell prompt, you would run:
Set-ExecutionPolicy RemoteSigned
See also: http://technet.microsoft.com/library/hh849812.aspx
UPDATE: excerpt from Help on applying policy and how it's supposed to behave:
If you set the execution policy for the local computer (the default)
or the current user, the change is saved in the registry and remains
effective until you change it again.
Of course, if your machine is on a Domain, then Group Policy could revert this.
For a reboot-proof solution, put this single line
powershell Set-ExecutionPolicy -Scope CurrentUser RemoteSigned -Force
in a batch file in the All Users Startup folder, which on Windows 7 is C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
(or you can get there by clicking Start -> All Programs, right-click Startup and click Open All Users)
This is how I got Jenkins executing PS scripts on a domain machine subject to Group Policy, without having to involve the sys admin guys ;-)
After experimentation, I realized that since Jenkins is running as a service as the System user, then the powershell scope is different than the scope used by my terminal services login session.
This script works for me and seems to properly set the registry keys so that the setting is persistent across reboots and new logins.
# SetExecutionPolicyToRemoteSigned.ps1
# Need to run this after every server reboot.
Write-Output "Setting local Powershell policy to RemoteSigned"
Write-Output ""
Set-ExecutionPolicy -scope CurrentUser Undefined -Force
#Set-ExecutionPolicy -scope Process Undefined -Force
Set-ExecutionPolicy -scope LocalMachine Undefined -Force
Set-ExecutionPolicy -scope CurrentUser RemoteSigned -Force
#Set-ExecutionPolicy -scope Process RemoteSigned -Force
Set-ExecutionPolicy -scope LocalMachine RemoteSigned -Force
Write-Output "Finished."
Get-ExecutionPolicy -list
Start-Sleep -s 10