Az Copy Scheduled Task Created but not executing script - powershell

I am using a powershell script that will read in a service principal and use it to run azcopy sync:
$StorageAccountName = 'nkstgacct'
$ContainerName = 'netangularproject'
$StorageURL = 'https://' + $StorageAccountName + '.blob.core.windows.net/' + $ContainerName
$LocalPath = <source path>
$TenantID = ''
$AppID = ''
$Password = ''
$env:AZCOPY_SPA_CLIENT_SECRET = $Password
.\azcopy login --service-principal --application-id $AppID --tenant-id $TenantID
.\azcopy sync $LocalPath $StorageURL --recursive=true
From there, I add the script file into a windows scheduled task command to run every 5 min:
schtasks /CREATE /SC minute /MO 5 /TN "AzCopy Script 2" /TR C:\Users\nk\Documents\AzCopy\Windows\azcopyAutomatedTest.ps1
The windows scheduled task gets created but when it runs, it does not actually run the script. I've checked my storage account every-time the task runs and do not see it updated. I've also changed the file to .bat and .exe and have not seen it run as expected.

The reason this wasn't running the script was because I did not include the path to the az copy folder in the script.
so I just added the az copy command path right before the:
$env:AZCOPY_SPA_CLIENT_SECRET = $Password
and it worked.

You have to have 3 things in place.
First you have to execute the script with powershell.exe the default application for opening .ps1 files is notepad:
powershell.exe -file "C:\Users\nk\Documents\AzCopy\Windows\azcopyAutomatedTest.ps1"
Second, you have to set the Execution Policy from the default RemoteSigned to either ByPass or Unrestricted:
powershell.exe -ExecutionPolicy ByPass
e.g.
schtasks /CREATE /SC minute /MO 5 /TN "AzCopy Script 2" /TR 'powershell.exe -ExecutionPolicy ByPass -File "C:\Users\nk\Documents\AzCopy\Windows\azcopyAutomatedTest.ps1"'
Third, when you are running the powershell script as a scheduled job, it starts up in the "C:\Windows\system32" folder (Note: This also happens when you specify the "Start in" directory). So you have to have all your paths be Fully Qualified.

Related

Executing CMD command remotely

I need to execute some commands remotely on computers and receive back input, to prevent calling every user and remote desktop to use CMD.
What I need to do:
Run CMD as admin, and run the two lines below and review the results. (On 30+ computers)
cd "c:\Program Files\Tenable\Nessus Agent"
nessuscli agent status --local
I tried:
wmic /node:COMPUTERNAME process call create "cmd.exe /c start"
It worked on my computer, but I think it opened the command prompt on the other persons computer when I tried this.
winrs -r:COMPUTERNAME CMD
WINRM apparently isn't enabled and I don't want to enable it if it's not already enabled.
$PC = (Read-Host "Enter Computer Name").ToUpper()
$PC cmd.exe --% /k cd "c:\Program Files\Tenable\Nessus Agent" & nessuscli agent status --local
write-host -f WHITE "Operation Complete."
I couldn't figure out how to make it work with a Powershell script in ISE.
I was able to run the below one from Powershell x86 as admin on my computer, but not sure how I would replicate to run it on an external computer.
cmd.exe --% /k cd "c:\Program Files\Tenable\Nessus Agent"
nessuscli agent status
EDIT
I created a .bat file and was able to launch it as admin, but it still requires input from the user to accept the cmd runas admin. Then I cannot see the results of the CMD on my end.
$PC = (Read-Host "Enter Computer Name").ToUpper()
#Change $xWare to your folder
[string]$RemoteStagingPath = '\\' + $PC + '\C$\Intel'
$xWare = "C:\Users\NAME\Desktop\"
$password= convertto-securestring $passwordTextBox.Text -asplaintext –force
$credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $userTextBox.Text,$password
$script = "C:\intel\cmd.bat"
#Runs Nessus
CP $xWare\cmd.bat $RemoteStagingPath
Start-Process powershell -Credential $credential -ArgumentList "-noprofile -command &{Start-Process $script -verb runas}"
write-host -f WHITE "Operation Complete."

How to run a script as a different user while staying in current session

In my current environment I have a local admin and domain account. I have created a powershell script which runs well when logged into my domain admin account. However, I wish to adapt the script to prompt the user for credentials and then run the script if they have permission.
The current script imports AD and presents the user with a menu. I would like to prompt the user for credentials then present them with the menu if correct.
I have tried adding:
start-process powershell.exe -argument C:\Users\Auser\Documents\User Leaver script test.ps1 -credential ""
I know this is not the correct method to verify then run the script and other parameters are needed.
An excerpt from the script is contained in the following:
$Programstop="No" #Used to Loop
Do
{
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Unrestricted -File ""C:\Users\Auser\Documents\User Leaver script test.ps1""' -Verb RunAs}"; #This line runs script as admin automatically, change file path to point at your script.
Import-Module ActiveDirectory
set-location ad:"dc=fakepleace,dc=local"
Write-Host "
$Credentials = Get-Credentials
Start-Process powershell.exe -argument C:\Users\Auser\Documents\User Leaver script test.ps1 -credential $Credentials -Verb RunAs

Elevated PS script in Jenkins

I have been trying to run a script from a Windows Jenkins (slave) server. The script is written in PowerShell and requires elevated privileges (such as if one right-clicked on PS and selected run-as-administrator).
Jenkins launches its scripts the following way:
powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\JOHAN.DER\AppData\Local\Temp\2\hudson9084956499652818911.ps1'"
My script fails because it requires elevated privileges. How can I spawn a new elevated-privileged PS process (that does not require clicking because Jenkins can't do that) that could run my script?
Cheers!
The snippet below checks if current process is elevated and if not, it spawns a new, privileged process. It is little tricky to get output of the child powershell process, so I'm using transcript command to capture it. Below you can find my pipeline definition step:
powershell """
cd "${env.WORKSPACE}"
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
echo "* Respawning PowerShell child process with elevated privileges"
\$pinfo = New-Object System.Diagnostics.ProcessStartInfo
\$pinfo.FileName = "powershell"
\$pinfo.Arguments = "& '" + \$myinvocation.mycommand.definition + "'"
\$pinfo.Verb = "RunAs"
\$pinfo.RedirectStandardError = \$false
\$pinfo.RedirectStandardOutput = \$false
\$pinfo.UseShellExecute = \$true
\$p = New-Object System.Diagnostics.Process
\$p.StartInfo = \$pinfo
\$p.Start() | Out-Null
\$p.WaitForExit()
echo "* Child process finished"
type "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
Remove-Item "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
Exit \$p.ExitCode
} Else {
echo "Child process starting with admin privileges"
Start-Transcript -Path "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
}
# put rest of your script here, it will get executed
# with elevated privileges.
"""
Even though this is an old thread, I still provide my methods here since I had the same problem, hoping to help anyone who is finding the answer.
First of all, This problem is not relevant to Jenkins, it's Windows's issue, you have to enable build-in Administrator to get an elevated privilege, here is the reference:
Administrator user
It is an unelevated administrator account
that is created by default during the installation of Windows. If an
administrator user tries to do something that requires elevated rights
(ex: run as administrator), Windows will display a UAC prompt for the
administrator user to approve before allowing the action.
Built-in "Administrator"
The hidden built-in elevated
"Administrator account" is a local account that has full
unrestricted access rights to the PC. By default, this "Administrator"
account will not be prompted by UAC.
After enabling build-in Administrator, you have two ways to elevate PS script which is triggered by Jenkins:
1.Login Windows with build-in Administrator:
This is the easiest way to achieve your goal, just log in with build-in Administrator, and everything are elevated, including the PS script triggered by Jenkins. (I am using this method.)
2.Pass credential and run as Administrator:
Add some codes in your PS script
$user = "Administrator"
$passwd = "password"
$securePasswd = ConvertTo-SecureString $passwd -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $user, $securePasswd
#Use Credential to prevent from being prompted for password
#Use argument -Verb RunAs to get script elevated
Start-Process powershell.exe -Credential $credential -ArgumentList "Start-Process powershell.exe -Verb RunAs -ArgumentList '-File hudson.ps1' -Wait"
Try this :
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

How do I execute a PowerShell script automatically using Windows task scheduler?

I have one PowerShell script which sends emails. I want to execute that script automatically, every 1 minute. How can I do it, using task scheduler?
Currently I have created a task and provided the path of my script. But that scheduler opens my script, instead of executing.
I am using Windows 7 Professional and PowerShell version 2.0.5.
Create the scheduled task and set the action to:
Program/Script: Powershell.exe
Arguments: -File "C:\Users\MyUser\Documents\ThisisMyFile.ps1"
Here is an example using PowerShell 3.0 or 4.0 for -RepeatIndefinitely and up:
# Trigger
$middayTrigger = New-JobTrigger -Daily -At "12:40 AM"
$midNightTrigger = New-JobTrigger -Daily -At "12:00 PM"
$atStartupeveryFiveMinutesTrigger = New-JobTrigger -once -At $(get-date) -RepetitionInterval $([timespan]::FromMinutes("1")) -RepeatIndefinitely
# Options
$option1 = New-ScheduledJobOption –StartIfIdle
$scriptPath1 = 'C:\Path and file name 1.PS1'
$scriptPath2 = "C:\Path and file name 2.PS1"
Register-ScheduledJob -Name ResetProdCache -FilePath $scriptPath1 -Trigger $middayTrigger,$midNightTrigger -ScheduledJobOption $option1
Register-ScheduledJob -Name TestProdPing -FilePath $scriptPath2 -Trigger $atStartupeveryFiveMinutesTrigger
Instead of only using the path to your script in the task scheduler, you should start PowerShell with your script in the task scheduler, e.g.
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NonInteractive -File "C:\Path\To\Your\PS1File.ps1"
See powershell /? for an explanation of those switches.
If you still get problems you should read this question.
In my case, my script has parameters, so I set:
Arguments: -Command "& C:\scripts\myscript.ps1 myParam1 myParam2"
After several hours of test and research over the Internet, I've finally found how to start my PowerShell script with task scheduler, thanks to the
video Scheduling a PowerShell Script using Windows Task Scheduler by Jack Fruh #sharepointjack.
Program/script -> put full path through powershell.exe
C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe
Add arguments -> Full path to the script, and the script, without any " ".
Start in (optional) -> The directory where your script resides, without any " ".
You can use the Unblock-File cmdlet to unblock the execution of this specific script. This prevents you doing any permanent policy changes which you may not want due to security concerns.
Unblock-File path_to_your_script
Source: Unblock-File
None of posted solutions worked for me.
Workaround, which worked:
create a run.bat and put inside
powershell.exe -file "C:\...\script.ps1"
then set Action to Program/Script: "C:\...\run.bat"

Windows schedules task creation issue with powershell

I'm trying to script windows scheduled task creation with powershell, where the schedules tasks call powershell scripts that are in a directory that contains a space. So i need to create with a /tr argument like powershell.exe -noninteractive -command "& 'c:\temp\program files\a.ps1'"
Here is a sample of what i have tried
# Create the script file the schedule task will call, note path contains a space
'set-content c:\temp\program files\a.log "Just done # $(get-date)"' > 'c:\temp\program files\a.ps1'
$scriptFilePath = 'c:\temp\program files\a.ps1';
$userName = read-host 'user name'; # will need log on as batch rights
$userPassword = read-host 'user password';
# The following looks good but schtasks args gets messed up so no creation
$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -command `"& '$scriptFilePath'`"";
$taskToRun
schtasks /create /tn 'ATest' /ru $userName /rp $userPassword /sc MINUTE /mo 1 /st '00:00' /f /tr $taskToRun;
# Gets imported but mangles the tr so instead of
$taskToRun = 'c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -command \"& ''' + $scriptFilePath + '''\"';
$taskToRun
schtasks /create /tn 'ATest' /ru $userName /rp $userPassword /sc MINUTE /mo 1 /st '00:00' /f /tr $taskToRun;
If anyone knows how to escape correctly, i would appreciate a hint
Thanks in advance
Pat
I'd trade the -command option for -file:
$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -file ""$scriptFilePath"""
Also, the PowershellPack has a TaskScheduler module that's makes task scheduling much easier:
http://archive.msdn.microsoft.com/PowerShellPack
[UPDATE] Thanks
Perfect, just needed to escape with a single quote rather than double quote
$taskToRun = "c:\windows\system32\windowspowershell\v1.0\powershell.exe -noninteractive -file '$scriptFilePath'";