Delaying a schedule task - windows

I have a schedule task i.e mytask on 50of my computers(windows) and i am working on writing a batch file to delay the task by 2 min on all 50 computers, is this the right way to go about it ? I come across this on microsoft website.
schtasks /Change
[/S system [/U system [/P [password]]]] /TN taskname
{ [/RU runasuser] [/RP runaspassword] [/TR taskrun] [/ST starttime]
[/RI interval] [ {/ET endtime | /DU duration} [/K] ]
[/SD startdate] [/ED enddate] [/ENABLE | /DISABLE] [/IT] [/Z] }

You can use Powershell jobs in combination with PowerShell remoting. Some pseudo code:
$session = New-PSSession -Computer "yourComputerNameOrIp" -Credential (Get-Credential)
Invoke-Command -Session $session -Scriptblock { Write-Host "$($env:COMPUTERNAME)"
Here you'll also find a description of how to enable Powershell remoting.
Hope that helps.

Related

Run Cleanmgr on remote PC as System user

So i'm trying to run CleanMgr via powershell on a remote computer. Since CleanMgr has a GUI Powershell cannot run it directly, as described here
If you do this then CleanMgr will hang forever waiting for user input. So this means we have to approach this differently.
I tried several approaches, see below. But non of them works like i would. It still hangs OR runs attached from powershell giving no feedback when done.
Simply put i want to run (remotely) CleanMgr on our Office PC's from my PC (Domain Admin).
Invoke-Command -ComputerName $ComputerOBJ -ScriptBlock {
# Create registry values
Write-Host "Setup keys..."
$volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
foreach ($key in $volumeCaches) {
Set-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0333 -Value 2
}
# Execute Disk Cleanup Tool (cleanmgr.exe)
#Write-Host 'Starting CleanMgr.exe...'
Attempt 1:
Start-Process -FilePath "CleanMgr.exe" -ArgumentList '/sagerun:333' -NoNewWindow
Attempt 2:
Start-Process -FilePath "CleanMgr.exe" -ArgumentList '/sagerun:333' -WindowStyle Hidden
Attempt 3:
Invoke-WmiMethod -Class Win32_Process -Name "Create" -ArgumentList 'CleanMgr.exe /sagerun:333'
Attempt 4:
C:\temp\PsExec.exe \\$ComputerOBJ CleanMgr.exe /sagerun:333
Attempt 5:
$A = New-ScheduledTaskAction -Execute "cleanmgr.exe" -Argument '/sagerun:333'
$T = New-ScheduledTaskTrigger -Once -At (get-date).AddSeconds(1); $t.EndBoundary = (get-date).AddSeconds(60).ToString('s')
$S = New-ScheduledTaskSettingsSet -StartWhenAvailable -DeleteExpiredTaskAfter 00:00:30
Register-ScheduledTask -Force -user SYSTEM -TaskName "Run CleanMgr" -Action $A -Trigger $T -Settings $S
#Wait until Clean is done.
Write-Host 'Waiting for CleanMgr and DismHost processes to complete...'
Get-Process -Name cleanmgr, dismhost -ErrorAction SilentlyContinue | Wait-Process
# Remove the previously created registry values
Write-Host "Cleanmgr completed, now deleting keys"
$volumeCaches = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches"
foreach ($key in $volumeCaches) {
Remove-ItemProperty -Path "$($key.PSPath)" -Name StateFlags0333 -Force
}
}

How can i see all users who have logged in to my computer (and when recently?) Via cmd command and by registry

I would love to get help on how can I see all users who have logged in to my computer (and when recently?) Via cmd command and by registry.
If you are on a supported Windows system, PowerShell is available. Using it to see logged in users on another computer will require that PowerShell Remoting be competently configred.
=== Get-LoggedOnUsers.ps1
[CmdletBinding()]
param (
[Parameter(Mandatory=$false,ValueFromPipeline=$True)]
[string[]]$ComputerName = [System.Net.Dns]::GetHostName()
)
foreach ($Computer in $ComputerName) {
((Get-CimInstance -ClassName Win32_LoggedOnUser -ComputerName $Computer).Antecedent |
Sort-Object -Unique) |
ForEach-Object { "$($_.domain)\$($_.name)" }
}
Run it with:
powershell -NoLogo -NoProfile -File ".\Get-LoggedOnUsers.ps1"

Register-ScheduledJob as the system account (without having to pass in credentials)

I believe for Register-ScheduledTask you can specify -User "System"or do something like:
$principal = New-ScheduledTaskPrincipal -UserId SYSTEM -LogonType ServiceAccount -RunLevel Highest
How do I do this with Register-ScheduledJob?
This command will be running the context of the local admin so it will have access to do this. I just don't see this option in the cmdlet.
Here is an example of how to do this with the scheduled tasks cmdlet
edit: Does windows make this impossible by design? If I open an interactive PS session as the system (using psexec) and try to create a schedualed job I get an error:
PS C:\Windows\system32> Register-ScheduledJob -Name systemsssss -ScriptBlock {'s
dfsdfsdfsd'}
Register-ScheduledJob : An error occurred while registering scheduled job
definition systemsssss to the Windows Task Scheduler. The Task Scheduler
error is: (32,4):UserId:.
At line:1 char:1
+ Register-ScheduledJob -Name systemsssss -ScriptBlock {'sdfsdfsdfsd'}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Power...edJobDefini
tion:ScheduledJobDefinition) [Register-ScheduledJob], ScheduledJobExceptio
n
+ FullyQualifiedErrorId : CantRegisterScheduledJobDefinition,Microsoft.Pow
erShell.ScheduledJob.RegisterScheduledJobCommand
This same command works fine when run as the local administrator account
First use Register-ScheduledJob to create your PowerShell job.
Then use Set-ScheduledTask to change a startup account to the Local System or any other built-in accounts, i.e. SYSTEM, LOCAL SERVICE, NETWORK SERVICE, etc.
Use the following PS-script. Or download it from my GitHub Gist
The code is self-explanatory (I believe).
You can run it multiple times under an administrative account if you want to check how it works.
BTW, I prefer to use jobs (Register-ScheduledJob) over tasks because jobs allow me to embed PowerShell script blocks (strings) instead using of external script files. Look at -ScriptBlock below.
Also pay attention to -RunElevated. It is a must be.
$ErrorActionPreference = 'Stop'
Clear-Host
#### Start of Main Logic ###########################
$taskName = "my_PowerShell_job"
$accountId = "NT AUTHORITY\SYSTEM";
#$accountId = "NT AUTHORITY\LOCAL SERVICE";
$task = Get-ScheduledJob -Name $taskName -ErrorAction SilentlyContinue
if ($task -ne $null)
{
Unregister-ScheduledJob $task -Confirm:$false
Write-Host " # The old ""$taskName"" PowerShell job has been unregistered"; Write-Host;
}
# Uncomment the following exit command to only delete your job.
# exit;
# Shchedule your job. Using of -AtStartup as an example.
$trigger = New-JobTrigger -AtStartup;
$options = New-ScheduledJobOption -StartIfOnBattery -RunElevated;
Write-Host " # Registering of ""$taskName"" job";
Register-ScheduledJob -Name $taskName -Trigger $trigger -ScheduledJobOption $options `
-ScriptBlock {
# Put your code here.
Write-Host Your job has been launched!;
}
$principal = New-ScheduledTaskPrincipal -UserID $accountId `
-LogonType ServiceAccount -RunLevel Highest;
$psJobsPathInScheduler = "\Microsoft\Windows\PowerShell\ScheduledJobs";
$someResult = Set-ScheduledTask -TaskPath $psJobsPathInScheduler `
-TaskName $taskName -Principal $principal
#### End of Main Logic ###########################
Write-Host;
Write-Host " # Let's look at running account of ""$taskName"" PowerShell job"
$task = Get-ScheduledTask -TaskName $taskName
$task.Principal
Write-Host " # Let's start ""$taskName"" manually"
Start-Job -DefinitionName $taskName | Format-Table
Write-Host " # Let's proof that ""$taskName"" PowerShell job has been launched"; Write-Host;
Start-Sleep -Seconds 3
Receive-Job -Name $taskName
Write-Host;
Sadly you can't run schedule a job or task as the system account.
But you can create local administrator accounts as the system account.
And you can schedule jobs or tasks as a local administrator account.
So what I did to get around this problem is this:
$password = ConvertTo-SecureString (New-Guid).Guid -AsPlainText -Force
$user = New-LocalUser "service.scheduler" -Password $Password -Description "For scheduling in tasks from system account"
$credentials = New-Object System.Management.Automation.PSCredential($user.name, $password)
Register-ScheduledJob -Trigger $trigger -ScriptBlock $scriptblock -Name $taskName -ScheduledJobOption $options -credential $credentials
This does mean you are passing in credentials, but you don't have to store them as plain text or specify them.
Sorry, can't make comments with reputation under 50.
Can you use Group Policy to run it as a start up script? That will run as the Local System account. Doesn't look like this cmdlet has the -verb paramater to runas.
Looking at: https://technet.microsoft.com/en-us/library/hh849755.aspx under -ScheduledJobOption there is a setting in there RunElevated=$False, that is the defualt. If you set that to true does it run as admin?
I haven't tried it, it might work.
Hope this helps.
Thanks, Tim.

What is the switch in Windows schtasks for ExecutionTimeLimit in the xml file?

Windows schtasks.exe:
What is the equivalent command line switch for ExecutionTimeLimit in schtasks. In the Edit Tasks dialog it is "Stop tasks if it runs longer than".
I tried /ET end time and /DU duration but they imply a repetition. I only want a task to run once and then be killed x minutes later.
Not a perfect solution , but you can use /XML option of schtasks
schtasks /Create /tn jobname /XML Path_of_xml
Within the xml file you should able to use ExecutionTimeLimit to specify the time you want to kill the job .
You can get sample xml by export a exist job to get reference
schtasks /Query /tn jobname /XML > Path_of_xml
Using the Powershell it is possible to create a task where you can modify ExecutionTimeLimit to your value.
$MyPathToFile = 'C:\Path\File.exe'
$hour = '20:00:00'
$user = 'MyDomain\MyUserName'
$password = '123321Password'
$MyTask = 'MyTask'
$MyExecutionTimeLimit = '01:00:00' # HH:MM:SS
$trigger = New-ScheduledTaskTrigger -Daily -At $hour
$action = New-ScheduledTaskAction -Execute $MyPathToFile
$settingsSet = New-ScheduledTaskSettingsSet -ExecutionTimeLimit $MyExecutionTimeLimit
$task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settingsSet
Register-ScheduledTask -TaskName $MyTask -InputObject $task -User $user -Password $password

Powershell script to change service account

Does anyone have a Powershell script to change the credentials used by a Windows service?
Bit easier - use WMI.
$service = gwmi win32_service -computer [computername] -filter "name='whatever'"
$service.change($null,$null,$null,$null,$null,$null,$null,"P#ssw0rd")
Change the service name appropriately in the filter; set the remote computer name appropriately.
I wrote a function for PowerShell that changes the username, password, and restarts a service on a remote computer (you can use localhost if you want to change the local server). I've used this for monthly service account password resets on hundreds of servers.
You can find a copy of the original at http://www.send4help.net/change-remote-windows-service-credentials-password-powershel-495
It also waits until the service is fully stopped to try to start it again, unlike one of the other answers.
Function Set-ServiceAcctCreds([string]$strCompName,[string]$strServiceName,[string]$newAcct,[string]$newPass){
$filter = 'Name=' + "'" + $strServiceName + "'" + ''
$service = Get-WMIObject -ComputerName $strCompName -namespace "root\cimv2" -class Win32_Service -Filter $filter
$service.Change($null,$null,$null,$null,$null,$null,$newAcct,$newPass)
$service.StopService()
while ($service.Started){
sleep 2
$service = Get-WMIObject -ComputerName $strCompName -namespace "root\cimv2" -class Win32_Service -Filter $filter
}
$service.StartService()
}
The PowerShell 6 version of Set-Service now has the -Credential parameter.
Here is an example:
$creds = Get-Credential
Set-Service -DisplayName "Remote Registry" -Credential $creds
At this point, it is only available via download via GitHub.
Enjoy!
I created a text file "changeserviceaccount.ps1" containing the following script:
$account="domain\user"
$password="passsword"
$service="name='servicename'"
$svc=gwmi win32_service -filter $service
$svc.StopService()
$svc.change($null,$null,$null,$null,$null,$null,$account,$password,$null,$null,$null)
$svc.StartService()
I used this as part of by post-build command line during the development of a windows service:
Visual Studio: Project properties\Build Events
Pre-build event command line:
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil.exe" myservice.exe /u
Post-build event command line:
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil.exe" myservice.exe
powershell -command - < c:\psscripts\changeserviceaccount.ps1
A slight variation on the other scripts here, is below. This one will set credentials for any/all services running under a given login account. It will only attempt to restart the service if it was already running, so that we don't accidentally start a service that was stopped for a reason. The script has to be run from and elevated shell (if the script starts telling you about ReturnValue = 2, you're probably running it un-elevated). Some usage examples are:
all services running as the currently logged in user, on the local host:
.\set-servicecredentials.ps1 -password p#ssw0rd
all services running as user: somedomain\someuser on host somehost.somedomain:
.\set-servicecredentials.ps1 somehost.somedomain somedomain\someuser p#ssw0rd
Set-ServiceCredentials.ps1:
param (
[alias('computer', 'c')]
[string] $computerName = $env:COMPUTERNAME,
[alias('username', 'u')]
[string] $serviceUsername = "$env:USERDOMAIN\$env:USERNAME",
[alias('password', 'p')]
[parameter(mandatory=$true)]
[string] $servicePassword
)
Invoke-Command -ComputerName $computerName -Script {
param(
[string] $computerName,
[string] $serviceUsername,
[string] $servicePassword
)
Get-WmiObject -ComputerName $computerName -Namespace root\cimv2 -Class Win32_Service | Where-Object { $_.StartName -eq $serviceUsername } | ForEach-Object {
Write-Host ("Setting credentials for service: {0} (username: {1}), on host: {2}." -f $_.Name, $serviceUsername, $computerName)
$change = $_.Change($null, $null, $null, $null, $null, $null, $serviceUsername, $servicePassword).ReturnValue
if ($change -eq 0) {
Write-Host ("Service Change() request accepted.")
if ($_.Started) {
$serviceName = $_.Name
Write-Host ("Restarting service: {0}, on host: {1}, to implement credential change." -f $serviceName, $computerName)
$stop = ($_.StopService()).ReturnValue
if ($stop -eq 0) {
Write-Host -NoNewline ("StopService() request accepted. Awaiting 'stopped' status.")
while ((Get-WmiObject -ComputerName $computerName -Namespace root\cimv2 -Class Win32_Service -Filter "Name='$serviceName'").Started) {
Start-Sleep -s 2
Write-Host -NoNewline "."
}
Write-Host "."
$start = $_.StartService().ReturnValue
if ($start -eq 0) {
Write-Host ("StartService() request accepted.")
} else {
Write-Host ("Failed to start service. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa393660(v=vs.85).aspx" -f $start) -ForegroundColor "red"
}
} else {
Write-Host ("Failed to stop service. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa393673(v=vs.85).aspx" -f $stop) -ForegroundColor "red"
}
}
} else {
Write-Host ("Failed to change service credentials. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa384901(v=vs.85).aspx" -f $change) -ForegroundColor "red"
}
}
} -Credential "$env:USERDOMAIN\$env:USERNAME" -ArgumentList $computerName, $serviceUsername, $servicePassword
Considering that whithin this class:
$class=[WMICLASS]'\\.\root\Microsoft\SqlServer\ComputerManagement:SqlService'
there's a method named setserviceaccount(), may be this script will do what you want:
# Copyright Buck Woody, 2007
# All scripts provided AS-IS. No functionality is guaranteed in any way.
# Change Service Account name and password using PowerShell and WMI
$class = Get-WmiObject -computername "SQLVM03-QF59YPW" -namespace
root\Microsoft\SqlServer\ComputerManagement -class SqlService
#This remmed out part shows the services - I'll just go after number 6 (SQL
#Server Agent in my case):
# foreach ($classname in $class) {write-host $classname.DisplayName}
# $class[6].DisplayName
stop-service -displayName $class[6].DisplayName
# Note: I recommend you make these parameters, so that you don't store
# passwords. At your own risk here!
$class[6].SetServiceAccount("account", "password")
start-service -displayName $class[6].DisplayName
Just making #alastairs's comment more visible: the 6th parameter must be $false instead of $null when you use domain accounts:
$service = Get-WMIObject -class Win32_Service -filter "name='serviceName'"
$service.change($null, $null, $null, $null, $null, $false, "DOMAIN\account", "mypassword")
Without that it was working for 4/5 of the services I tried to change, but some refused to be changed (error 21).
$svc = Get-WmiObject win32_service -filter "name='serviceName'"
the position of username and password can change so try this line to find the right place$svc.GetMethodParameters("change")
$svc.change($null,$null,$null,$null,$null,$null,$null,$null,$null,"admin-username","admin-password")
What I cannot find in the default PS stack, I find it implemented in Carbon:
http://get-carbon.org/help/Install-Service.html
http://get-carbon.org/help/Carbon_Service.html (Carbon 2.0 only)
The given answers do the job.
Although, there is another important detail; in order to change the credentials and run the service successfully, you first have to grant that user account permissions to 'Log on as a Service'.
To grant that privilege to a user, use the Powershell script provided here by just providing the username of the account and then run the other commands to update the credentials for a service as mentioned in the other answers, i.e.,
$svc=gwmi win32_service -filter 'Service Name'
$svc.change($null,$null,$null,$null,$null,$null,'.\username','password',$null,$null,$null)
Sc config example. First allowing modify access to a certain target folder, then using the locked down "local service" account. I would use set-service -credential, if I had PS 6 or above everywhere.
icacls c:\users\myuser\appdata\roaming\fahclient /grant "local service:(OI)(CI)(M)"
sc config "FAHClient" obj="NT AUTHORITY\LocalService"

Resources