您的位置:首页 > 运维架构 > Shell

Powershell Profiles配置文件的存放位置介绍

2014-08-08 08:52 801 查看

适用于:Windows PowerShell 2.0, Windows PowerShell 3.0

当我们打开一个PowerShell对话框,并在里面创建一些变量(variables)、函数(functions)时,这些变量、函数均只在当前会话中有效。一旦我们关闭这个对话框重新打开PowerShell时,这些变量都不存在了。如果我们想保留这些设置,我们就需要用到profile,翻译过来就是配置文件。在PowerShell启动的时候,会自动导入配置文件里面的设置。这有点像autorun.bat,如果有dos系统还有印象的朋友,应该知道这个。

配置文件存放于如下几个地方,不同的配置文件,作用域不同。

1、%windir%\system32\WindowsPowerShell\v1.0\profile.ps1
它作用于所有用户、所有的Shell。

2、%windir%\system32\WindowsPowerShell\v1.0\ Microsoft.PowerShell_profile.ps1
作用于所有用户,但只作用于Microsoft.PowerShell这个shell。这个我也没懂是什么意思,难道还有不是PowerShell的PowerShell shell?呃,有点像绕口令。

3、%UserProfile%\My Documents\WindowsPowerShell\profile.ps1
作用于当前用户的所有shell。

4、%UserProfile%\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
作用于当前用户的Microsoft.PowerShell这个shell。

以上的Windows的PowerShell profiles不是自动创建的。言下之意是,如果要用,我们就自己去创建。我们只要按照上面给出的文件路径和文件名,编写我们自己的内容进去即可。

有一个变量:$profile,它保存了当前Profile的路径。使用Test-Path $profile可以查看当前有没有这个文件。如果没有,可以使用new-item -path $profile -itemtype file -force命令来创建它。然后再使用notepad $profile来快捷的打开它来编辑。我们在里面输入function pro { notepad $profile },呵呵明眼人都懂了,以后我们想要修改profile的时候,直接运行pro命令就可以了。

最后,想要PowerShell启动时能成功的载入配置文件,还需要在PowerShell的Execution Policy(执行策略)中设置允许它这样做。否则,尝试载入配置文件将会失败,PowerShell界面上也会显示错误信息。无法加载配置文件的错误提示如下:


C:\Users\Hong>powershell
Windows PowerShell
版权所有(C) 2012 Microsoft Corporation。保留所有权利。

. : 无法加载文件 C:\Users\Hong\Documents\WindowsPowerShell\Microsoft.PowerShell
_profile.ps1,因为在此系统上禁止运行脚本。有关详细信息,请参阅 http://go.micros
oft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。
所在位置 行:1 字符: 3
+ . 'C:\Users\Hong\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
'
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~
   + CategoryInfo          : SecurityError: (:) [],PSSecurityException
   + FullyQualifiedErrorId : UnauthorizedAccess


其实解决这个问题跟解决执行ps1文件的方法一样,因为这个Profile其实也是一个ps1格式的文件。所以使用Set-ExecutionPolicy RemoteSigned即可。

参考文章:http://msdn.microsoft.com/en-us/library/bb613488%28VS.85%29.aspx

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息