I'm trying to run process via powershell script on windows startup. Unforturnately, PC on which I running it is slow. In most of cases the Start-Process method "crashes" with message This command cannot be executed due to the error: The service did not respond to the start or control request in a timely fashion. Is there a way, to adjust this timeout or do something, to solve this problem?
Line on which this issue appears:
Start-Process $AppPath -Credential $credential -WorkingDirectory $InstalationPath
EDIT: I tried also to set HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\ServicesPipeTimeout and HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\WaitToKillServiceTimeout to some big values (up to 1200000), but it doesn't help.
Related
I use a script to create a windows scheduled task to call a powershell script in elevated mode to run windows update by using boxstarter (a tool could automatically continue running code even there is reboot during the execution) when system startup. But not sure why, the task could be called after startup, but nothing has been done. If I manually start the scheduled task in task manager, it will run as expected.
Script to register a scheduled task:
$TaskActionArgument ="-noprofile -command "&{start-process powershell -argumentList '-File C:\users\administrator\updatescript\boxstarter.ps1 -verb runas'}""
$TaskAction = New-ScheduledTaskAction -Execute "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe" -argument $TaskActionArgument
$TaskTrigger = New-ScheduledTaskTrigger -AtStartup
Register-ScheduledTask -TaskName boxstarter -Action $TaskAction -Trigger $TaskTrigger -User administrator -Password Vmc12svt -RunLevel Highest
I checked the event log viewer and see following error message for the scheduled job:
System
Provider
[ Name] PowerShell
EventID 403
[ Qualifiers] 0
Level 4
Task 4
Keywords 0x80000000000000
TimeCreated
[ SystemTime] 2018-01-10T18:21:12.000000000Z
EventRecordID 267
Channel Windows PowerShell
Computer WIN-6HSHKOKP31E
Security
EventData
Stopped Available NewEngineState=Stopped
PreviousEngineState=Available SequenceNumber=16 HostName=ConsoleHost
HostVersion=4.0 HostId=13ece112-b027-4051-9ddf-1a195d3aa30f
HostApplication=C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
-File C:\users\administrator\updatescript\boxstarter.ps1 -verb runas EngineVersion=4.0 RunspaceId=d158a216-18e3-4e86-9ade-b232201c9cdc
PipelineId= CommandName= CommandType= ScriptName= CommandPath=
CommandLine=
For the error message, I googled and found explain of error code here
In general, the page says such issue could be caused by following error:
The Task Scheduler service is disabled
The COM service is disabled
The Windows Event Log service is disabled
The RPC service is disabled
There is not enough free memory
Non of above is true for my system.
So what's error with my scheduled task? How could I make it work?
It looks like all your services are not setup. It's a common problem on things that run on startup/login. There's a -RandomDelay parameter to New-ScheduledTaskTrigger. I recommend you tinker with that if its your own machine you are testing this with. My example uses 1 minute.
$TaskTrigger = New-ScheduledTaskTrigger -AtStartup -Delay (New-TimeSpan -Minutes 1)
If you want a minute or so, all the services needed should be started up by then.
Another thing you'll want to do is have the your code in a try/catch, so the error is being written out to a log file, so you can see the error in the context of PowerShell, which might provide a more detailed message than what you are getting in the event log.
You can troubleshoot this by creating the scheduled task manually and then trying to run it.
Try changing the TaskActionArgument property to only the following string:
-NoProfile -ExecutionPolicy Bypass -File C:\users\administrator\updatescript\boxstarter.ps1
You don't need Start-Process or -Verb runas. In fact, -Verb runas will actually keep things from working, because it provokes a UAC prompt, which you don't want when trying to automate.
Is there a way I can execute sysinternals Autologon.exe from command line (Powershell) and get the result, i.e. know if the credentials entered were correct?
If I use the GUI and not the command line then I do get message with this info..
Thanks.
You can run any Windows .exe/cmd/bat/vbs from PoSH, as long as you call it correctly.
PowerShell: Running Executables
https://social.technet.microsoft.com/wiki/contents/articles/7703.powershell-running-executables.aspx
There are several different methods for running executables as well as invoking code. How do you know which one to use for the job? Here is an outline of the methods with examples and general use.
Regarding ---
"If I use the GUI and not the command line then I do get message with this info.."
This is because Autologon.exe is doing this work and returning the result. SO, it's Autologon. PoSH will not get in Autologon's way / process, but you can get the exit code from external tools as long as you know what they are. I've not tried to this with Autologon. Yet, in most cases, it's a Boolean response: success or failure, 0 or 1, or 1 or 2. The Start-Process cmdlet allows you to trap error / exit code from a process, using the -PassThru parameter. Often that is use in concert with the -wait parameter as well.
Something like:
$AutologExitCode = Start-Process -FilePath = Autologon.exe -ArgumentList $SomeArguments -NoNewWindow -Wait -PassThru
"The error/exit code from AutoLogon is $($AutologonExitCode.ExitCode)"
Full disclosure: We do not allow Autologon in our environment. So, I've spent no time using Autologon, but the above premise would be the same as other exe's.
I'm trying to create a Powershell script that will be deployed to any node that is showing bad update health to automate some of the simple tasks without having to interrupt users during their workday. The Powershell script works perfectly if ran from an elevated PS prompt. It also runs fine when the same script is deployed to a test machine via SCCM with one exception: it won't call SFC.EXE /SCANNOW.
I've tried using:
Start-Process -FilePath "${env:Windir}\System32\SFC.EXE" -ArgumentList '/scannow' -Wait -NoNewWindow
Start-Process -FilePath "sfc.exe" -ArgumentList '/scannow' -Wait -NoNewWindow
Start-Process -FilePath "${env:Windir}\System32\SFC.EXE" -ArgumentList '/scannow' -RedirectStandardOutput "C:\SFC-Out.log" -RedirectStandardError "C:\SFC-Err.log" -Wait -NoNewWindow
& "sfc.exe" "/scannow"
Invoke-Command -ScriptBlock { sfc.exe /scannow }
Again, all of these examples work exactly as intended when run from an elevated PS prompt, but fail when run from the deployed PowerShell script. When I used the -RedirectStandardOutput, I checked the file SFC-Out.log and it read:
"Windows Resource Protection could not start the repair service"
I think this is because SCCM runs programs/scripts in the SYSTEM context instead of a user context (or even an elevated user context, but SYSTEM is supposed to be higher than an elevated session).
Is there a way to accomplish this? Sorry for the bad formatting, this is my first post on this site.
A bit late but I encountered the same issue. Not sure if this is the case for you but the cause was configuring the deployment of the script with SCCM to run as a 32 bit process. The script was being deployed to 64 bit systems. When I unchecked "run as 32 bit process" in the deployment configuration SFC worked without an issue under the context of a System account.
I created a package (not an application) in SCCM and had to use the redirect using the elusive sysnative folder for x64 machines:
https://www.thewindowsclub.com/sysnative-folder-in-windows-64-bit
So it would be:
C:\Windows\Sysnative\SFC.EXE /SCANNOW
What you have will work, just missing "-Verb RunAs" to elevate permissions. So your cmdlet should read:-
Start-Process -FilePath "${env:Windir}\System32\SFC.EXE" -ArgumentList '/scannow' -Wait -Verb RunAs
I've been reading and searching online for this, the only answer so far is that It can't be run due to sccm using the system account. It's also the same behavior when trying to run winmgt.
Fast forward to SCCM Current Branch 2109 and I was able to solve this problem by using the new Scripts feature built into SCCM. Using & 'sfc.exe' '/scannow' works, and I can manually run this script against any device collection showing devices in error. Start-Process -FilePath "sfc.exe" -ArgumentList "/scannow" -NoNewWindow -Wait works too.
Current PS script:
Invoke-Command -ComputerName RemoteServer007.FQDN.com -ScriptBlock {
Set-Variable -Name WOWCONFIG -value "d:\ABCs\WOWzers" `
| Start-Process "d:\da-folder\Do-It-NOW-Pleez.cmd"
}
If I log on locally to the server(RemoteServer007.FQDN.com) and execute the cmd file, it runs through all of the lines(commands) within the cmd file.
When I execute it remotely, it gets about 30% of the way through the commands within the cmd file, the PS execution ends without error, but not all of the lines/commands in the cmd file had been executed.
This was discovered by simply configuring each line of the cmd file to output to txt files.
I even tried re-ranging the commands in the cmd file, thinking that perhaps there was a specific command that was causing it to exit, but that is not the case.
I'm wondering if there is some timeout or response that PowerShell is not getting? and just quitting almost immediately after starting?
Any ideas or help would be greatly appreciated.
There are a couple of things you can do here:
You may have a memory issue. Increasing the value of MaxMemoryPerShellMB might help
set-item WSMan:\$target\Shell\MaxMemoryPerShellMB -Value 0 -Force
You'd need to run this once on the remote machine before you execute your commands again.
You can also see possible error logs in the windows event viewer. There are categories for powershell and for Windows Remote Management which you should look at.
Finally, you can just run this process asynchronously, using the task scheduler for instance. I had a similar problem with windows in the past, and running the process from the task scheduler, outside the powershell session, fixed it. There's an example of how we did this in Cloudify here:
https://github.com/CloudifySource/cloudify/blob/master/esc/src/main/resources/clouds/ec2-win/upload/bootstrap-management.ps1#L220
I use the following command to run setup_server.exe on remote Windows box:
powershell -command "$encpass=convertto-securestring -asplaintext RPASSWORD -force;$cred = New-Object System.Management.Automation.PSCredential -ArgumentList RUSER,$encpass; invoke-command -computername RCOMPUTERNAME -scriptblock {setup_server.exe} -credential $cred;"
setup_server.exe's task is to create some configuration files and start my_server.exe (some daemon process), then it finishes. And I want my_server.exe to keep running after setup_server.exe is finished.
So when I do it via CMD on local box (i.e. just run setup_server.exe from CMD) it works, but when I do it via powershell on remote host it doesn't work. Namely the my_server.exe gets started, but right after setup_server.exe is closed the server also gets closed(killed).
So the question is following:
Which powershell flags/cmdlets should I use to make the described scenario to work as in local mode?
NOTE: I want synchronously get output of setup_server.exe, so running remote command with -AsJob flag, probably wouldn't work for me, though I even don't know if it will keep the server alive after setup_server.exe's end.
The way to keep the remote PowerShell session running after the command has finished is to use a PSSession e.g.:
$s = new-PSSession computername
Invoke-Command -session $s { ..script.. }
... do other stuff, remote powershell.exe continues to run
Remove-PSSession $s # when you're done with the remote session
Generally though exes should run independently from the app that launched them.
Why are you using Invoke-Command. If you want a persistent Session, use Enter-PSSession.
$s = New-PSSession -Computername "Computername";
Enter-PSSession -Session $s;
setup_server.exe
# Once you are finnished
Exit-PSSession
With 'Enter-PSSession' you are not just Invoking some Command on the Server, you are directly logged-in like you probably know from SSH.
If you want your powershell session to keep running because you are running an exe, try using the -InDisconnectedSession switch. From what I understand, it will run the executable on the remote machine in a session that isn't actually connected to your computer. In essence, your computer will not destroy the session, when it disconnects, allowing the exe to continue to run.
invoke-command -computername RCOMPUTERNAME -scriptblock {start-process setup_server.exe} -InDisconnectedSession
If you need to do this on multiple computers. Setup an array of all the computer names.
Note: I don't believe this works with sessions that are already created.
In order to keep a powershell code running on the session exit it should be a process. And the windows way to keep the process is running a .exe or a windows service.
To keep a Powershell shell open after executing a command, I use the -NoExit switch, e.g. this script starts a remote interactive PS session on servername with user administrator
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoExit
-Command "Enter-PSSession -ComputerName servername -Credential administrator"
http://powershell-guru.com/powershell-tip-13-prevent-powershell-from-exiting-once-script-finished/