컴퓨터 & IT (Computer & IT)/Windows and Powershell

[PowerShell] Prompt에 현재 폴더 이름만 표기하기

UltraLowTemp-Physics 2022. 2. 19. 18:14

Powershell을 사용하다보면, prompt 상에서 현재 자신의 폴더 이름이 상위 폴더 이름을 포함하고 있는 경우가 많다. 이런 부분들은, powershell을 사용할 때, 사실 굉장히 많은 불편함을 초래한다. 따라서, 사용 상 편의를 위해, 상위 폴더들을 제외한 현재 폴더 이름만 powershell prompt에 표기하길 원한다. 따라서, 이번 포스트에선, 현재 폴더 이름만 powershell prompt에 나오도록 설정하는 방법을 작성하였다 [1]. 


 1. 현재 상태

현재 이 글을 읽고 있는 사람들의 powershell을 보면 아래와 같을 것이다;

PS C:\Users\"User-name"\"folder-name">

위와 같은 prompt를 이후 최종적으로 아래와 같이 변경되도록 설정할 것이다. 

PS "folder-name">

 

2. 설정 파일

위와 같은 변경을 위해선, 사용자의 powershell 설정 파일을 변경해야 한다. 사용자의 powershell 설정 파일은 일반적으로 아래의 위치에 존재한다. 

1) window powershell 설정 파일의 위치 

c:\Users\"user-name"\Documents\WindowsPowerShell\profile.ps1

위 profile.ps1 파일을 연 후, 아래 코드를 추가한다.

function prompt {
	$p = Split-Path -leaf -path (Get-Location)
	"PS $p> "
}

이후 Powershell을 재시작하면, 위에서 언급한 것처럼 prompt에 현재 폴더만 나타나게 된다. 


3. Troubleshot (2023-01-06)

윈도우 11을 설치 후, powershell의 설정을 변경하려 시도를 하였는데 몇 가지 문제점이 있었다.

1) 기본 profile 설정 파일의 $home/Documents/WindowsPowerShell/에 위치해있는 것이 아닌 $home/Documents/Onedrives/WindowsPowerShell/에 위치하는 것이었다.
2) 설정 파일이 권한 문제로 제대로 실행되지 못했다.

이에 대한 해결책들은 아래와 같다. 

1) 아래와 같이 profile 위치를 powershell을 실행 후 변경한다. 

PS $profile="$home/Documents/WindowsPowershell/Microsoft.PowerShell_profile.ps1"

- 이후부터 설정 파일의 위치는 위에 설정된 위치로 할당된다. 

2) 권한 문제 해결 [2][3]
권한 문제로 인한 오류 메시지는 아래와 같다;  

File C:.../Microsoft.Powershell_profile.ps1 cannot be loaded because running scripts is disabled on
 this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3

 

권한 문제를 해결하기 위해, Powershell을 관리자 모드로 실행한 후, 아래 명령어를 기입한다. 

Set-ExecutionPolicy -ExecutionPolicy unrestricted

 

[1] https://blog.technotesdesk.com/configure-the-windows-powershell-to-display-only-the-current-folder-name-in-the-shell-prompt  
[2] https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.3