CIO Resources and Information from TechTarget 09月29日
PowerShell配置文件详解
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

PowerShell配置文件是每次启动PowerShell时运行的脚本,用于自定义环境。本文介绍了配置文件的概念、位置、如何访问以及如何添加实用功能,如操作系统感知、自定义提示、模块加载、版本管理、安全功能和别名等,以提升工作效率和避免潜在问题。

💻 PowerShell配置文件是每次启动PowerShell时运行的脚本,用于自定义环境,包括设置环境变量、别名、函数等,提升工作效率。

🌍 配置文件的位置取决于PowerShell版本、用户类型和主机应用程序,如ISE或VS Code,用户可以通过`$Profile`变量访问不同位置的配置文件。

🔧 用户可以通过在配置文件中添加条件语句来根据操作系统执行不同命令,例如使用`$IsWindows`、`$IsLinux`和`$IsMacOS`变量来判断当前运行环境。

📈 自定义提示功能允许用户在命令提示符中显示更多信息,如当前路径、用户身份(管理员或root)等,通过修改`Prompt`函数实现。

🔒 配置文件是启用安全功能的好地方,例如预配置JEA会话、解锁秘密保险库、启用会话记录等,以增强脚本执行的安全性。

🚀 用户可以在配置文件中添加别名和参数自动完成功能,如将`Get-MgUser`缩写为`gmu`,或为`kubectl`设置别名并启用自动完成。

🔄 配置文件可用于管理PowerShell模块的版本,通过在启动时运行`Update-PSResource`或`Update-Module`命令,确保常用模块保持最新状态。

<p>If you run the same commands every time you launch the PowerShell console, consider modifying your PowerShell profile for a better overall experience.</p><div class="ad-wrapper ad-embedded"> <div id="halfpage" class="ad ad-hp"> <script>GPT.display('halfpage')</script> </div> <div id="mu-1" class="ad ad-mu"> <script>GPT.display('mu-1')</script> </div> </div> <p>The PowerShell profile loads your settings whenever you launch PowerShell to customize the environment to your needs. You define your settings as a PowerShell script, making the process straightforward. This article will explain the concepts behind the PowerShell profile, how to edit it for the various PowerShell consoles -- <a href="https://www.techtarget.com/searchwindowsserver/definition/PowerShell"&gt;PowerShell&lt;/a&gt;, Windows PowerShell, Visual Studio Code (VS Code), Integrated Scripting Environment (ISE) -- and several useful additions to incorporate to enhance your workflow and avoid potential issues.</p> <section class="section main-article-chapter" data-menu-title="What is the PowerShell profile?"> <h2 class="section-title"><i class="icon" data-icon="1"></i>What is the PowerShell profile?</h2> <p>The PowerShell profile is simply a PowerShell script that runs every time you launch PowerShell, except when you launch PowerShell with the <b>-NoProfile </b>flag. The location of the profile varies depending on several conditions:</p> <ul class="default-list"> <li>The version of PowerShell (Windows PowerShell vs PowerShell)</li> <li>Is the profile for all users or the current user?</li> <li>Is the profile host application specific? (ISE, VS Code, etc)</li> </ul> <p>The following lists are directories. The names of the profile scripts depend on the host application.</p> <p>For all users, the profile is located here:</p> <ul class="default-list"> <li>Windows PowerShell: $PSHOME\</li> <li>PowerShell:</li> <li>Windows: $PSHOME\</li> <li>Linux: /usr/local/Microsoft/powershell/7/</li> <li>macOS: /usr/local/Microsoft/powershell/7/</li> </ul> <p>For specific users, the profile is located here:</p> <ul class="default-list"> <li>Windows PowerShell: $HOME\Documents\WindowsPowerShell\</li> <li>PowerShell</li> <li>Windows: $HOME\Documents\PowerShell\</li> <li>Linux: ~/.config/powershell/</li> <li>macOS: ~/.config/powershell/</li> </ul> <p>In these directories, you can have several valid profile files. The difference between the profiles is based on the host application that launches PowerShell. For this tutorial, we will use the ISE and VS Code as examples for hosts:</p> <ul class="default-list"> <li>All hosts: profile.ps1</li> <li>ISE: Microsoft.PowerShellISE_profile.ps1</li> <li>VS Code: Microsoft.VSCode_profile.ps1</li> </ul> <p>If a user launches PowerShell in VS Code, the following profiles could run on Windows:</p> <ul class="default-list"> <li>All users, all hosts: $PSHOME\profile.ps1</li> <li>All users, VS Code: $PSHOME\Microsoft.VSCode_profile.ps1</li> <li>Current user, all hosts: $HOME\profile.ps1</li> <li>Current user, VS Code: $HOME\Microsoft.VSCode_profile.ps1</li> </ul> <p>If any of the files don't exist, PowerShell skips that profile.</p></section> <section class="section main-article-chapter" data-menu-title="How to access the PowerShell profile"> <h2 class="section-title"><i class="icon" data-icon="1"></i>How to access the PowerShell profile</h2> <p>The easiest way to access PowerShell's profile is through PowerShell itself. There's no need to remember any of the listed paths because they are all stored in a variable called <b>$Profile</b>.</p> <figure class="main-article-image full-col" data-img-fullsize="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image1-f.jpg"&gt; <img data-src="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image1-f_mobile.jpg" class="lazy" data-srcset="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image1-f_mobile.jpg 960w,https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image1-f.jpg 1280w" alt="A PowerShell command line window shows the location of the PowerShell profile." height="85" width="557"> <figcaption> <i class="icon pictures" data-icon="z"></i>To locate the PowerShell profile, enter the $Profile variable to show the path. </figcaption> <div class="main-article-image-enlarge"> <i class="icon" data-icon="w"></i> </div> </figure> <p>In this case, the username is hidden.</p> <p>You'll notice that the only path displayed is the current user's PowerShell host application profile. Thankfully the <b>$Profile</b> variable has some additional properties to show us the other paths. We can find those properties by piping the variable to <b>Get-Member</b>:</p> <pre class="language-powershell"><code>$Profile | Get-Member -MemberType NoteProperty</code></pre> <figure class="main-article-image full-col" data-img-fullsize="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image2-f.jpg"&gt; <img data-src="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image2-f_mobile.jpg" class="lazy" data-srcset="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image2-f_mobile.jpg 960w,https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image2-f.jpg 1280w" alt="A PowerShell command line window shows the properties of the $Profile variable." height="129" width="560"> <figcaption> <i class="icon pictures" data-icon="z"></i>Use the Get-Member cmdlet to find the properties associated with the $Profile variable. </figcaption> <div class="main-article-image-enlarge"> <i class="icon" data-icon="w"></i> </div> </figure> <p>Therefore, if we want to find the path for the AllUsersAllHosts profile, we can do so with:</p> <pre class="language-powershell"><code>$Profile.AllUsersAllHosts</code></pre> <p>On our system, the result is C:\Program Files\PowerShell\7\profile.ps1 for the path. Because the file is in the Program Files hierarchy and we can't edit that without administrative permissions, let's instead focus on the CurrentUserCurrentHost profile with:</p> <pre class="language-powershell"><code>$Profile.CurrentUserCurrentHost</code></pre> <figure class="main-article-image full-col" data-img-fullsize="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image3-f.jpg"&gt; <img data-src="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image3-f_mobile.jpg" class="lazy" data-srcset="https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image3-f_mobile.jpg 960w,https://www.techtarget.com/rms/onlineimages/ahowell_psprofile_image3-f.jpg 1280w" alt="A PowerShell command line window shows the location of the CurrentUserCurrentHost profile script." height="130" width="559"> <figcaption> <i class="icon pictures" data-icon="z"></i>Find the location of the CurrentUserCurrentHost profile script. </figcaption> <div class="main-article-image-enlarge"> <i class="icon" data-icon="w"></i> </div> </figure> <p>If we want to edit that script, we can call VS Code directly:</p> <pre class="language-powershell"><code>code $Profile.CurrentUserCurrentHost</code></pre> <p>This will launch VS Code and open that file.</p></section> <section class="section main-article-chapter" data-menu-title="Ideas of things to add to your profile"> <h2 class="section-title"><i class="icon" data-icon="1"></i>Ideas of things to add to your profile</h2> <p>Since the profile is so flexible, you could do many different things with it. Let's look at a few that I've found useful over the years.</p> <h3>Add OS awareness to profile</h3> <p>Not all commands work the same way across the OSes that PowerShell supports, so we need logic to separate different commands. Fortunately, PowerShell makes this very easy with some built-in variables that will all exist cross-platform:</p> <ul class="default-list"> <li>$IsWindows is true when running on Windows</li> <li>$IsLinux is true when running on Linux</li> <li>$IsMacOS is true when running on MacOS</li> </ul> <pre class="language-powershell"><code>if ($IsWindows) {&nbsp;&nbsp;&nbsp; # do Windows stuff} elseif ($IsLinux) {&nbsp;&nbsp;&nbsp; # do Linux stuff} elseif ($IsMacOS) {&nbsp;&nbsp;&nbsp; # do MacOS stuff}</code></pre> <p>The following suggestions will contain some examples of how to write profile code for multiple platforms.</p> <div class="btt-thumbnailContainer"> <span class="btt-thumbnailTitle">How to find and customize your PowerShell profile</span> <a class="btt-thumbnailLink" data-video-id="652455" data-channel-id="18865"> <div class="btt-thumbnailImgContainer"> <img class="btt-videoBtThumbnail" src="https://cdn.brighttalk.com/ams/california/images/communication/652455/image_1059040.png?width=640&amp;amp;height=360"&gt; </div></a> <time class="btt-video-duration" datetime="PT5M59S">5:59</time> </div> <div class="btt-modal"> <div class="btt-modal-content"></div> </div> <h3>Customize your prompt</h3> <p>PowerShell allows you to run a script every time the prompt loads, which is every time you run a command. If you aren't already familiar with customizing your prompt, I highly encourage you to do additional research to see some cool prompts folks have blogged about. This article will only cover a very basic example.</p> <p>For instance, if we wanted to place the cursor on the line below the path and display the # symbol if we are running as administrator on Windows or as root on Linux, we could do something like:</p> <pre class="language-powershell"><code>Function Prompt {&nbsp;&nbsp;&nbsp; $endChar = '&gt;'&nbsp;&nbsp;&nbsp; # check if running as admin&nbsp;&nbsp;&nbsp; if ($IsWindows) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; If (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $endChar = '#'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp; } elseif ($IsLinux) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if ((id -u) -eq 0) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $endChar = '#'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp; "$PWD`nPS$endchar"}</code></pre> <p>Since we want this to run every time PowerShell loads, put it in your profile.</p> <h3>Load a PowerShell module and set default properties</h3> <p>A mistake I regularly make is to use a module that requires authentication before authenticating. Some modules are slick and remind you to authenticate, while others throw a cryptic error. Regardless, if it is a module you use frequently, consider adding the authentication steps to your profile.</p> <p>Let's <a href="https://www.techtarget.com/searchwindowsserver/tip/Whats-new-in-Microsoft-Graph-PowerShell-v2"&gt;use the Microsoft.Graph module</a> as an example. It allows you to authenticate using cached credentials, so, assuming you have previously authenticated, you can simply add the following to your profile:</p> <pre class="language-powershell"><code>Connect-MgGraph</code></pre> <p>Though one of the quirks of the Microsoft.Graph.Users module is that returning multiple properties of users requires specifying even the default properties. We can work around this by building a variable in our profile:</p> <pre class="language-powershell"><code>$graphUserProps = @(&nbsp;&nbsp;&nbsp; 'BusinessPhones',&nbsp;&nbsp;&nbsp; 'DisplayName',&nbsp;&nbsp;&nbsp; 'GivenName',&nbsp;&nbsp;&nbsp; 'Id',&nbsp;&nbsp;&nbsp; 'Mail',&nbsp;&nbsp;&nbsp; 'PreferredLanguage',&nbsp;&nbsp;&nbsp; 'Surname',&nbsp;&nbsp;&nbsp; 'UserPrincipalName')</code></pre> <p>And then whenever we need additional properties for a Graph user, we can reference that variable and add additional properties:</p> <pre class="language-powershell"><code>Get-MgUser -UserId &lt;upn&gt; -Select ($graphUserProps + 'AccountEnabled','UsageLocation')</code></pre> <h3>Manage PowerShell module versions</h3> <p>If you have a particular module that you want to keep up to date, you can run version checks in your profile or run the Update-PSResource or Update-Module command on every launch. Since you may end up managing many modules or modules that are large themselves, we could initiate this part of the profile in a ThreadJob:</p> <pre class="language-powershell"><code>$modulesToUpdate = @('az', 'microsoft.graph')$null = Start-ThreadJob -Name "Update modules" -ArgumentList $modulesToUpdate {&nbsp;&nbsp;&nbsp; param([string[]]$modulesToUpdate)&nbsp;&nbsp;&nbsp; foreach ($module in $modulesToUpdate) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Update-PSResource -Name $module -Force -Confirm:$false&nbsp;&nbsp;&nbsp; }}</code></pre> <p>Since this example <a href="https://www.techtarget.com/searchwindowsserver/tutorial/Try-these-PowerShell-Start-Job-examples-for-more-efficiency"&gt;runs as a ThreadJob</a>, the modules will update in the background without slowing your profile.</p> <h3>Add security features</h3> <p>Since your PowerShell profile will load every time you run, this is a great place to enable some security features.</p> <p>For example, if <a href="https://www.techtarget.com/searchwindowsserver/tutorial/PowerShell-7-remoting-expands-management-horizons"&gt;your organization uses Just Enough Administration (JEA),</a> you can pre-emptively set up some JEA sessions:</p> <pre class="language-powershell"><code>$jeaDcSession = New-PSSession -ComputerName 'DC01' -ConfigurationName 'JEA_DC'Import-PSSession -Session $jeaDcSession -Prefix 'JEADC'</code></pre> <p>Then, if you wanted to see what commands were imported, you could run:</p> <pre class="language-powershell"><code>Get-JEADCCommand</code></pre> <p>Another use case is for unlocking secret vaults. If you <a href="https://www.techtarget.com/searchwindowsserver/tutorial/Working-with-PowerShell-Secret-Management-and-Secret-Vault"&gt;use the Secrets Management module</a>, you can unlock your most-used vault in your profile:</p> <pre class="language-powershell"><code>Unlock-SecretVault -Name VaultName -Password (Read-Host -AsSecureString)</code></pre> <p>However, this will prompt you for the vault password on every run.</p> <p>If your infosec team requires you to log all your PowerShell activity for ingestion into your company's SIEM, you could even add transcript logging to your profile:</p> <pre class="language-powershell"><code>Start-Transcript -OutputDirectory C:\Path\To\SIEM\Directory</code></pre> <h3>Adding aliases and argument completers</h3> <p>Another excellent use case for the PowerShell profile is adding aliases. If you work a lot in PowerShell interactively, then aliases can save quite a bit of typing. If we go back to the previous Microsoft.Graph example, you could shorten <b>Get-MgUser</b> to <b>gmu</b>:</p> <pre class="language-powershell"><code>New-Alias -Name gmu -Value Get-MgUser</code></pre> <p>However, one of my favorite aliases is for the Kubernetes command line tool kubectl. I alias it to the letter k:</p> <pre class="language-powershell"><code>New-Alias -Name k -Value kubectl</code></pre> <p>Kubectl <a target="_blank" href="https://kubernetes.io/docs/tasks/tools/install-kubectl-windows/#enable-shell-autocompletion" rel="noopener">includes</a> a PowerShell argument completer -- the function that offers dynamic hints for parameter values for commands to speed up coding. If <a href="https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/compare-Kubernetes-kubectl-vs-kubelet-when-to-use"&gt;you use kubectl</a> a lot, that is an excellent addition to your profile.</p> <h3>Load custom functions</h3> <p>A lot of times, you may find yourself writing one-off functions to help with your work. They may not feel worth adding to a module, but they help you get your work done. So after you have them in source control, your profile can dot-source them all to load them when you load PowerShell:</p> <pre class="language-powershell"><code>. C:\path\to\Function.ps1</code></pre> <h3>Apply environment awareness</h3> <p>If you have hosts with standard names or an easy way to identify what environment a host is in, you can make environment-aware adjustments to PowerShell. For example, you could force the background to be red when you are in production.</p> <pre class="language-powershell"><code>if ($IsWindows) {&nbsp;&nbsp;&nbsp; if ($env:COMPUTERNAME -like 'prod-*') {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; $Host.UI.RawUI.BackgroundColor = 'DarkRed'&nbsp;&nbsp;&nbsp; }}</code></pre> <p>Or you could even update the window title, giving another layer of warning:</p> <pre class="language-powershell"><code>$Host.ui.RawUI.WindowTitle = "POWERSHELL in PRODUCTION"</code></pre> <h3>Ways to sync a PowerShell profile</h3> <p>Once you've perfected your profile, you won't see those customizations when you hop onto another system. To solve that, we can introduce some profile synchronization.</p> <p>A common and easy fix is to use a file-syncing application, such as OneDrive. Be sure to enable the Documents folder redirection to sync your profile. If you do this, also be aware that your modules will also be synced, which could introduce latency unless you configure your Documents folder to be stored locally on your device. Whenever you import a module, OneDrive will download the files associated with the module.</p> <p>A better approach would be to store your profile in a place that is easily accessible. If you work in a corporate environment, this could be on a file server or even an Azure File share. Then, any time you launch PowerShell on a new machine, you just need to copy the profile onto your local system:</p> <pre class="language-powershell"><code>Copy-Item Z:\share\home\profile.ps1 ~\Documents\PowerShell\Profile.ps1</code></pre> <p>This approach also has the advantage of being supported on servers where installing an application such as OneDrive is prohibited.</p> <p>Another method is to use a GitHub <a target="_blank" href="https://docs.github.com/en/get-started/writing-on-github/editing-and-sharing-content-with-gists/creating-gists" rel="noopener">gist</a> to make the profile available for download. Gists are publicly available, so only use this method if your profile contains no private information, such as information about your internal environment.</p> <p>An excellent example of using a gist to sync your PowerShell profile is the from Steve Lee, the principal software engineer manager of the PowerShell development team from Microsoft. <a target="_blank" href="https://gist.github.com/SteveL-MSFT/a208d2bd924691bae7ec7904cab0bd8e" rel="noopener">His profile</a> uses a comment to identify the published version:</p> <pre class="language-powershell"><code># Version 1.2.13</code></pre> <p>He also includes logic that compares the version in the local profile with the public version. If the public profile version is greater, then the profile will be downloaded and made available the next time PowerShell launches.</p> <p>The following code downloads a PowerShell profile from a gist and saves it as the local PowerShell profile.</p> <pre class="language-powershell"><code>$gist = Invoke-RestMethod https://api.github.com/gists/a208d2bd924691bae7ec7904cab0bd8e$gist.files."profile.ps1".content | Out-File ~\Documents\PowerShell\Profile.ps1</code></pre> <p>These are just a few examples of how to customize your PowerShell profile. Experiment with some of these suggestions and incorporate them to optimize and simplify your workflow when working with this automation tool.</p> <p><i>Anthony Howell is an IT strategist with extensive experience in infrastructure and automation technologies. His expertise includes PowerShell, DevOps, cloud computing, and working in both Windows and Linux environments.</i></p></section>

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

PowerShell 配置文件 自定义环境 操作系统感知 自定义提示 模块管理 安全功能 别名 参数自动完成
相关文章