I have a batch file which uses gpresult /v and saves the output in a text file and copy that text file to a shared folder. This batch when i run on my local machine works perfectly fine but once i deploy it through SCCM it says can not open file with error code 4. I dont know what is wrong in the file.
the code is Like this:
#echo off
gpresult /v >%computername%.txt
xcopy %computername%.txt \some path
Error 4 is "The system cannot open the file.", as if the path is invalid or the open() fails for some other reason.
Do you know what directory the program is running in (CWD)?
That's where the results of gpresult are going (if the output redirection succeeds).
gpresult is not going to produce meaningful user-level data for the SYSTEM user.
Perhaps you should use gpresult /v scope computer.
Why are you using xcopy when you're only copying one file? xcopy really only has added value (over copy) if you are copying directories.
xcopy's behavior changes depending on how you specify the target. If the target ends with the directory separator (backslash), xcopy treats it like it's a directory. If it doesn't and the target doesn't exist, xcopy asks you what to do, which causes automated processes to pause indefinitely waiting for user input.
SCCM Programs Run as 'NT Authority\SYSTEM'
When SCCM (2007) runs a program, the program doesn't run as a regular user. It runs as the highest privilege user (sort of), SYSTEM.
This account is not a regular account, and many settings and environment variables that exist and are predictable for a regular user are different or do not exist for SYSTEM.
One particularly frustrating "feature" of the SYSTEM account's profile is that it is nestled away under %WINDIR%\System32, and so it is subject to filesystem redirection whenever you refer to anything relative to the profile.
Try this: use psexec -s (sysinternals) to get shell access as the SYSTEM account and run the command in that environment to see how it behaves. This is as close as we can get to an environment like the one SCCM programs run under.
When SCCM runs the command, the CWD will probably be somewhere under %WINDIR%\SysWOW64\CCM\ and may be invoked with the 32-bit version of CMD.EXE.
I have a question in regards to something similar to this. So I have an uninstall bat that runs. Due to the vendors uninstall it causes a force close of the windows explorer UI. So in haste to solve that issue I added a call to open explorer.exe. There is a problem with this as someone pointed out to me. Actually as soon as he said I knew exactly what he was saying and where he was going with his statement. Calling explorer.exe would be fine except that the bat is running under the system context not the user so when explorer is restarted it will start under the guise of the system desktop profile not the user's. I know there is way to still run under the guise of system but to restart explorer under the currently logged in user's profile.
Related
I don't know if this is the right place to ask this question, but I am going to ask it anyway.
I have a frequent problem when I try to rename one of my folders; it says access is denied. I have full administrative rights on my computer. The problem occurs only when I try to do it via command prompt or batch files. I can manually rename the folder with no problems whatsoever. But I need to be able to rename it using the ren command. It is an irritating problem, and I have heard other people having the same problems. They usually fix it by re-taking ownership of the folder and restarting the computer. This works for me, but I hate having to do this every time. Is there a permanent solution that I can do to stop this problem? Also, when this problem occurs, it happens to all folders; I can't rename any of them using the ren command.
The answer is quite simple:
Windows does not permit deletion or renaming a directory/folder which is
the current directory of any running process (application/service) like the command process, or
any subdirectory of the directory to rename is the current directory of any running process, or
any file is opened in the directory to rename or any of its subdirectories by any process with OF_SHARE_DENY_READ, OF_SHARE_DENY_WRITE, OF_SHARE_EXCLUSIVE used on opening the file.
In other words as long as the directory itself or any file or subdirectory in this directory or its subdirectories is in use by any application, Windows denies renaming or deleting the directory.
On Unix/Linux it is possible to delete or rename a directory while it is in use by 1 or more running processes. The running *nix process has to handle the special use case that the directory or file just accessed successfully a millisecond before does suddenly not exist anymore.
My approach to solving this problem is to run the utility Handle, by Mark Russinovich of Windows Sysinternals. You can find it here.
This utility will show all the open handles on the system and which process is using them. One of them may have a path to the folder you are trying to rename.
I typically redirect the output of handle.exe to a file.
handle >handles.txt
Then I look at handles.txt in a text editor and search for the name of the folder I was trying to rename. It will appear in a section of handles belonging to the process that is keeping the handle to that folder open, and hence preventing it from being renamed. It shows the pid of the offending process, which you can decide how to deal with, in case you need to terminate it.
e.g. Trying to rename myfolder I forgot I had started a service running using pm2 (a process monitor) The output of Handle.exe included the following:
node.exe pid: 12752 DISCO\Stu
40: File (---) C:\Dev\myfolder\service
I fixed this by disabling Quick Access:
See Screenshot:
[
Well before you can run this command you have to have the privileges to do so as overwriting or modifying files from the command line requires admin rights. Once you got that done, enter the following:
ren (path name) (modified name, no quotation marks)
1 copy path of the folder. To do this, hold shift and right-click, you'll see the "copy as path option"
2 open cmd as admin. To do this, press window + X, then A.
3 in the cmd, type "cd C: then paste the path" so it will be, for example, like:
cd C:\Users\abc\Desktop\music
before you press enter, quote the last name; for example:
cd C:\Users\abc\Desktop\"music"
4 Next, type: ren *.present extension *.new extension; For example, from mp3 to exe:
ren *.mp3 *.exe
If no extension was existing, then, for example:
ren *. *.exe
This should work and eliminate the access denied nuisance.
I solved this problem by giving the user who run the batch full right on the directory. It seems the right from a group membership is not sufficient: the user was member of the local group Administrators and I received a "Access denied". After having added the user account in the directory security with full rights, it does the job.
I don't know if this is the right place to ask this question, but I am going to ask it anyway.
I have a frequent problem when I try to rename one of my folders; it says access is denied. I have full administrative rights on my computer. The problem occurs only when I try to do it via command prompt or batch files. I can manually rename the folder with no problems whatsoever. But I need to be able to rename it using the ren command. It is an irritating problem, and I have heard other people having the same problems. They usually fix it by re-taking ownership of the folder and restarting the computer. This works for me, but I hate having to do this every time. Is there a permanent solution that I can do to stop this problem? Also, when this problem occurs, it happens to all folders; I can't rename any of them using the ren command.
The answer is quite simple:
Windows does not permit deletion or renaming a directory/folder which is
the current directory of any running process (application/service) like the command process, or
any subdirectory of the directory to rename is the current directory of any running process, or
any file is opened in the directory to rename or any of its subdirectories by any process with OF_SHARE_DENY_READ, OF_SHARE_DENY_WRITE, OF_SHARE_EXCLUSIVE used on opening the file.
In other words as long as the directory itself or any file or subdirectory in this directory or its subdirectories is in use by any application, Windows denies renaming or deleting the directory.
On Unix/Linux it is possible to delete or rename a directory while it is in use by 1 or more running processes. The running *nix process has to handle the special use case that the directory or file just accessed successfully a millisecond before does suddenly not exist anymore.
My approach to solving this problem is to run the utility Handle, by Mark Russinovich of Windows Sysinternals. You can find it here.
This utility will show all the open handles on the system and which process is using them. One of them may have a path to the folder you are trying to rename.
I typically redirect the output of handle.exe to a file.
handle >handles.txt
Then I look at handles.txt in a text editor and search for the name of the folder I was trying to rename. It will appear in a section of handles belonging to the process that is keeping the handle to that folder open, and hence preventing it from being renamed. It shows the pid of the offending process, which you can decide how to deal with, in case you need to terminate it.
e.g. Trying to rename myfolder I forgot I had started a service running using pm2 (a process monitor) The output of Handle.exe included the following:
node.exe pid: 12752 DISCO\Stu
40: File (---) C:\Dev\myfolder\service
I fixed this by disabling Quick Access:
See Screenshot:
[
Well before you can run this command you have to have the privileges to do so as overwriting or modifying files from the command line requires admin rights. Once you got that done, enter the following:
ren (path name) (modified name, no quotation marks)
1 copy path of the folder. To do this, hold shift and right-click, you'll see the "copy as path option"
2 open cmd as admin. To do this, press window + X, then A.
3 in the cmd, type "cd C: then paste the path" so it will be, for example, like:
cd C:\Users\abc\Desktop\music
before you press enter, quote the last name; for example:
cd C:\Users\abc\Desktop\"music"
4 Next, type: ren *.present extension *.new extension; For example, from mp3 to exe:
ren *.mp3 *.exe
If no extension was existing, then, for example:
ren *. *.exe
This should work and eliminate the access denied nuisance.
I solved this problem by giving the user who run the batch full right on the directory. It seems the right from a group membership is not sufficient: the user was member of the local group Administrators and I received a "Access denied". After having added the user account in the directory security with full rights, it does the job.
Create a new file test.bat, the content is as follows:
echo aa;
and execute it in the dos command line,
test.bat
there are no output in the window. But when I tested it in another computer, it outputs
aa
When I double click the bat file, it always disappeared suddenly even I add a "pause" clause line in the test.bat file. Both the systems are Window XP. Can sb tell me where is the problem, please?
I have checked all the things Mofi suggested, but the problem remains.
Now, I divscover when reboot to the system using another Administrator account. All is fine.
So, whether the problem comes from the registry record of the Windows XP?
See my answer on Iterating over files in directory prepends extra character to filename where I have already explained what to check if batch files are not working as expected.
The environment variables ComSpec, PATHEXT and PATH should be verified by you first. And check also the values of registry key Command Processor as explained in referenced answer. Also Autorun value of key Command Processor is very critical.
Further, start Regedit and check standard value of registry key HKEY_CLASSES_ROOT\.bat displayed on right side. It should be batfile. Then go to HKEY_CLASSES_ROOT\batfile, open it and navigate to subkey open - command. The standard value is "%1" %*. It could be that your Windows registry is partly corrupt which makes it not possible to run a batch file by double click.
A check for a problem with registry would be opening a command prompt window by running
C:\Windows\System32\cmd.exe
via Run entry in start menu of Windows. Then run your batch file from within the command prompt window.
You should also run from a command prompt window
C:\Windows\System32\chkdsk.exe C: /F
and confirm running the check disk tool of Windows on next boot of Windows. Then restart Windows to let this tool check the file system for errors resulting in 1 or more corrupt files. If an error was really detected in file system, run after Windows finished starting from a command prompt window
C:\Windows\System32\chkdsk.exe C: /F /R
Confirm running this tool once again on next boot of Windows, but this time with read/write tests on all sectors of your hard disk and repairing sectors if that is possible at all. It can take several hours depending on size of drive C: to finish this task.
Added on 2014-09-28:
Anti-virus application
Do you have checked already the configuration of the anti-virus application?
It could be that it blocks the execution of all *.bat files.
Windows System Restore
Do you have already tried to use Windows System Restore for the account on which batch file execution fails and go back to a restore point of a date on which you are sure that batch file execution worked?
If ntuser.dat or ntuser.dat.log (= registry of current user) is partly corrupt or something is misconfigured in Windows registry for this user account, this would be the easiest method to get back a working environment for the account.
Process Monitor Analysis
As execution of batch files does not work only with one account, the reason must be a corrupt or wrong set key or value in registry of this account.
I suggest to download and run free tool Process Monitor from Sysinternals (Microsoft) using first the account on which batch file execution does not work as expected.
The first displayed on start of this tool is a dialog to configure a filter. Select from first list Process Name, let is selected on second list, enter cmd.exe in edit field, and let Include selected in last list. Click next on button Include and then on OK.
Now in main application window of Process Monitor click on last 3 symbols in toolbar to toggle off those features resulting in monitoring only registry and file system accesses. Clear current list by clicking on fifth symbol in toolbar or by pressing Ctrl+X.
Now double click on your sample batch file in Windows Explorer. Then switch batck to Process Monitor, scroll up to beginning and look line by line what happens on executing of a batch file. Perhaps you can see something which you think is not correct.
The column Result should show only SUCCESS and NAME NOT FOUND and rarely NO MORE ENTRIES for registry entries in log. INVALID in column Result is not good. The log can be saved as CSV file with Ctrl+S or by clicking on disk symbol in toolbar.
Exit Process Monitor, logout from this account, logon on other account, start here also Process Monitor, configure the same filter, execute same batch file and save also this log into a CSV file. Compare the 2 CSV files and look for differences (other than time and line number).
Windows Registry Compare
Another method to find out what is different between the 2 accounts resulting in batch file execution not working is comparing the registry hives of those 2 accounts. In both accounts start Regedit and export entire key HKEY_CURRENT_USER to a *.reg file. Compare the two registry exports with a text comparison tool. The new administrator account has definitely less keys and values. Interesting are those blocks with just similar, but not identical lines.
Most interesting are the keys:
HKEY_CURRENT_USER\Console
HKEY_CURRENT_USER\Environment
HKEY_CURRENT_USER\Software\Classes\.bat
HKEY_CURRENT_USER\Software\Classes\batfile
HKEY_CURRENT_USER\Software\Microsoft\Command Processor
Some keys from this list can be missing completely. That would be okay as in this case the same key under HKEY_LOCAL_MACHINE is taken into account by Windows. But when a key is missing in account on which batch file execution fails, it should be also missing in the other account, or something is wrong here.
What could be a big and hard to find problem is a registry key which is displayed on viewing the registry tree with Regedit, but when clicking on the key it cannot be read.
I have seen such partly corrupt registry keys already several times and it is very hard to fix such a registry error. This happens for example if an application removes a registry key without removing it also from index table of the registry.
Totally unexpected things happen if a registry key is present in index, but does not exist anymore in registry. For example I fixed once an issue where HKLM\Software\Classes\mailto was in index list, but did not exist anymore in registry. When the user clicked on a mailto link, Windows started creating new emails in Outlook in a loop until Windows run out of resources and user restarted Windows.
Please add # before echo, like this:
#echo aa
#pause
Its working in my Windows7 machine.
OS: Windows Server 2008 R2 Enterprise
I am unable to get the Task Scheduler to run .bat files while I am logged off. I have a a production .bat file I want to use, but for my troubleshooting purposes I am using C:\Users\Administrator\Desktop\test.bat
test.bat is very simple. All it contains is:
taskkill /im notepad.exe
It runs successfully on its own. If I have Notepad open and I double-click test.bat then the cmd window flashes and Notepad dies. The .bat file is not the problem.
The task I created in Task Scheduler is "Test taskkill" (without the quotes). I can see its location in Windows Explorer: C:\Windows\System32\Tasks\Test taskkill
If the task is set to run only when the user is logged on then the task works. With this setting, I can right-click on it > run and I get the same behavior as if I double-click the .bat file. That means the task is configured correctly.
If I set it to run whether or not the user is logged on then when I right-click > run nothing obvious happens. The job is reported as having been run successfully in the history, but Notepad survives. I know that I am using the proper credentials for the account that I am configuring to run the task. That account is the local administrator.
This issue appears similar to issues other have had in the past:
Running a .bat file in Scheduled Task
http://social.technet.microsoft.com/Forums/windowsserver/en-US/d47d116e-10b9-44f0-9a30-7406c86c2fbe/scheduled-task-wont-run-bat-file?forum=winservermanager
The thread in the second link seemed to resolve an identical issue for many people with the suggestion that the account used to run the task requires explicit permission to the .bat file and all files that the .bat file modifies. This was very promising (if an annoying requirement). However, I have confirmed or assigned explicit permissions for the local administrator to the following areas, and I am still not successful:
C:\Users\Administrator\Desktop\
C:\Users\Administrator\Desktop\test.bat
C:\Windows\System32\Tasks\
C:\Windows\System32\Tasks\Test taskkill
Additionally, I have confirmed that the local administrator account is in the local administrators group.
Am I missing some other permissions that needs to be set? Is there something else I should be looking at? Thanks!
I have resolved this problem with help from a contractor who was doing some other work for my institution.
In the properties window for the task, on the Action tab, when creating or editing the action that opens the batch file (in my case test.bat), there is the "Program/script:" field and there is also a "Start in (optional):" field. I previously had the "Program/script:" field containing the full path to the file, ending with the file name, and I had the "Start in (optional):" field null. This configuration appears to work without issue when the task is set to "Run only when user is logged on" in the General tab of the task's properties window. However, this configuration does not work when the task is set to "Run whether user is logged on or not".
In order to resolve the problem, I changed the action so that the "Program/script:" field contained only the file name, not the file path. I put the file path in the "Start in (optional):" field. This configuration works when the task is set to "Run only when user is logged on"! I have tested with the task running on a trigger and also with running it manually.
Not sure if this helps. My issue was using a interactive program (in particular Excel) as well.
Creating the 2 empty folders (Desktop) solved it. Create both even if you are running on x64.
C:\Windows\System32\config\systemprofile\Desktop
C:\Windows\SysWOW64\config\systemprofile\Desktop
I debugged my code and realised the code exited at this line
ExcelFile excelFile = new ExcelFile(directory, filename);
I read this solution somewhere and I cannot find the URL now.
Try this as well..
Resolved the "Run whether user is logged on or not" by setting the “Log on as Batch Job” security policy.
Here is details on the setting… https://danblee.com/log-on-as-batch-job-rights-for-task-scheduler/
You may take another approach, but here is the steps…
1) I updated the default domain group policy by adding my admin account (that I fire the task with) to the “Log on as Batch Job” security policy. (Even though ADMIN group is listed, and I am using an admin account)
2) I forced GPUPDATE on the client
3) Rebooted the client
4) Looked at the policy on the client to make sure it made it over from the DC
5) Set the task "Run whether user is logged on or not"
6) Ran the task on demand and it worked creating a PDF file.
7) Logged out and ran the task at scheduled time and it worked creating a PDF file.
I had similar problem, but it was related to the fact that there was a space in the path of my executable batch file. I have removed the space and now it works fine.
What work for me was make sure that the path is available.
i used net use Z: \computername\folder /persistent:yes
then the xxcopy /s /c /d /e /i /y D:*.* z:\BackupBat
I notice all my other .bat work fine only the one with the reference to a map folder was the one no running, so that need to be the problem. with these change the bat file runs good.
Verifying the following has worked for me:
1) 'Run if user is not logged in' option in Task Scheduler does not work for programs that is interactive mode. Example notepad, clock. Tasks will not run interactively. Make sure your program does not requires any interactive actions.
2)Check the “Start in (optional) “ If your program path is not one of the system paths. You have better to add you program path in it. On the "Program/Script" enter only the name of the program, and enter the path of your script in "Start in".
3)The user account you setup for your program must have permission not only to run your program itself and but also to run all other program that related to your program.
Here is a sample program:
On C:\myprogram\folderOne\test.cmd
date /t >> c:\Temp\testAuto.log
date /t >> c:\temp\testAuto.log
echo ----->> c:\temp\testAuto.log
cls
exit
-Create a Tasks, selecting on General>SecurityOptions "Run whether user is logged on or not"
-Enter on Action>Program/script: test.cmd
on "Start in" C:\myprogram\folderOne
-Run, you might see the cmd windows open and closes very quickly. The testAuto.log file should be in c:\tmp folder.
It might be because you don't have permission. I was facing the same problem and i found the solution like this -
Open Task Scheduler right click on your task and than select properties option.
In properties click on General tab and then click on 'User Group or User' and select the appropriate user.
I'll try to keep this short, without all the details of this batch file procedure.
OS: Windows XP
Action: Scheduled Task (background, I can't find a way to run it in the foreground)
Problem: files not created on mapped drive. When the batch file is ran directly, it works.
It does the following (or at least tries to):
clean a directory: works
create executables based on a substituted location
We use the following to map a local folder to the K: drive:
subst K: /D
subst K: D:\Development\SVN
The executables are built from source code that is located on (for example) K:\Sources to K:\Executables.
This fails, for a reason I did not yet discover. As mentioned above, if the batch file is ran directly it doesn't fail. If I substitute K:\ by C:\Development\SVN the issues seem to be resolved but still, this doesn't solve the fact that I can't run it when using K:.
I hope anyone here has an idea, I tried Googling for a long time + scanning SO but to no avail.
Thanks in advance!
substed drives are local to session, and your scheduled task is run in another session then your login session.
It seems to be possible to schedule task for user login session with schtasks.exe command line, but then the task runs only if the user is logged in. It might not be what you want, so using a full non-substed path might be the best solution after all.