$profile
使我有些头疼。 $Profile.GetType()
解析为String
很好,但是它具有NoteProperty值:
$profile | Get-Member -Type NoteProperty
AllUsersAllHosts, AllUsersCurrentHost, CurrentUserAllHosts, CurrentUserCurrentHost
当我键入$profile
时,将返回CurrentUserCurrentHost NoteProperty。很好,但是我需要更改此值-这很复杂,但是我的公司VPN使用网络配置文件,当我在线时,它会尝试为我的$profile
引用该位置,这意味着每次控制台启动都需要9秒钟(非常慢)。如果将配置文件本地加载,我可以将其降低到1秒,但这意味着更改这些值。为此,我将以下内容放入AllUsersAllHosts
profile.ps1
$profile = C:\Users\($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
很好,但是通过执行此操作,我发现所有NoteProperty值都被删除!所以我尝试了:
$profile.CurrentUserCurrentHost = C:\Users\($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
但是这失败了,因为$ Profile的根值继续指向网络配置文件,并且控制台启动又是9秒!
然后我也注意到了以下怪异现象:
$x = [string]$profile
$x -eq $profile
Ny主要问题是:
•即使$ x在True
中没有任何NoteProperty
值,为什么$ x返回$profile
(因为对象肯定不相同!)?
•如何在不破坏$profile
值的情况下控制NoteProperty
的根值,并且
•如何更新.CurrentUserAllHosts
和.CurrentUserCurrentHost
,使根值也相应更新?即,即使我执行以下操作,$profile
的根值仍保持不变(仍然位于非常慢的网络配置文件位置):
Add-Member -InputObject $PROFILE -NotePropertyName "AllUsersAllHosts" -NotePropertyValue "C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "AllUsersCurrentHost" -NotePropertyValue "C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "CurrentUserAllHosts" -NotePropertyValue "C:\Users\$($env:Username)\Documents\WindowsPowerShell\profile.ps1"
Add-Member -InputObject $PROFILE -NotePropertyName "CurrentUserCurrentHost" -NotePropertyValue "C:\Users\$($env:Username)\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"
虽然在技术上可以将NoteProperty成员从一个字符串实例复制到另一个字符串实例(请参阅下文),但不幸的是,这对您没有帮助:
PowerShell公开了$PROFILE
变量,以提供[[用户的好处:
您应该将$PROFILE
视为只读变量,即使可以从技术上对其进行修改。
解决方法
,请参阅this related question的答案。如果以启动交互式会话为重点,则最有前途的方法是创建一个专用的快捷方式文件(*.lnk
)以启动您的PowerShell会话,该快捷方式文件是使用诸如以下目标命令定义的:powershell -noprofile -noexit -c ". c:\CustomProfileDir\profile.ps1"
解决您的问题,但它说明了如何将NoteProperty成员从一个对象复制到另一个对象,即使是在具有不同值的字符串之间。要使用PowerShell [Core] 6+,请用
pwsh
代替powershell
。
在对象之间复制NoteProperty成员:注意:
- 如上所述,这将
不是
[string]
实例,需要使用-PassThru
并分配回输入变量($obj = $obj | Add-Member -PassThru ...
)才能保留NoteProperty成员;对于其他类型,$obj | Add-Member ...
就足够了。# Assign the new string value to a new (temporary) variable.
$newProfile = '/path/to/my.ps1'
# Copy the NoteProperty members from the original, decorated string
# to the new variable's string instance.
$PROFILE.psobject.properties | where MemberType -eq 'NoteProperty' | foreach {
$newProfile = $newProfile |
Add-Member -PassThru -NotePropertyName $_.Name -NotePropertyValue $_.Value
}
# You can now assign the new variable to the old one,
# but note that *with $PROFILE that won't help*.
# $PROFILE SHOULD BE TREATED AS READ-ONLY.
$PROFILE = $newProfile