Create a folder alias in PowerShell - powershell

I know that I can create variable that represents a folder path in my profile. For example,
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
Is there an easy way to create an alias to a directory in PowerShell?
Create an alias
PS> Create-FolderAlias -name $foo -path "C:\Program Files"
Create an alias based on another alias
PS> Create-FolderAlias -name $bar -path $foo + "\Microsoft"
Use alias as expected
PS> cd $foo
It would be nice if these aliases would be persisted between sessions.

You can turn a folder into a new powershell drive with New-PSDrive
New-PSDrive foo filesystem 'C:\Program Files'
New-PSDrive bar filesystem 'foo:\Microsoft'
cd foo:
To persist between sessions you could add them to your profile script ($profile).
But of course you can also cd to a folder from a variable
$foo = 'C:\Program Files'
$bar = Join-Path $foo 'Microsoft'
cd $foo

An alternative solution is to write a function that cd's to that directory. For me, this yields the least amount of typing to get where I want. For instance, I put the following function in my profile.ps1:
# quickly cd to folder
function <short name> {
cd <path to directory>
}
Then, in Powershell:
PS> <short name>

I'll just elaborate on #en casa's response and add a concrete example.
Open powershell's equivalent of .bash_profile:
notepad $profile
Add aliases
function code { cd C:\Users\john\code }
function work { cd C:\Users\john\work }
function stuff { cd C:\Users\john\stuff }
Restart PS and type PS> code to get to the code folder.

Related

mkdir vs New-Item , is it the same cmdlets?

I found that there are two different cmdlets : New-Item and mkdir, firstly I was thinking that mkdir is one of aliases of New-Item, but it is not:
Try to get aliases of it, it is md for mkdir and ni for New-Item :
So I am a little bit confused, what the difference between that cmdlets, because powershell reference gives me almost the same pages: mkdir, New-Item
But New-Item is in Microsoft.PowerShell.Management and mkdir in Microsoft.PowerShell.Core , but the do the same(or not?)! Why there are two same cmdlets in powershell?
New-Item is a cmdlet, defined in an assembly, which creates new objects - both files and directories. mkdir is a function which calls New-Item to create directories specifically. It is provided for convenience to shell users who are familiar with Windows CMD or unix shell command mkdir
To see the definition of mkdir use Get-Content Function:\mkdir. You can see that it calls New-Item under the covers, after some parameter and pipeline management. Using PS 5.0:
$wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('New-Item', [System.Management.Automation.CommandTypes]::Cmdlet)
$scriptCmd = {& $wrappedCmd -Type Directory #PSBoundParameters }
Both of the following commands will create a new directory named foo in the root of C:\. The second form is familiar to people coming from other shells (and shorter to type). The first form is idiomatic PowerShell.
PS> New-Item -Path C:\foo -Type Directory
PS> mkdir C:\foo
Because mkdir hardcodes the -Type Directory parameter, it can only be used to create directories. There is no equivalent mkfile built-in function. To create files, use New-Item -Type File, or another cmdlet such as Out-File.

SVN INFO fails in PowerShell when CD'ing into a working copy while spelling the directory name with wrong letter case

When I use Set-Location (aka cd) to change the current directory in a PowerShell window, but deliberately avoid auto-complete and type the name in the "wrong" case...
PS C:\> Set-Location winDOWs
...then Get-Location (aka pwd) will return that "wrong" path name:
PS C:\winDOWs> Get-Location
Path
----
C:\winDOWs
This causes problems with svn info:
PS C:\svn\myDir> svn info --show-item last-changed-revision
2168
PS C:\svn\myDir> cd ..\MYDIR
PS C:\svn\MYDIR> svn info --show-item last-changed-revision
svn: warning: W155010: The node 'C:\svn\MYDIR' was not found.
svn: E200009: Could not display info for all targets because some targets don't exist
As you can see svn info fails when the user doesn't type the name of the working copy directory "myDir" with the correct letter case when cd'ing into it.
Is there a way to solve this? I could not find a suitable parameter of svn info.
Another option could be to overwrite PowerShell's cd alias and make sure the letter case of the typed path is fixed before actually cd'ing, but how to accomplish that? Resolve-Path, for example also returns the "wrong" directory name.
Something like this might work for you:
Set-Location C:\winDOWs\sysTEm32
$currentLocation = (Get-Location).Path
$folder = Split-Path $currentLocation -Leaf
$casedPath = ([System.IO.DirectoryInfo]$currentLocation).Parent.GetFileSystemInfos($folder).FullName
# if original path and new path are equal (case insensitive) but are different with case-sensitivity. cd to new path.
if($currentLocation -ieq $casedPath -and $currentLocation -cne $casedPath)
{
Set-Location -LiteralPath $casedPath
}
This will give you the proper casing for the "System32" portion of the path. You will need to recursively call this piece of code for all pieces of the path, e.g. C:\Windows, C:\Windows\System32, etc.
Final recursive function
Here you go:
function Get-CaseSensitivePath
{
param([System.IO.DirectoryInfo]$currentPath)
$parent = ([System.IO.DirectoryInfo]$currentPath).Parent
if($null -eq $parent)
{
return $currentPath.Name
}
return Join-Path (Get-CaseSensitivePath $parent) $parent.GetDirectories($currentPath.Name).Name
}
Example:
Set-Location (Get-CaseSensitivePath C:\winDOWs\sysTEm32)

Change directory in PowerShell

My PowerShell prompt's currently pointed to my C drive (PS C:\>). How do I change directory to a folder on my Q (PS Q:\>) drive?
The folder name on my Q drive is "My Test Folder".
Unlike the CMD.EXE CHDIR or CD command, the PowerShell Set-Location cmdlet will change drive and directory, both. Get-Help Set-Location -Full will get you more detailed information on Set-Location, but the basic usage would be
PS C:\> Set-Location -Path Q:\MyDir
PS Q:\MyDir>
By default in PowerShell, CD and CHDIR are alias for Set-Location.
(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)
To go directly to that folder, you can use the Set-Location cmdlet or cd alias:
Set-Location "Q:\My Test Folder"
Multiple posted answer here, but probably this can help who is newly using PowerShell
SO if any space is there in your directory path do not forgot to add double inverted commas "".
You can simply type Q: and that should solve your problem.
Set-Location -Path 'Q:\MyDir'
In PowerShell cd = Set-Location
You can also use the sl command to be able to change directories. It is Set-Location but it is much shorter.
Example:
# Too verbose
Set-Location -Path C:\
# Just the right amount of characters to type
sl C:\
If your Folder inside a Drive contains spaces In Power Shell you can Simply Type the command then drive name and folder name within Single Quotes(''):
Set-Location -Path 'E:\FOLDER NAME'
The Screenshot is attached here
On Powershell use Set-Location instead of cd.
Put path in quotes. Single quotes works for me.
Set-Location 'C:\Program Files\MongoDB\Server\6.0'

Setting an alias with attributes in PowerShell

I wanted to set an alias for listing files in the directory, but Set-Alias -name lf -value ls -file does not seem to work. I intend to use this the Unix alias way.
An alias can't do that. From the help for Set-Alias:
You can create an alias for a cmdlet, but you cannot create an alias for a command that consists of a cmdlet and its parameters.
However, using a technique called "splatting", a function can do it easily:
function lf {
ls -file #args
}
For more information, see help about_splatting.
Example 5 from Get-Help Set-Alias -Full is what you want:
Function lsfile {Get-Childitem -file}
Set-Alias lf lsfile
Append to the answer from #mike-z .
You can put the function definition into the PowerShell profile so that you can reuse it opening shell again.
test-path $profile
// Ensure it doesn't exists before creating the profile!
new-item -path $profile -itemtype file -force
notepad $profile
Simply put the code into the file:
function lf { ls -file #args }
You can check the details from official documentation.

Copy directory structure with PowerShell

Is there a way of doing the following in PowerShell?
xcopy \\m1\C$\Online\*.config \\m2\C$\Config-Backup /s
I have tried this:
Copy-Item \\m1\C$\Online\* -Recurse -Destination \\m2\C$\Config-Backup -include *.config
But it does nothing, probably because there are no configuration files in the root. How do I do it?
If you would like to use native PowerShell (with a third party .NET module :P) and also don't want to let long file paths (> 255 characters) halt the copy, you can use this:
# Import AlphaFS .NET module - http://alphafs.codeplex.com/
Import-Module C:\Path\To\AlphaFS\DLL\AlphaFS.dll
# Variables
$SourcePath = "C:\Temp"
$DestPath = "C:\Test"
# RecursePath function.
Function RecursePath([string]$SourcePath, [string]$DestPath){
# for each subdirectory in the current directory..
[Alphaleonis.Win32.Filesystem.Directory]::GetDirectories($SourcePath) | % {
$ShortDirectory = $_
$LongDirectory = [Alphaleonis.Win32.Filesystem.Path]::GetLongPath($ShortDirectory)
# Create the directory on the destination path.
[Alphaleonis.Win32.Filesystem.Directory]::CreateDirectory($LongDirectory.Replace($SourcePath, $DestPath))
# For each file in the current directory..
[Alphaleonis.Win32.Filesystem.Directory]::GetFiles($ShortDirectory) | % {
$ShortFile = $_
$LongFile = [Alphaleonis.Win32.Filesystem.Path]::GetLongPath($ShortFile)
# Copy the file to the destination path.
[Alphaleonis.Win32.Filesystem.File]::Copy($LongFile, $LongFile.Replace($SourcePath, $DestPath), $true)
}
# Loop.
RecursePath $ShortDirectory $DestPath
}
}
# Execute!
RecursePath $SourcePath $DestPath
Please note this code was stripped out of a much larger project of mine, but I gave it a quick test and it seems to work. Hope this helps!
Start-Process xcopy "\\m1\C$\Online\*.config \\m2\C$\Config-Backup /s" -NoNewWindow
:P
The new AlphaFS 2.0 makes this really easy.
Example: Copy a directory recursively
# Set copy options.
PS C:\> $copyOptions = [Alphaleonis.Win32.Filesystem.CopyOptions]::FailIfExists
# Set source and destination directories.
PS C:\> $source = 'C:\sourceDir'
PS C:\> $destination = 'C:\destinationDir'
# Copy directory recursively.
PS C:\> [Alphaleonis.Win32.Filesystem.Directory]::Copy($source, $destination, $copyOptions)
AlphaFS on GitHub
Look into robocopy. It's not a native PowerShell command, but I call it from PowerShell scripts all the time. Works similarly to xcopy only it's way more powerful.