Change directory in PowerShell - 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'

Related

Open all files with a certain extension in Powershell

On Linux if I am in a directory and I want to open all .py files with an application (such as atom), I would simply type atom *.py and then all .py files will open with atom. If I type the same thing in Powershell, I receive an error, so I assume the syntax is different on Powershell. How would I accomplish this with Powershell?
Sorry if this is a very beginner question, its my first time using Powershell.
Collect the files you want to open first, then pipe them to the call of your external program:
Get-ChildItem -Path .\* -Include *.py | ForEach-Object {Start-Process -FilePath atom.exe -ArgumentList "`"$($_.FullName)`""}
Adjust the path to your external program if needed and also the the argument list (named arguments instead positional for example). Through the special quoting, this statement is prepared to even handle filenames with spaces.
If this line is to long for your *nix background, you can shrink it to:
gci *.py|%{start atom "`"$($_.FullName)`""}
Try this:
& "Full path of atom.exe" #("*.py")
If atom is set as the default for items with the .py extension you could run gi *.py. Assuming this is not the case i'd right some function as part of a profile script to do this:
$AtomPath = "Path\To\Atom.exe"
function openWithAtom{
Get-ChildItem -Path .\* -Include $args[0] | ForEach-Object {Start-Process -FilePath $AtomPath -ArgumentList "`"$($_.FullName)`""}
}
new-item alias:atom -value openWithAtom
then you would run it with this: atom *.py, or atom filename.py
This tutorial should help with seting up a profile https://www.howtogeek.com/126469/how-to-create-a-powershell-profile/
Also if you haven't already id style your window so it looks more like a terminal.

PowerShell - Restore directory of script location while being ran as administrator

My Situation:
I have to run a PowerShell script as Administrator (because of accessing a privileged folder) and my script is also referencing files in the same directory as the script. I need to use a relative file path but I can't due to PowerShell switching the directory to C:\WINDOWS\system32 when ran as admin.
In PowerShell, is there a way to restore the directory to the current directory that the script is located?
My Script: (will be ran as admin)
Copy-Item -Path .\file1.txt -Destination 'C:\Users\privileged_folder'
Directory Structure:
MyDir\
file1.txt
myscript.ps1 <- ran as admin
By Changing Location
In your script, you can set the location to the script folder. From within your script, either of the following techniques will work:
# PowerShell 3+
cd $PSScriptRoot
# PowerShell 2
cd ( Split-Path -Parent $MyInvocation.MyCommand.Definition )
Changing to $PSScriptRoot works in all currently supported versions of PowerShell, but using Split-Path to get the script directory is useful if you for some reason still have nodes running PowerShell 2.
If you want to change back to the previous directory after your script is done executing (probably a good move) you can also make use of Push-Location and Pop-Location instead of cd or Set-Location:
# Also aliased to pushd
Push-Location $PSScriptRoot
# My script stuff
# Also aliased to popd
Pop-Location
These two cmdlets treat locations as a stack - Push-Location changes your location and adds the directory to the location stack while Pop-Location will remove the current directory from the stack and return you to the previous location. It works much like push and pop operations on arrays.
By Prefixing the Relative Paths
You could also prefix your relative paths in your script with either $PSScriptRoot or ( Split-Path -Parent $MyInvocation.MyCommand.Definition ) as shown in the previous section. If we attach the prefix to the otherwise relative path of file1.txt:
$filepath1 = "${PSScriptRoot}\file1.txt"
Now you have an absolute path to file1.txt. Note that this technique will work with any relative path to $PSScriptRoot, it does not have to be in the same folder as your ps1 script.

Dot Slash and Backslashes in PowerShell Cross-Platform

I'm writing PowerShell scripts which call other PowerShell scripts with & .\other\script.ps1 but the backslash \ is, I assume, a Windows thing and I want my scripts to work cross-platform.
I've noticed that PowerShell in Windows does accept & ./other/script.ps1 but that may be accidental. Is PowerShell ALWAYS gonna translate my backslashes to the host platform?
What is the best approach to handling path seperators cross-platform in PowerShell?
In my experience Windows PowerShell is happy to accept either \ or / as a path separator so one way to be cross-platform is to always use /.
Alternatively you can use the Path cmdlets to handle building paths for you, for example:
Join-Path -Path $Pwd -ChildPath (Join-Path -Path 'Other' -ChildPath 'script.ps1')
Or to get the path for a file in the current directory:
Resolve-Path test.txt
Path cmdlets:
~> get-command *-path* | Select Name
Name
----
Convert-Path
Join-Path
Resolve-Path
Split-Path
Test-Path
I don't have enough credit to add a comment to the accepted answer by #mark-wragg but I just want to point out I started using forward slashes only in cross-platform scripts etc and hit a problem with symbolic links.
As an example, run
new-item -itemtype SymbolicLink -path TestScript8.ps1 -target ./TestScript.ps1
and you will not be able to open TestScript8.ps1 in VS Code on Windows.

path as parameter powershell

I have problem with path. I need to copy all files from directory I add as 1st parameter in Powershell command.
Now I have:
Copy-Item -Path "$args[0]/" -Filter*.*
So it will copy to location I am now (and it's ok, I don't want other location) but it doesn't copy anything. Please help.
Pretty sure the issue is that the 0 element in $args is not expanding in the string creating an invalid path. Wrap the variable in $() to allow it to expand inside a double quoted string. Else you would end up trying to copy the folder C:\TEST[0]/ which obviously is not correct.
Copy-Item -Path "$($args[0])/" -Filter *.* -Recurse
Not yet sure why you have a forward slash in there since Windows pathing uses backslashes.
function Copy-Something(){
test-Path "$($args[0])/"
test-path "$($args[0])"
}
Copy-Something C:\temp
With what little you have provided the output shows that it might be redundant to have the slash there. Would also recommend calling Test-Path on the argument anyway as it might have caught this for you.
True
True
From Question Comment
You are looking for the -Recurse parameter if you also want folder contents.
From Answer Comment
If you want the contents and not the folder you should be able to do something like this:
Copy-Item -Path "$($args[0])\*" -Filter *.* -Recurse
When in doubt, Get-Help Command.
PS C:\> Get-Help Copy-Item -ShowWindow
-------------------------- EXAMPLE 3 --------------------------
This command copies the contents of the C:\Logfiles directory
to the C:\Drawings\Logs directory. It creates the \Logs
subdirectory if it does not already exist.
Windows PowerShell
PS C:\> Copy-Item C:\Logfiles -Destination C:\Drawings\Logs -Recurse

Powershell: how to assign path in the beginning of a script

As a beginner: How can I place a path to folder in Powershell script? I would like to hard-code a path to a folder where the rest of the script would do some data munging. How to do that?
Do you mean?
$path = "C:\Windows"
Get-ChildItem $path
This will let you reference path in cmdlet parameters.
As per your comment:
Set-Location C:\Windows
will change working directory of the script to C:\Windows