I want to go back to my previous location just like what cd - does on most unix shells.
How is this done on windows ?
You don't have cd - natively (cmd, powershell) on windows.
You can either:
1) Have cygwin on your windows and use bash
2) Have Linux subsystem on your Win 10 and use bash there.
3) use pushd on the directory you want to save. Then change somewhere you want.
To return back you just popd
First and Second Edit
There is a my own workaround with Powershell (licence MIT, but have my SO 'nick' there).
It will work the following way:
`cd` ... to list stack of saved directories
`cd -` ... return to previous directory (putting another `cd -` goes further to the history)
`cd +` ... add current directory to the top of the stack
`cd <path>` ... changes the path and puts the previous to the stack
You could put the following code in your Profile.ps1
# to remove default alias
Remove-Item Alias:cd -force
# create a new named stack at your ~ dir
Push-Location ~ -StackName 'RememberPaths'
# create a new cd with stack
function cd_with_stack {
<#
.SYNOPSIS
Change directory (cd)replacement
.DESCRIPTION
Remembers history when changing directories. When directory is changed then it is added to the stack
User can return to the history;
User can force manually adding a directory;
User can view the whole history stack.
.PARAMETER parameter
Can be - ... to return to the historical directory
Can be + ... to add current directory to the stack
Can be empty ... to view the whole stack
Can contain directory path to change it
.EXAMPLE
PS c:\users > cd -
PS c:\ >
PS C:\t> cd
Path
----
C:\t
C:\users\admin
C:\users
C:\Users\tukan
.NOTES
Author:
Tukan #StackOverflow
Version Info:
1.0 - 27/02/2018
- Initial release
.LINK
http://www.ceq.cz
#>
param ([String]$parameter)
switch ($parameter) {
'-' {
If ((Get-location -StackName 'RememberPaths').Count -gt 1) {
popd -StackName 'RememberPaths'
} Else {
# do not empty stack, always keep the first item on stack
Set-Location -Path ((Get-location -StackName 'RememberPaths').Peek().ToString())
}
break
}
'+' {
If ((Get-location -StackName 'RememberPaths').Peek().ToString() -ne (Convert-Path .)) {
pushd -StackName 'RememberPaths'
}
# Else -> no path storing to stack
break
}
'' { get-location -StackName 'RememberPaths'; break }
default {
If (Test-Path -Path $parameter) {
If ((Get-location -StackName 'RememberPaths').Peek().ToString() -eq (Convert-Path .)) {
Set-Location -Path $parameter
} Else {
pushd -Path $parameter -StackName 'RememberPaths'
}
} Else {
Write-Warning "Probably wrong path $parameter"
}
break
}
}
}
# setting new alias for cd
set-alias cd cd_with_stack
Details about commands:
Based on that comment below the question I'm adding this information. Which shows only a partial information.
With the pushd and popd it is important to differentiate when using cmd shell or powershell
In powershell - these two commands are aliases to different commands
PS C:\Users> get-alias -name pushd
CommandType Name ModuleName
----------- ---- ----------
Alias pushd -> Push-Location
PS C:\Users> get-help pushd
NAME
Push-Location
SYNTAX
Push-Location [[-Path] <string>] [-PassThru] [-StackName <string>] [-UseTransaction] [<CommonParameters>]
Push-Location [-LiteralPath <string>] [-PassThru] [-StackName <string>] [-UseTransaction] [<CommonParameters>]
ALIASES
pushd
REMARKS
Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
-- To download and install Help files for the module that includes this cmdlet, use Update-Help.
-- To view the Help topic for this cmdlet online, type: "Get-Help Push-Location -Online" or
go to http://go.microsoft.com/fwlink/?LinkID=113370.
PS C:\Users> get-alias -name popd
CommandType Name ModuleName
----------- ---- ----------
Alias popd -> Pop-Location
PS C:\Users> get-help popd
NAME
Pop-Location
SYNTAX
Pop-Location [-PassThru] [-StackName <string>] [-UseTransaction] [<CommonParameters>]
ALIASES
popd
REMARKS
Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help.
-- To download and install Help files for the module that includes this cmdlet, use Update-Help.
-- To view the Help topic for this cmdlet online, type: "Get-Help Pop-Location -Online" or
go to http://go.microsoft.com/fwlink/?LinkID=113369.
In cmd.exe (or command.com) the pushd and popd are internal commands of the interpreter:
C:\Windows\system32>pushd /?
Stores the current directory for use by the POPD command, then
changes to the specified directory.
PUSHD [path | ..]
path Specifies the directory to make the current directory.
If Command Extensions are enabled the PUSHD command accepts
network paths in addition to the normal drive letter and path.
If a network path is specified, PUSHD will create a temporary
drive letter that points to that specified network resource and
then change the current drive and directory, using the newly
defined drive letter. Temporary drive letters are allocated from
Z: on down, using the first unused drive letter found.
C:\Windows\system32>pushd /?
Stores the current directory for use by the POPD command, then
changes to the specified directory.
PUSHD [path | ..]
path Specifies the directory to make the current directory.
If Command Extensions are enabled the PUSHD command accepts
network paths in addition to the normal drive letter and path.
If a network path is specified, PUSHD will create a temporary
drive letter that points to that specified network resource and
then change the current drive and directory, using the newly
defined drive letter. Temporary drive letters are allocated from
Z: on down, using the first unused drive letter found.
It's true that you do not have cd- natively on Windows.
BUT you can use cd.. to go back one directory.
C:\Users\Acer\cd..
Will send you back to C:Users\ directory.
I know this answer is late, but again may be helpful for someone else.
Thanks!
Related
Good Evening,
New programmer here and the first thing I was told to begin studying was PowerShell and the Command prompt prior to my journey on Python.
While doing some exercises listed in the book I came across the command dir -R, this command listed all files in the folder(s), which made it easier then going to each folder and typing ls.
What is the actual description of this command and why does it list all the files, not just in a straight line but it goes line by line.
I like to understand the basic functions of what I'm learning so I have full understanding, while doing a Google search I could not find a answer.
Thank you in advance.
In Powershell dir is an alias name for Get-ChildItem Cmdlet. You can confirm it by Get-Alias dir
> Get-Alias dir
CommandType Name Version Source
----------- ---- ------- ------
Alias dir -> Get-ChildItem
So dir -R is equivalent to Get-ChildItem -Recurse which will gets the items in the specified locations and in all child items of the locations.
The dir command is just an alias for Get-ChildItem.
So dir -R would be equivalent to Get-ChildItem -Recurse.
If I start a PowerShell as a regular user (not admin) and run
cd Desktop
mkdir test
cd test
git init
cd ..
I then cant delete the folder via PowerShell. I have tried the following commands as admin and as the current user.
rm -r test # -> no access permission
rmdir test # -> no access permission
del -r test # -> no access permission
del test # -> no access permission
It prints
+ CategoryInfo : PermissionDenied: (.git:DirectoryInfo) [Remove-Item], IOException
+ FullyQualifiedErrorId : RemoveFileSystemItemUnAuthorizedAccess,Microsoft.PowerShell.Commands.RemoveItemCommand
But I don't understand why I can't remove folders with a .git folder in them.
In order to remove [a directory that contains] hidden items, PowerShell's Remove-Item cmdlet requires passing the -Force switch:
Remove-Item -Recurse -Force test
The shortest form of this command (for interactive rather than scripting use), using the platform-neutral ri alias and PowerShell's so-called elastic syntax, where it is sufficient to specify a prefix of a parameter name (such as -r for -Recurse), as long as that prefix is unambiguous):
ri -r -fo test
Note how a two-letter prefix is required for -Force, because -f alone is ambiguous: it could also refer to the -Filter parameter.
git init creates a .git subdirectory that is assigned the Hidden attribute on Windows (on Unix-like platforms, the fact that the name starts with . alone makes the directory a hidden one).
On Windows, rm, del, rmdir are simply built-in aliases of Remove-Item, the single cmdlet used to remove both files and directories (removal of the latter requiring -Recurse if the directory is not empty).
(On Unix-like platforms, only del is defined as an aliases, so as not to shadow the platform-native rm and rmdir utilities.)
ri is a platform-neutral alias derived from the name Remove-Item, and therefore preferable.
To see all aliases defined for a given command use Get-Alias -Definition $name; e.g.:
Get-Alias -Definition Remove-Item
Note: While it is arguably beneficial for PowerShell to require explicit opt-in via -Force in order to delete hidden items - so that you don't accidentally delete items whose existence you may not be aware of - the error message is suboptimal, in that the problem isn't one of permissions.
The question seems pretty easy, the method I used below should work but it doesn't:
PS C:\Users\John.Smith\Downloads> rm .\uucode.ps1
PS C:\Users\John.Smith\Downloads> [System.IO.File]::Exists("uucode.ps1")
True
PS C:\Users\John.Smith\Downloads> [System.IO.File]::Exists(".\uucode.ps1")
True
I deleted the file, but it still indicates the file exists. I figured out that it is looking for the file under my home directory (even when "." is specified):
PS C:\Users\John.Smith\Downloads> rm ..\uucode.ps1
PS C:\Users\John.Smith\Downloads> [System.IO.File]::Exists("uucode.ps1")
False
PS C:\Users\John.Smith\Downloads> [System.IO.File]::Exists(".\uucode.ps1")
False
Is this a bug or something? The OS and Powershell version I am using are:
PS C:\Users\John.Smith\Downloads> (Get-WmiObject -class Win32_OperatingSystem).Caption
Microsoft Windows Server 2012 R2 Standard
PS C:\Users\John.Smith\Downloads> $psversiontable.psversion
Major Minor Build Revision
----- ----- ----- --------
5 1 14409 1005
One solution I can think of myself is to find the current directory using pwd, and check if the file supplied to me is if a relative path (not starting with \ or /), and join the current directory with the relative path, but I think there should be an easier way, can you help me?
Is this a bug or something?
No, this behavior is expected.
.NET methods that take relative paths as arguments will resolve them relative to the working directory of the calling process - and powershell.exe doesn't update its current working directory when you navigate between locations inside PowerShell itself:
PS C:\Users\John.Smith> [System.Environment]::CurrentDirectory
C:\Users\John.Smith
PS C:\Users\John.Smith> cd Downloads
PS C:\Users\John.Smith\Downloads> [System.Environment]::CurrentDirectory
C:\Users\John.Smith
You can solve it by only passing rooted file system paths:
PS C:\Users\John.Smith\Downloads> [System.IO.File]::Exists("$PWD\uucode.ps1")
PS C:\Users\John.Smith\Downloads> [System.IO.File]::Exists('C:\Users\John.Smith\Downloads\uucode.ps1')
... or, preferably, just stick to PowerShell's provider cmdlets - when in a FileSystem location, Test-Path -PathType Leaf would be the equivalent of [File]::Exists():
PS C:\Users\John.Smith\Downloads> Test-Path .\uucode.ps1 -PathType Leaf # always correctly resolves path relative to $PWD
If you want PowerShell to always update the current working directory of the host application process, you could do so in the prompt function
$function:prompt = {
# Need to check that we're in the file system - can't set process directory to a registry path for example
if ($PWD.Provider.Name -eq 'FileSystem') {
[System.IO.Directory]::SetCurrentDirectory($PWD)
}
return "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) "
}
I'm a newbie. I am trying to figure out how to use the command line. Please could you tell me what command I should enter so that I can get a list of all the exe files on my computer. thanks.
You can use the dir functionality to search the directory and all of its children directories while filtering on a particular file type.
dir /s /b *.exe | findstr /v .exe.
Source
If you want to find all the executable files that are on the path and/or in the current directory, i.e., all the files you can run from the command line without specifying a path, this should work:
where *.exe
To get names of all .exe files , that are currently running then type tasklist in cmd.
http://ss64.com/nt/tasklist.html
Here's another method I use a lot for tasks like this.
Open powershell and navigate to your root directory by entering the command
cd c:/
cd stands for change directory, and is an alias for the command "Set-Location". We are setting the location to C:/
Next run the following command:
Get-ChildItem -Filter "*.exe" -Recurse
Get-ChildItem is a function that gets the files and folders in a file system drive, and runs on whatever directory you're current at by default.
-Filter "*.exe" is an argument that specifies to only find filenames which end in ".exe". (The * is a type of regular expression notation).
-Recurse is an argument that specifies to search all child directories. This will make your function run on "C:/", but also all child directories of C:/, and all child directories of those directories and so on. This will allow you to search the entire drive.
Suppose I need to navigate to a sub-folder using the wildcard character *. What is the command in cmd/batch script?
Example:
My current directory is c:\Users\Test
I have only one sub-folder as 3
I want to navigate to c:\Users\Test\3
cd * //doesn't work
cd *. * //doesn't work
What is the command to navigate?
You could choose one random/the first directory found by a FOR-Loop
for /d %%A in (*) do cd %%A
Are you sure? This is working in my environment:
PS C:\users\myuser\test> ls
Directory: C:\users\myuser\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 9/18/2013 9:56 AM 3
PS C:\users\myuser\test> cd *
PS C:\users\myuser\test\3>
This would not work if you try to use it in a directory that has multiple sub-directories. For example, my "Documents" folder has multiple subdirectories:
PS C:\users\myUser\documents> cd *
Set-Location : Cannot set the location because path '*' resolved to multiple
containers. You can only the set location to a single container at a time.
Here's what happens when I try to use the wildcard to match for certain incomplete phrases that are specific enough to return a single match:
PS C:\users\myUser\documents> cd boo*
PS C:\users\myUser\documents\Books>
PS C:\users\myUser\documents> cd *ooks
PS C:\users\myUser\documents\Books>