How to Open Desktop Properties from CMD? - cmd

First post here..
I'm writing a program and I need to change the location of the Desktop from Java, (or CMD).
Is there a CMD command that will open the Desktop properties? (where you can modify the location of the desktop)
Thanks,

You can change the location in the registry.
The following batch file example should set the location to %USERPROFILE%\Desktop, (which is the default).
#Echo Off
Reg Add "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Desktop" /V "Path" /T REG_EXPAND_SZ /D "%%USERPROFILE%%\Desktop" /F >Nul
I'll leave it to you to change it to a single cmd.exe command if you'd prefer to do it at the Command prompt or if you think changing the registry another way would be easier for you.
You can enter any valid UNC name or mapped drive in the value of this entry. Just remember that as this is an EXPAND string, you should double up the percent characters if using variables you want to expand when accessed.

Related

Batch | Why can't a script running in admin access other scripts? [duplicate]

I have a batch file that is in the same directory as the file I want to xcopy. But for some reason the file is not being found.
I thought that current directory was always where the batch file was located.
I run batch file as administrator. This occurs on a Windows 7 64-bit desktop computer.
Batch file:
#ECHO OFF
XCOPY /y "File1.txt" "File2.txt"
PAUSE
Error:
File not found - File1.txt
0 File(s) copied
Which directory is current working directory on starting a batch file with context menu item Run as administrator depends on User Account Control (UAC) setting for the current user.
This can be demonstrated with following small batch file C:\Temp\Test.bat:
#echo Current directory is: %CD%
#pause
With having selected in User Account Control Settings
Default - Notify me only when programs try to make changes to my computer
Don't notify me when I make changes to Windows settings
and using Run as administrator, Windows uses registry key
HKEY_CLASSES_ROOT\batfile\shell\runasuser\command
This registry key does not contain a default string for executing the batch file. Instead there is the string value DelegateExecute with the CLSID {ea72d00e-4960-42fa-ba92-7792a7944c1d}.
The result is opening a dialog window with title User Account Control and text:
Do you want to allow the following program to make changes to this computer?
Program name: Windows Command Processor
Verified publisher: Microsoft Windows
After confirmation by the user, Windows opens temporarily a new user session like when using on command line RunAs.
In this new user session the current working directory is %SystemRoot%\System32 on executing now the command defined in Windows registry with default string of key
HKEY_CLASSES_ROOT\batfile\shell\runas\command
which is:
%SystemRoot%\System32\cmd.exe /C "%1" %*
Therefore a console window is opened with title C:\Windows\System32\cmd.exe and the 2 lines:
Current directory is: C:\Windows\System32
Press any key to continue . . .
After hitting any key, batch execution finishes which results in closing cmd.exe which results in closing the user session.
But with having selected in User Account Control Settings
Never notify me when
Programs try to install software or make changes to my computer
I make changes to Windows settings
the behavior is different as the user has already elevated privileges.
Now Windows uses directly the command
%SystemRoot%\System32\cmd.exe /C "%1" %*
according to default string of key
HKEY_CLASSES_ROOT\batfile\shell\runas\command
in current user session.
The result is opening a console window also with title C:\Windows\System32\cmd.exe, but displayed in window is:
Current directory is: C:\Temp
Press any key to continue . . .
The current working directory of the parent process (Windows Explorer as desktop) is used for executing of the batch file because no switch to a different user session was necessary in this case.
PA has posted already 2 possible solutions in his answer which I replicate here with a small improvement (pushd with directory in double quotes) and with adding a third one.
Change current directory to directory of batch file using pushd and popd:
pushd "%~dp0"
%SystemRoot%\System32\xcopy.exe "File1.txt" "File2.txt" /Y
popd
This works also for UNC paths. Run in a command prompt window pushd /? for an explanation why this also works for UNC paths.
Use directory of batch file in source and destination specifications:
%SystemRoot%\System32\xcopy.exe "%~dp0File1.txt" "%~dp0File2.txt" /Y
Change working directory to directory of batch file using cd:
cd /D "%~dp0"
%SystemRoot%\System32\xcopy.exe "File1.txt" "File2.txt" /Y
This does not work for UNC paths because command interpreter cmd does not support a UNC path as current directory by default, see for example CMD does not support UNC paths as current directories for details.
The error message is very self explanatory. The file file1.txt is not found.
Because the file name does not include an absolute path, the system tries to find it on the current directory. Your current directory does not contain this file.
Your misconception is that the current directory is not the directory that contains the bat file. Those are two unrelated concepts.
You can easily check by adding this two commands in your bat file
echo BAT directory is %~dp0
echo Current directory is %CD%
you can notice they are different, and that there is a subtle difference in the way the last backslash is appended or not.
So, there are esentially two ways to cope with this problem
either change the current directory to match the expected one
pushd %~dp0
XCOPY /y "File1.txt" "File2.txt"
popd
or specify the full path in the command
XCOPY /y "%~dp0File1.txt" "%~dp0File2.txt"
For the sake of completeness and obscurity, I add another workaround, confirmed as working under Windows 8.1 and expected to work elsewhere, as it relies on documented functionality:
You can change the runas command definition keys
HKEY_CLASSES_ROOT\batfile\shell\runas\command and
HKEY_CLASSES_ROOT\cmdfile\shell\runas\command into
%SystemRoot%\System32\cmd.exe /S /C "(for %%G in (%1) do cd /D "%%~dpG") & "%1"" %*
Which results in the bat or cmd file starting in its containing directory when started using the runas verb, respectively the "Run as Administrator" menu entry.
What the additions to the original command exactly do:
cmd /S strips away first and last (double) quote in command string after /C
for %%G in (%1) do enumerates its single entry, the %1 argument,
making it available for expansion as %%G in the loop body; the letter is arbitrary but some may be "reserved"
%%~dpG expands to the drive and path of %%G, the ~ tilde stripping away quotes if present, which is why we add them back explicitly
cd /D changes both the drive and directory to its argument, and finally
& runs the second command "%1" %* regardless of success of the first one.
You can use pushd which will even support UNC paths, but a stray popd would land any script in the system32 directory, not a behavior I would be fond of.
It should be possible to do this for the exefile entry as well, but frankly, I'd rather live with the inconsistency than to attempt this on my system, as any error there could break a lot.
Enjoy defeating the security mechanics of your operating system :)

Adding "Open Anaconda Prompt here" to context menu (Windows)

I'd like to add an option on my context menu (Windows 7 and 10) to open an Anaconda Prompt into the file location when I right-click the folder, but I can't figure out the right registry key.
Here's what I know how to do:
Add an item to the context menu that opens a normal command window at the folder location
Open an Anaconda prompt from cmd (run their "activate.bat" file)
What I can't figure out is how to combine these steps into a single registry key so I can open an Anaconda Prompt and then cd in that prompt to the current folder. But maybe I'm approaching this the wrong way.
Help from internet gurus is appreciated.
Run Registry Editor (regedit.exe)
Go to HKEY_CLASSES_ROOT > Directory > Background > shell
Add a key named AnacondaPrompt and set its value to Anaconda Prompt Here
Add a key under this key called command, and set its value to cmd.exe /K C:\Users\user\Anaconda3\Scripts\activate.bat change the location to wherever your Anaconda installation is located.
In recent Anaconda versions (I'm at conda 4.5.5) they have changed the behaviour and the shortcut to Anaconda Prompt, so the new procedure is in fact a bit simpler than described by bdforbes.
The new way to launch Anaconda Prompt in a folder is
cmd.exe /K %%USERPROFILE%%\AppData\Local\Continuum\Anaconda3\Scripts\activate.bat
pushd is to change the current directory, %V is the current directory, and /K is to run a command.
So the modified cwp2.py is not needed anymore. Put the following contents in a .bat-file and run as administrator to add the needed keys to the registry (a modified version of the gist posted by Thibaud Ruelle in the comments to the other answer)
REG ADD HKCR\Directory\Background\shell\Anaconda\ /ve /f /d "Anaconda Prompt Here"
REG ADD HKCR\Directory\Background\shell\Anaconda\ /v Icon /f /t REG_EXPAND_SZ /d %%USERPROFILE%%\\Anaconda3\\Menu\\Iconleak-Atrous-Console.ico
REG ADD HKCR\Directory\Background\shell\Anaconda\command /f /ve /t REG_EXPAND_SZ /d "%windir%\System32\cmd.exe pushd "%V" "/K" %%USERPROFILE%%\Anaconda3\Scripts\activate.bat %%USERPROFILE%%\Anaconda3"
REG ADD HKCR\Directory\shell\Anaconda\ /ve /f /d "Anaconda Prompt Here"
REG ADD HKCR\Directory\shell\Anaconda\ /v Icon /f /t REG_EXPAND_SZ /d %%USERPROFILE%%\\Anaconda3\\Menu\\Iconleak-Atrous-Console.ico
REG ADD HKCR\Directory\shell\Anaconda\command /f /ve /t REG_EXPAND_SZ /d "%windir%\System32\cmd.exe pushd "%V" "/K" %%USERPROFILE%%\Anaconda3\Scripts\activate.bat %%USERPROFILE%%\Anaconda3"
UPDATE: The answer by Filip S. might work better on more recent versions of Anaconda.
ANOTHER UPDATE: I fixed an issue with using this launcher in the drive root (e.g. C:\ or D:\). It's very minor: some whitespace has been added to the registry entry (relevant part: "%V ") so that the trailing backslash does not confuse Windows.
Original post
I also wanted this functionality, so I made it.
The key steps are outlined below, with the explanation further down.
Solution
Warning: Do not proceed unless you are comfortable editing the registry and are using a non-production system. And obviously don't run everything I tell you to, check that it's not doing anything nefarious. You don't know me!
1. Modify the Anaconda script that sets the working directory
Find the Anaconda script cwp.py (mine was in C:\Users\bdforbes\Anaconda3\) and copy it to cwp2.py in the same directory.
Modify cwp2.py to accept a target path as the second argument and change to that directory:
prefix = sys.argv[1]
cwd = sys.argv[2]
args = sys.argv[3:]
... (PATH setting code)
(REMOVE OLD LOGIC THAT CALLED os.chdir)
os.chdir(cwd)
sys.exit(subprocess.call(args, env=env))
Full code here: https://gist.github.com/bdforbes/9ef59cd01c22acefc20c5c92bd9550ae
2. Add the registry keys
In the registry, go to HKEY_CLASSES_ROOT\Directory\Background\shell\ and add a key Anaconda with default value "Open Anaconda Prompt Here", with a sub-key command with the following default value:
C:\Users\bdforbes\Anaconda3\pythonw.exe C:\Users\bdforbes\Anaconda3\cwp2.py C:\Users\bdforbes\Anaconda3 "%V " cmd.exe "/K" C:\Users\bdforbes\Anaconda3\Scripts\activate.bat C:\Users\bdforbes\Anaconda3
Add the same entries to HKEY_CLASSES_ROOT\Directory\shell\.
I've put a .reg file here, you just need to search replace bdforbes and replace it with your Windows account name. Don't run a .reg file without checking it first!
3. Use your fancy new context menu item
Right click on a folder. You should see the new entry there which will let you open a new Anaconda prompt.

How to run a command on command prompt startup in Windows

EDIT
If you want to perform any task at computer startup or based on an
event this is very helpful
http://answers.microsoft.com/en-us/windows/forum/windows_7-performance/how-to-schedule-computer-to-shut-down-at-a-certain/800ed207-f630-480d-8c92-dff2313c193b
Back to the question
I have two questions:
I want some specific commands to be executed when I start command prompt.
e.g. cls to clear my command prompt.
I want to execute some commands in a batch file and wait for the user to enter new commands (if any).
e.g. A batch file which will take the user to some specified folder and then wait for the user to rename/delete a file from the command prompt.
How can I do it?
If you want a defined set of commands to run every time you start a command prompt, the best way to achieve that would be to specify an init script in the AutoRun registry value. Create it like this (an expandable string value allows you to use environment variables like %USERPROFILE%):
reg add "HKCU\Software\Microsoft\Command Processor" /v AutoRun ^
/t REG_EXPAND_SZ /d "%"USERPROFILE"%\init.cmd" /f
Then create a file init.cmd in your profile folder:
#echo off
command_A
command_B
...
cls
To remove these changes, delete the registry key:
reg delete "HKCU\Software\Microsoft\Command Processor" /v AutoRun
Make a shortcut
Go to the properties
The bit where it says: C:\Users\<Your username>\Desktop\cmd.exe, you put: -cmd /K <your command here>
e.g.
C:\Users\Lewis\Desktop\cmd.exe -cmd /K color 1f
This is the way to launch 1 command without having to mess about with the registry.
Run multiple commands
You can also use & (and) operator to execute multiple commands.
Eg.
C:\Users\Lewis\Desktop\cmd.exe -cmd /K color 1f & H: & <your command>
Credits: user6589073
I found my answer: I should use the /K switch, using which I can enter a new command on the opened command prompt.
E.g. cmd /K cls will open a command prompt for me and clear it. (Answer for question 1)
and
cmd /K MyBatchFile.bat will start a command prompt, execute the batch file and stay on the command prompt and will not exit. (Answer for question 2).
First, you need to press Windows Key + R.
In the box that appears, type "regedit" (without the quotes).
The Windows Registry Editor should open.
Now, locate to HKEY_CURRENT_USER/Software/Microsoft/Command Processor.
Once you have clicked on Command Processor on the left side, click Edit on the top bar.
Then go to New > String Value in the Edit menu.
Rename the String Value that appears to Autorun.
Right click on Autorun and select Modify.
Under the "Value Data" area, type in the commands you want to run. You can run multiple by typing && between them.
Expanding a bit, here is an alternative for Windows 10 where multiple aliases can be defined and applied to the Command Prompt upon execution.
Create a file called init.cmd containing aliases on your %USERPROFILE% folder:
init.cmd
#echo off
doskey c=cls
doskey d=cd %USERPROFILE%\Desktop
doskey e=explorer $*
doskey g=git status
doskey l=dir /a $*
Register it to be applied whenever the Command Prompt is executed:
In the Command Prompt, run:
reg add "HKCU\Software\Microsoft\Command Processor" /v AutoRun /t REG_EXPAND_SZ /d "%"USERPROFILE"%\init.cmd" /f
Done
Now the contents of init.cmd will run for executions of cmd.exe namely from:
Taskbar shortcut
WIN+R cmd
By typing cmd in the File Explorer address bar
By running cmd.exe directly from C:\Windows\System32
After registering these settings just remember to close/open:
The Command Prompt so the settings are applied
The File Explorer, if you use to launch the cmd via File Explorer address bar
To unregister it, run:
reg delete "HKCU\Software\Microsoft\Command Processor" /v AutoRun
I have a command to run a python program. I do not want to run this command manually after login, I want this command should run automatically after I logged in to my ubuntu. I am using Ubuntu 16.04.
Here is the command.
sh demo_darknet_yolov3.sh , this shell is placed in this directory littro#littro-System-Product-Name:~/MobileNet-YOLO-master/MobileNet-YOLO-master
Depending on your script, you may want to use the cmd.exe /k <input script> method instead of the registry entry Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor\autorun
I have found with the latter, that other programs that launch cmd are affected by the registry entry. For example, I cannot get Visual Studio Native Tools prompt to work properly because my script gets in the way. In my case, the script is a menu with 5 options including to launch various programs manually (I like to minimize my auto-run programs) and set various environment variables (ie., printers, proxy settings, default versions of programs, etc).
If you are doing something static I think either method works fine.
I would have commented on the question or an applicable answer, but I do not have the reputation to comment.

Setting a system environment variable from a Windows batch file?

Is it possible to set a environment variable at the system level from a command prompt in Windows 7 (or even XP for that matter). I am running from an elevated command prompt.
When I use the set command (set name=value), the environment variable seems to be only valid for the session of the command prompt.
The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe:
C:\Program Files\Support Tools>setx /?
SETX: This program is used to set values in the environment
of the machine or currently logged on user using one of three modes.
1) Command Line Mode: setx variable value [-m]
Optional Switches:
-m Set value in the Machine environment. Default is User.
...
For more information and example use: SETX -i
I think Windows 7 actually comes with setx as part of a standard install.
Simple example for how to set JAVA_HOME with setx.exe in command line:
setx JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"
This will set environment variable "JAVA_HOME" for current user. If you want to set a variable for all users, you have to use option "/m" (or -m, prior to Windows 7).
Here is an example:
setx /m JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"
Note: you have to execute this command as Administrator.
Note: Make sure to run the command setx from an command-line Admin window
If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.
Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):
SET XYZ=test
SETX XYZ test
For XP, I used a (free/donateware) tool called "RAPIDEE" (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).
System variables can be set through CMD and registry
For ex. reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH
All the commonly used CMD codes and system variables are given here: Set Windows system environment variables using CMD.
Open CMD and type Set
You will get all the values of system variable.
Type set java to know the path details of java installed on your window OS.
SetX is the command that you'll need in most of the cases.Though its possible to use REG or REGEDIT
Using registry editing commands you can avoid some of the restrictions of the SetX command - different data types, variables containing = in their name and so on.
#echo off
:: requires admin elevated permissions
::setting system variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v MyVar /D MyVal
::expandable variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /T REG_EXPAND_SZ /v MyVar /D MyVal
:: does not require admin permissions
::setting user variable
REG ADD "HKEY_CURRENT_USER\Environment" /v =C: /D "C:\\test"
REG is the pure registry client but its possible also to import the data with REGEDIT though it allows using only hard coded values (or generation of a temp files). The example here is a hybrid file that contains both batch code and registry data (should be saved as .bat - mind that in batch ; are ignored as delimiters while they are used as comments in .reg files):
REGEDIT4
; #ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"SystemVariable"="GlobalValue"
[HKEY_CURRENT_USER\Environment]
"UserVariable"="SomeValue"
Just in case you would need to delete a variable, you could use SETENV from Vincent Fatica available at http://barnyard.syr.edu/~vefatica.
Not exactly recent ('98) but still working on Windows 7 x64.

cmd defaults to F: drive

When I open cmd on my laptop it is defaulting to the F: drive. This is troubling me does anyone know how it got that way or how to get it back to where it opens to the C: drive by default?
Use the command
C:
To change to the drive C. It would of course work for any drive letter.
Very minor nit: if you're using Windows 7 you don't need the cmdhere powertoy, it's built in to Explorer.
You just navigate to a directory in Windows Explorer then hold down the shift key and right click. "Open command window here" is one of the selections on the context menu.
When it comes to opening cmd.exe in a specific directory, I just create a shortcut to cmd.exe and then in the shortcut properties I set "Start in:" to the drive/directory I want it to start in.
Using a shortcut allows me to customize the cmd.exe windows depending on what I'm using it for. For normal file editing/viewing I use a 180x60 window and appropriate font, but when I want to read/search log files I have a shortcut that opens a 260x100 window with a smaller font. That way I can view most long log file lines without having to use the horizontal scroll.
http://blog.stevienova.com/2007/04/08/change-your-default-cmd-prompt-path/
Sometimes, your path when you go to start->run, CMD will be something
you don’t want. In active directory or on an NT domain, sometimes your
default home path might be a network drive. This isn’t so good when
you are offline or drop offline after being online. The CMD prompt is
set to a place where you can’t get to.
To change the path, you can edit the registry (at your own risk)
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USERSoftwareMicrosoftCommand Processor] “Autorun”=”c:”
This will change the path to your c: drive.
I believe it defaults to %HOMEDRIVE%\%HOMEPATH% so if you can muck about with those environment variables that might be an option. I can't edit these environment variables on my company's network, so I had to use the AutoRun to change it to something sane.
quick answer: cmd /k c:
long answer to make it "automagical":
http://windowsxp.mvps.org/autoruncmd.htm
In RegEdit.exe I created a String:
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
The value I used for AutoRun was "D:"
On the start screen / menu, type in "cmd", right-click it and select "Open File - Location".
In the opened window, right-Click on "Command Prompt" icon, select "Properties", and edit the "Start In" property to your desired path. I used "C:\" as an example
If you are opening it from a shortcut change the working dir for the shortcut.
In addition to the other answers, there's a nice powertoy for XP called "open command window here." It adds an option to your right-click context menu when you click inside a folder to open a command window using that directory as the starting path.
http://www.microsoft.com/windowsxp/Downloads/powertoys/Xppowertoys.mspx
I ran into a similar issue where cmd would always open up in a particular directory (annoying when running scripts which invoke cmd). The best way to deal with this is to edit your autorun settings. Raymond Chen has a nice article about this here:
http://blogs.msdn.com/oldnewthing/archive/2007/11/21/6447771.aspx
The summary is that when you start a command shell, it checks the autorun registry key, and executes the commands stored there. The registry keys it checks are:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
Some answers already mentioned AutoRun as a solution.
But that can be very dangerous, as the AutoRun entry will be executed for any new cmd.exe instance (only pipes ignore the AutoRun).
A simple expample that fails:
cd /d E:\myPath
FOR /F "delims=" %%Q in ('dir') do echo - %%Q
With AutoRun=C:, this shows the content of the current path of drive C:
You can still use AutoRun, but it should be a batch script, that checks if it was called interactive, by FOR/F or by drag&drop.
#echo off
REM *** To enable this script, call it by <scriptName> --install
setlocal EnableDelayedExpansion
REM *** ALWAYS make a copy of the complete CMDCMDLINE, else you destroy the original!!!
set "_ccl_=!cmdcmdline!"
REM *** The check is necessary to distinguish between a new cmd.exe instance for a user or for a "FOR /F" sub-command
if "!_ccl_:~1,-2!" == "!comspec!" (
REM ***** INTERACTIVE ****
REM *** %1 contains only data, when the script itself was called from the command line
if "%~1" NEQ "" (
goto :direct_call
)
endlocal
doskey /macrofile="%~dp0\cmdMacros.mac"
echo ********************************************************************
echo * AutoRun executed from "%~f0"
echo * Macros loaded from "%~dp0\cmdMacros.mac"
echo ********************************************************************
cd /d C:\myPath
) ELSE (
REM *** Called by a FOR command, by an explorer click or a drag & drop operation
REM *** Handle PROBLEMATIC Drag&Drop content, if necessary
endlocal
)
exit /b
:direct_call
if "%~1" == "--install" (
reg add "HKEY_CURRENT_USER\Software\Microsoft\Command Processor" /v "AutoRun" /t REG_SZ /d "%~f0"
exit /b
)
if "%~1" == "--show" (
reg query "HKEY_CURRENT_USER\Software\Microsoft\Command Processor" /v AutoRun
exit /b
)
if "%~1" == "--remove" (
reg DELETE "HKEY_CURRENT_USER\Software\Microsoft\Command Processor" /v AutoRun /f
)
exit /b

Resources