Getting the home directory?
I am trying to get a directory from a user's home directory in a script. This is what I'm trying, but ~
interacts as a literal instead of expanding into the home directory. Is there a way to extend it? If not, can I get the home directory in another way?
$mySourceDir = "~/Projects/svn/myProject/trunk" # Single quote also does not expand
cd $mySourceDir
This is using the PS 6 beta on OSX.
source to share
In PowerShell, the most reliable way to reference the user's current home directory is to use an automatic variable $HOME
internally "..."
if it's part of a larger path :
-
$mySourceDir = "$HOME/Projects/svn/myProject/trunk"; Set-Location $mySourceDir
(Set-Location
Equivalent to PowerShellcd
, thanks to the built-in alias definition, you can also usecd
.) -
If you pass a path as an argument to a command, you can get away without the closing
"..."
, depending on what characters the path contains; eg,Set-Location $HOME/Desktop
-
Works on both Windows and Unix platforms , whereas if you try to use environment variables such as
$env:HOME
, the platform differences will look like. -
To find out about all the automatic variables (built-in variables) that PowerShell defines, run
Get-Help about_Automatic_Variables
(from this point$HOME
onwards , the entry reflects only the Windows perspective, but$HOME
works similarly on Unix platforms).
Use ~
only if you are sure that the current location is the location of the filesystem:
-
Current location is a generalized PowerShell concept of the current directory: PowerShell generalizes the drive concept to include other (usually) hierarchical data stores, such as the Windows registry, the directory of all defined functions (drive
Function:
), variables (Variable
), or environment variables (Env:
). -
Each such disk is provided by a disk vendor, of which the [disk vendor] file system is only one instance.
-
~
is a disk centric concept, so using only~
, without explicitly referring to the disk provider, refers to the original location as being determined by the provider underlying the current location .- Some vendors do not provide a default value for the view
~
, causing attempts to use it to fail; for example, this is the case for the providerEnvironment
and its diskEnv:
:Set-Location Env:; Set-Location ~
leads to an errorHome location for this provider is not set. To set the home location, call "(get-psprovider 'Environment').Home = 'path'
- Some vendors do not provide a default value for the view
-
It is a disk vendor that interprets
~
, therefore also works internally and~
'...'
"..."
- From a filesystem location, the following commands work the same:
-
Set-Location ~/Desktop
-
Set-Location "~/Desktop"
-
Set-Location '~/Desktop'
-
- Contrast this with POSIX-like wrappers like
bash
where it is a wrapper that expands~
ahead of the front before the target command sees it, but only if it is not defined.
- From a filesystem location, the following commands work the same:
source to share