I wish there's a way to show a shortened directory path in windows CMD, I searched the internet and found this command:
for %I in (.) do %~nxI
if you enter this command in cmd and press enter it would show the current dir name. suppose I was standing in my desktop it will print:
Desktop
thats enough for me. but not yet, I tried to save this command in a environment system variable then pass that variable to cmd line, but this way it would print the command itself instead of the result.
created a variable named PROMPT then value is:
%username%$s$p$s$d$t$_-$g$s
result is:
my_username full_path_to_current_dir date time newline dash greater_than_mark(>)
Mahdi c:\Users\Mahdi\Desktop 23/02/2020 19:27:38.93
->this is an screenshot of what Ihave: (https://i.stack.imgur.com/Auicf.png)
This is not a feature avaible in the standard prompt.
You potentially could hack it using echo off and doskeys,
but I would instead suggest checking out one of the many alternatives such as cmder or Zoc
Is this what you wanted?
For /F "Tokens=1*Delims=|" %I In (""%UserName%"|"%CD%"") Do #Prompt %~I$s%~nxJ$s$d$t$_-$g$s
Alternatively, if you wanted it setting to a variable, run the prompt command inside another for loop, and capture the output of that with the Set command.
Related
I'm running a command line script on multiple PC's and i'm trying to save username as a file name so i can see who's information i'm viewing later on.
In the command line script i run Whoami and i'd like to save it as "user"."file type". I'm trying to do this in a command line script because I always do it manually in command line and am trying to automate this process so I can do it faster.
If you know how to do it in a better way do share.
whoami > test.txt
tells it to go to a file and "test.txt" will be generated wherever your CMD CurDir is.
You may use Windows Environment variables %USERNAME% and possibly %USERDOMAIN% if the domain is needed.
%USERNAME% does not return the domain by itself.
Full list of standard environment variables: How-to: Windows Environment Variables
Use these in the command as needed. For example:
dir > %USERNAME%.txt
If you need the domain in there:
dir > %USERDOMAIN%_%USERNAME%.txt
(using _ to separate domain and username instead of \ since filename cannot contain \)
Remember to use >> instead of > if you don't want the file to be overwritten each time the command is run.
You may want to direct errors and standard output as needed: Redirecting error messages from Command Prompt: STDERR/STDOUT
Instead of showing
C:\Users\test_user\Documents\Folder\etc
show
\etc
or if possible limit it to a certain number
\Document\Folder\etc
If you check in help prompt /? there are two options that can either show the current drive or full path.
I would suggest to use new line option along with the Drive so that you will get more space to view/type the command using below combination.
prompt $P$_$G
With this you will be able to see the Path in the line above the prompt.
In short, can't see a simple way of doing it.
In order to change the prompt options you can use the prompt command. The configuration you're looking for isn't listed.
The available options can be viewed by
prompt /? in the command window.
https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/prompt.mspx?mfr=true
The following is a simple batch script which can set the prompt to include only the current folder. Note that it does not work on directory names with certain characters such as parenthesis and spaces. I named it cdd.bat.
#echo off
cd %1
for %%i in (%CD%) do set NEWDIR=%%~ni
PROMPT %NEWDIR%$G
Like others pointed out, you can use the command - prompt to set the text that is shown in cmd.
While you cannot dynamically set the path to just the parent folder, you can manually set it using:
prompt {text}
So in your case, you can set it as:
prompt etc\$G
This will result in:
etc\>
$G adds an arrow sign. You can refer the documentation for detailed explanation.
Here is a .ps1 file i use to do this for myself.
<#
FileName: promptPsShort.ps1
To set the prompt to the last folder name in the path:
> function prompt {$l=Get-Location; $p="$l".split("\")[-1]; "PS $p> "}
# works at cmd prompt, BUT NOT DIREECTLY from a .ps1 file.
RESEARCH
1. google: powershell 7 copy text into clipboard
[How to copy text from PowerShell](https://superuser.com/q/302032/236556)
[Set-Clipboard](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/?view=powershell-7)
2. google: powershell escape double quote
[Escaping in PowerShell](http://www.rlmueller.net/PowerShellEscape.htm)
3. google: powershell raw string
[About Quoting Rules](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7)
4. Usage example: powershell
PS C:\flutter_beta\flutter\examples\catalog\android\app\src\main> pwd
Path
----
C:\flutter_beta\flutter\examples\catalog\android\app\src\main
PS C:\flutter_beta\flutter\examples\catalog\android\app\src\main> promptPsShort.ps1
Paste the current Clipboard contents into the Powershell Command Line and press Enter.
PS C:\flutter_beta\flutter\examples\catalog\android\app\src\main> function prompt {$l=Get-Location; $p="$l".split("\")[-1]; "PS $p> "}
PS main>
PS main>
PS main>
#>
$shortPromptCmdStr = #'
function prompt {$l=Get-Location; $p="$l".split("\")[-1]; "PS $p> "}
'#
Set-Clipboard -Value $shortPromptCmdStr
write-host "Paste the current Clipboard contents into the Powershell Command Line and press Enter."
Love and peace,
Joe
I am attempting to run a build task from a .cmd file where Powershell extracts a zip file, which helps bypass a problem with Visual Studio's limit on the number of directory characters. However, I am having problems getting the Powershell command to execute correctly. I've tried a number of variations with the quotations, and I either get a termination error, or the Powershell command outputs as a string with the zip file not extracted. Below is an example of my current .cmd file:
//%1% is a passed in command line argument for the absolute path, e.g. C:\path\to\dir
set Source=%1%directory.zip
set Destination=%1%directory
powershell -Command $pscmd = '{Add-Type -assembly "system.io.compression.filesystem";[io.compression.zipfile]::ExtractToDirectory("%Source%", "%Destination%");}'; Write-Host $pscmd;
I'm very open to a number of variations that can get this to work, provided that this task runs on the command line, uses Powershell, and can be executed from a .cmd file, which is triggered by our app's build process. I'll be happy to provide additional information if needed. Thanks!
This was a strange one. Your code above has some sort of hidden character in it. I took the code and opened it in notepad, saved as ANSI, and when you type it to command line or open it again in a new instance of notepad you can see the error.
Neither add-type nor ExtractToDirectory give output, so I removed your pscmd var.
I would open your existing script, save as ansi as a new file name, delete the original, rename the new one back to the original name.
Here is what I came up with to troubleshoot your script, and it works on my machine.
I named my script L:\util\unzip.cmd
setlocal
//%1% is a passed in command line argument for the absolute path, e.g. C:\path\to\dir
set _Source='%1\directory.zip'
set _Destination='%1\directory'
echo _Source=%_Source%
echo _Destination=%_Destination%
set _c1=Add-Type -assembly system.io.compression.filesystem;
set _c2=[io.compression.zipfile]::ExtractToDirectory(%_Source%, %_Destination%)
echo _c1=%_c1%
echo _c2=%_c2%
set _Command=^& {%_c1% %_c2%};
: to echo, use double quotes or cmd thinks text after & is another command
echo _Command="%_Command%"
pause
powershell -Command "%_Command%"
endlocal
I ran it like this, and it worked: unzip.cmd L:\util
I'll bet this this info, you are good to go.
We can use setx as discussed here.
setx PATH "%PATH%;C:\Something\bin"
But this command can just make changed to user PATH variable not the system one.
How can we make a similar system wide command?
Type setx /? to get basic command help. You'll easily discover:
/M Specifies that the variable should be set in
the system wide (HKEY_LOCAL_MACHINE)
environment. The default is to set the
variable under the HKEY_CURRENT_USER
environment.
You need to run this from an elevated command prompt. Right-click the cmd shortcut and select Run as Administrator.
E.g.
setx /M PATH "%PATH%;C:\Something\bin"
Caution:
We may destroy the current system's PATH variable. Make sure you backup its value before you modify it.
From powershell
setx /M PATH "$($env:path);c:\program files\mynewprogram"
Solution when dealing with a >1024 char path:
None of the other answers worked in my case, but using pathed did the trick. You can append to path as simply as this:
pathed /append C:\Path\To\Be\Added /machine
You can check if the edit happened correctly by running
pathed
PS: if you want to change the user's path instead use:
pathed /append C:\Path\To\Be\Added /user
and pathed /user to check if it went through correctly.
PPS: In order to be able to run pathed from terminal, you need to put the exe in a directory already on your path (or add a new directory to path, but then you you might need to open a new instance of cmd.exe in order for the new path to be recognized)
One problem with %PATH%, is it includes the user's path. If you don't mind Powershell, you can run the following
$p = [Environment]::GetEnvironmentVariable("PATH", [EnvironmentVariableTarget]::Machine);
[Environment]::SetEnvironmentVariable("PATH", $p + ";C:\MyPath", [EnvironmentVariableTarget]::Machine);
If you want to add some location to the PATH environment variable on user level, use the following on the command line:
setx PATH ^%PATH^%;"C:\Program Files\Something\bin"
Why the strange syntax?
First, you do not want to expand the system PATH variable but keep it as a symbol, otherwise you will not participate in future additions to the system PATH variable. Therefore, you have to quote the % characters with ^.
If you use this in a command script, you have to use double %% instead of ^%.
The " encloses a string that contains spaces. If you do not have spaces, you can omit the quotes.
The added string has to follow directly without space so the whole thing forms a single argument to the setx command.
Please refer to Adding a directory to the PATH environment variable in Windows
append_user_path.cmd
append_system_path.cmd
- both work just fine
Take an excruciatingly simple batch file:
echo hi
pause
Save that as test.bat. Now, make a shortcut to test.bat. The shortcut runs the batch file, which prints "hi" and then waits for a keypress as expected. Now, add some argument to the target of the shortcut. Now you have a shortcut to:
%path%\test.bat some args
The shortcut runs the batch file as before.
Now, run the shortcut as administrator. (This is on Windows 7 by the way.) You can use either right-click -> Run as Administrator, or go to the shortcut's properties and check the box in the advanced section. Tell UAC that it's okay and once again the shortcut runs the batch file as expected.
Now, change the arguments in the target of the shortcut to add double quotes:
%path%\test.bat "some args"
Now try the shortcut as administrator. It doesn't work this time! A command window pops up and and disappears too fast to see any error. I tried adding > test.log 2>&1 to the shortcut, but no log is created in this case.
Try running the same shortcut (with the double quotes) but not as Administrator. It runs the batch file fine. So, it seems the behavior is not because of the double quoted parameters, and it's not because it's run as Administrator. It's some weird combination of the two.
I also tried running the same command from an administrator's command window. This ran the batch file as expected without error. Running the shortcut from the command window spawned a new command window which flashed and went away. So apparently the issue is caused by a combination of administrator, the shortcut, and the double quotes.
I'm totally stumped, does anyone have any idea what's going on? I'd also like a workaround.
I just ran Process Monitor on this and here is what I saw:
Run as User:
cmd /c ""C:\Users\Sunbelt\Desktop\test.bat" "some args""
Run as Admin:
"C:\Windows\System32\cmd.exe" /C "C:\Users\Sunbelt\Desktop\test.bat" "some args"
For some reason, the Run as Admin case is not quoting the entire command. It seems it is trying to run the command:
C:\Users\Sunbelt\Desktop\test.bat" "some args
I would guess that since the first space is quoted it actually trying to run the following command:
"C:\Users\Sunbelt\Desktop\test.bat some" args
And in Process Monitor logs there is a file system entry of "NO SUCH FILE" for "C:\Users\Sunbelt\Desktop\test.bat some". I don't know why it is different when run as Admin, but that's what appears to be happening.
To work around this, create another bat file on a path without spaces, and with a filename without spaces, that simply does this:
call "Long path to original bat file\Original bat file.bat"
This secondary bat file can be run as admin.
You can now create a shortcut to this secondary bat file and check run as admin in the shortcut's advanced options. The shortcut can be placed on a path with spaces and it can have a filename containing spaces.
In my case I just want to pass one filename as parameter, but the path has spaces.
I found a solution that worked for this case (if that's okay to truncate the file name).
Create another bat file (input_gate.bat) to remove the spaces in the path using the syntax of CALL.exe.
Assuming that the shortcut is named test.lnk and is on the same route as the input_gate.bat:
call %~sdp0test.lnk %~sf1
This pass as a parameter to test.bat the full file name in short format, with administrator privileges.
%~sdp0 -> Is the current path (for the input_gate.bat) in short format.
%~sf1 -> Is the first parameter passed to input_gate.bat (in my case the full filename with spaces)
This worked for me in Windows 7:
ShortcutTarget: C:\Windows\System32\cmd.exe /C myscript.bat Param1 "Param Two with spaces"
StartIn: "C:\Path containing\my script"
Not tried it yet as Admin. I don't think it would work if myscript.bat contained spaces
I finally figured it out, in a way that allows the use of long filenames (short filenames weren't adequate for my use case). My solution works on Win 7, 8, and 10. I think it was inspired by Luke's mention of the missing double-quote.
Here it is:
1.) For the shortcut you create to the batch file, which you set to run as admin, use the following command line:
cmd /s /c ""path_to_batch_file"
Note that there are 2 double-quote characters at the beginning of the command, and only 1 at the end, even though there should normally be 2 at the end also. But that is the trick in getting it to work!
2.) In your batch file, add back the missing double-quote character:
set user_file=%1"
That's it! Here's an example to let you see it in action:
1.) On your desktop, create "test.bat" with the following content:
#echo off
set user_file=%1"
echo The file is: %user_file%
pause
3.) Create a shortcut to the batch file. Set it to run as admin, and give it the following command line:
cmd /s /c ""%userprofile%\desktop\test.bat"
4.) Drag a file onto the shortcut. Success! (I hope...)
Answer here worked for me: https://superuser.com/questions/931003/passing-variables-with-space-to-the-command-line-as-admin
Which is...
Adding cmd /C before the target.
I also had to make sure my script's name and path didn't have spaces, and not quote the script's path in target.