How to change the directory to program files using Powershell?
Unlike command.com/cmd.exe, PowerShell follows much more consistent rules and in the failing case Program and Files\R..bin are parsed as two separate arguments, where the second is invalid in context (as cd only accepts a single non-named argument).
To fix this use quotes, eg.
With the quotes it is parsed as a string value which is supplied as a single argument (the string itself does not include the quotes, again unlike cmd.exe rules).
FWIW, cd is an alias for Set-Location. Run get-help cd for the details on how it can be used — include which optional (and named) parameters it does support.
Как установить каталог PowerShell по умолчанию?
Есть ли способ изменить расположение PowerShell по умолчанию?
Как установить рабочий каталог PowerShell по умолчанию?
11 ответов
Вы можете указать каталог для открытия при запуске PowerShell:
Просто используйте его в своем ярлыке.
Или используйте профиль, чтобы задать начальный каталог.
Создайте профиль PowerShell следующим образом.
Запустите PowerShell от имени администратора и выполните следующую команду:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
Это позволит PowerShell запускать локальные сценарии и сценарии, загруженные из Интернета, которые были подписаны. Дополнительные сведения об этой команде см. В документации .
В папке Documents найдите папку с именем WindowsPowerShell для классической оболочки PowerShell или PowerShell для более новой версии PowerShell Core. Если его не существует, ничего страшного; просто создай это.
Откройте profile.ps1 и добавьте следующую команду, чтобы установить рабочий каталог по умолчанию:
Откройте новое окно PowerShell . изменения должны были вступить в силу.
Это решение устанавливает текущую рабочую папку в то место, где находится скрипт. Обязательно поместите в начало вашего скрипта или, по крайней мере, перед тем, как вы попытаетесь использовать команду, полагающуюся на путь местоположения.
Более простой способ установить каталог по умолчанию:
-
Щелкните правой кнопкой мыши значок Windows PowerShell и закрепите его на начальном экране.
Щелкните правой кнопкой мыши значок Windows PowerShell в меню «Пуск» и снова щелкните правой кнопкой мыши Windows PowerShell и выберите «Свойства» (не Запуск от имени администратора , а не Windows PowerShell ISE ).
- На вкладке Ярлык -> поле «Начать в» перейдите в место, в котором должна запускаться PowerShell.
Сделайте это первой строкой в вашем Profile.ps1, и PowerShell Core (pwsh) откроется в каталоге, в котором вы сейчас работаете:
Установить-расположение (получить-расположение) .path
При этом, похоже, есть некоторая путаница в «рабочем каталоге» и «местоположении» PowerShell. Большинство людей здесь делают и говорят, что нужно изменить «местоположение» PowerShell. «Рабочий каталог» на самом деле другой. Вот статья это объясняет.
Для тех, кто не хочет читать статью: откройте PowerShell и используйте то, что говорят другие Set-Location «C:\some\directory» . Обратите внимание, что ваш «рабочий каталог» по-прежнему находится там, где был открыт PowerShell. Либо «
» , либо «%SYSTEMROOT%\system32» , в зависимости от того, работаете вы как администратор или нет. Чтобы проверить рабочий каталог, используйте [Environment]::CurrentDirectory .
Примечание: в статье автор предлагает проверить «рабочий каталог» с помощью этой команды:
Я не уверен, работает ли это со старыми версиями PowerShell, но с PowerShell 5 (и более поздними версиями) вы должны использовать [Environment]::CurrentDirectory .
Install Software in PowerShell

PowerShell scripting language automates multiple Windows operating system tasks and processes. For example, PowerShell can execute various files like installation files with format MSI or .exe.
This article will demonstrate several methods and approaches to installing Windows PowerShell software.
Install Software in PowerShell
The following are the steps to install software using PowerShell:
Open your Windows PowerShell terminal.
Find the location of the .exe file and change the working directory to this.
Then, use the change directory or cd command to change the current working directory of the console.
Once we have adjusted our working directory, we may run our executable file by calling it to the command line.
However, this method’s caveat would be that it will not suffice if we want to pass specific arguments when installing. Before, we had a legacy command called msiexec executed in the command prompt.
The following section will teach us the similar counterpart to msiexec in Windows PowerShell.
Install Software Using the Start-Process Cmdlet in PowerShell
The Start-Process command can run executable files in Windows PowerShell. The PowerShell cmdlet stated above and the -FilePath parameter takes the complete path of the .exe installation file.
Moreover, the -ArgumentList parameter provides the internal parameters used by the executable file when the installation process starts in Windows PowerShell. Lastly, the -PassThru parameter is used to verify that the command worked as we intended.
Please enable JavaScript
Suppose we want to open an executable file named installer_setup.exe .
Once the above script is executed, Windows PowerShell will run the defined executable file.
Install Software Silently in PowerShell
Running installation software in Windows PowerShell takes advantage of the msiexec legacy command that we usually use to run installation software in the command prompt.
To execute the installation software silently, we must use specific msiexec command parameters and pass them to the -ArgumentList parameter in Windows PowerShell.
- /s : runs the installation in silent mode.
- /v : passes command-line values and public properties options through the Msiexec.exe facility.
- /q : sets user interface level.
- n : interface level of the /q parameter; will run the installation with no graphical user interface.
Combining all of the parameters above in one command is how the PowerShell script should look.
The installation should run in silent mode with no window or wizard prompts by executing the code snippet above.
It is worth noting that both the /v and /qn parameters are executed with no spaces between them because the /qn parameter is executed as a subfunction of the /v parameter.
The above parameters are not the only existing parameters under the msiexec command. You may run the msiexec command in PowerShell for more info.
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
PowerShell change directory

PowerShell change directory is a terminology to navigate the file system through the cmdlets and they are very helpful in the script to work with the current files and folders or the relative path of the files and folders. Various cmdlets are useful for working with current locations, setting up the desired location, keeping the track of the previous location, and storing the locations in the stack and even location can be set for PSDrives like certificates, registry, etc.
Syntax
Hadoop, Data Science, Statistics & others
Below are the cmdlets used for the syntax to change the directory.
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
- Cd command to change the path.
cd -Path DirectoryPath -PassThru
- Set-Location command
Set-Location -Path DirectoryPath -PassThru
- Push-Location Command to push path into Stack.
Push-Location -Path DirectoryPath -PassThru
- Pop-Location command to pop the location from the stack.
Or to retrieve it from the particular stack,
Pop-Location -StackName stack1 -PassThru
How to change the directory in PowerShell?
To change the directory in a PowerShell, we use the various cmdlets. There are the absolute path and relative path in operating systems. Absolute path means the full path of the particular directory, file, or application. For example, C:\Windows\notepad.exe and the relative path means the direct path like Notepad.exe.
An absolute path can be accessed from any directory while the relative path can only accessible from the present directory unless any shortcut is created by the windows OS.
Set-Location command has aliases like (cd, sl, chdir) and we can use this command to change the location to the mentioned directory by using the absolute path or the relative path.
There is another way to change the location using the Push-Location command. When we specify the Push-Location command, PowerShell pushes the current location into the stack and then changes the location to the location specified by the path. Using the Pop-Location command uses the last location from the stack to change location.
By default, Push-Location uses the default stack to push locations but we can create a new stack and add new locations there.
Examples
Here are the following examples mention below
Example #1
Use the “cd” command to change location.
The above command will change the location to the C:\temp.

By default, the path parameter is included when you don’t specify anything. The above command is similar to,
cd -Path C:\Temp\ -PassThru
You can also use chdir or sl alias to set the above path for example.
chdir -Path C:\Temp\ -PassThru
sl -Path C:\Temp\ -PassThru
To change the directory to the previous location, you need to use “..” (double dot) syntax.
cd -Path .. -Passthru
Output:

Example #2
Using Set-Location command.
Although the above-mentioned examples are aliases of the Set-Location command, many scripts generally use the Set-Location command. We have already discussed the set path in the above example. In this example, we will discuss setting up the different PS locations like certificates, registry, etc, and using the stack to change the directory.
You can change the locations to the all below drives.
Output:

To set up the location for the certificate, use the below command.
PS C:\> Set-Location -Path Cert:\
Output:

You can check the current location using the Get-Location command.

You can return to the windows directory by changing the directory using any of the above commands.
Output:

Once you set the location to the certificate, you can browse the certificate paths and auto-completion also works with the TAB button. For example,
and to browse the content of the directory you can use the dir or Get-ChildItem command.
Similarly, to set the registry path for the Local Machine, we can use the below command.
Set-Location -Path HKLM:\SOFTWARE\
Example #3
Navigate location history through ‘+’ or ‘-‘.
PS C:\> Set-Location -Path HKLM:\HARDWARE\
PS HKLM:\HARDWARE\> Set-Location -Path $env:SystemRoot
PS C:\Windows> Set-Location -Path C:\
We have already set the locations as shown above. To navigate back through the history use the ‘-‘ (minus) sign using the Set-Location command.
PS C:\> Set-Location -Path —
PS C:\Windows> Set-Location -Path —
PS HKLM:\HARDWARE\>
To again move into the reverse direction, use the + (plus) syntax.
PS HKLM:\HARDWARE\> Set-Location -Path +
PS C:\Windows> Set-Location -Path +
PS C:\>
Example #4
Change directory using Push-Location command.
You can also change the directory using the Push-Location command. This command first pushes the current location into the stack and then navigates through the provided location. In PowerShell, you can consider the stack means Queue which works in LIFO order (Last In First Out). An example is shown below.
PS C:\> Push-Location C:\Temp\
PS C:\Temp>
In the above example, the Current location is C: and Push-Location saves that location to the default stack (as we haven’t provided stack name) and navigates to the C:\temp location. You can check the location stored in the stack using the below command.
Output:

When you navigate to another location using the Push-Location command,
Check the stack locations again,
Output:

When we use the Pop-Location command the locations will be retrieved in sequential order (LIFO).
To navigate the location using the Push Command with new stack name,
Push-Location C:\Temp\Data\ -StackName Newstack
Check location new stack.
Get-Location -StackName NewStack
Output:

Example #5
Pop-Location command to change directory.
Pop-Location retrieves the last inserted location from the stack. When the stack name is not provided, the default stack is used.
PS C:\Temp\Data> Get-Location -Stack
Output:

When we use the Pop-Location command, C:\temp will be retrieved first and then C:\ in the LIFO order.
PS C:\Temp\Data> Pop-Location
PS C:\Temp> Pop-Location
PS C:\>
To use the Pop-Location command for the different stack,
Pop-Location -StackName Newstack
Conclusion
There are various commands to navigate through the directory and we can directly use them in a console or we can use them in the script as well. They are useful in the script to navigate the path when the script executes.
Recommended Articles
This is a guide to the PowerShell change directory. Here we discuss How to change the directory in PowerShell along with the examples and outputs. You may also have a look at the following articles to learn more –