Олаф предоставил критический указатель в комментарии:
$profile | select * # short for: $profile | Select-Object -Property *
показывает все местоположения файла профиля, независимо от того, существуют ли отдельные файлы профиля .
Например, на моем компьютере с Ubuntu с установленной PowerShell в /home/jdoe/.powershell
я получаю:
AllUsersAllHosts : /home/jdoe/.powershell/profile.ps1
AllUsersCurrentHost : /home/jdoe/.powershell/Microsoft.PowerShell_profile.ps1
CurrentUserAllHosts : /home/jdoe/.config/powershell/profile.ps1
CurrentUserCurrentHost : /home/jdoe/.config/powershell/Microsoft.PowerShell_profile.ps1
Length : 62
Обратите внимание на наличие стандартного свойства [string]
типа *1015*, которое вы можетепропустите, если вы использовали
$profile | select *host*
.
То, что вы можете получить расположение профиля таким образом, неочевидно, учитывая, что $profile
является переменной string (тип [string]
).
PowerShell украшает этот экземпляр [string]
элементами NoteProperty
, отражающими все местоположения профиля, поэтому select
(Select-Object
) может извлекать их.
Выводпросто $profile
- т.е. строковое значение - дает /home/jdoe/.config/powershell/Microsoft.PowerShell_profile.ps1
, то есть тот же путь, что и его свойство CurrentUserCurrentHost
. [1]
Вы можетеПроверьте наличие этих свойств с помощью отражения следующим образом (что также показывает их значения):
$profile | Get-Member -Type NoteProperty
Это мозначает, что вы также можете использовать обычный доступ к свойству и завершение вкладки для получения отдельных местоположений профиля ;Например:
# Use tab-completion to find a specific profile location.
# Expands to .Length first, then cycles through the profile-location properties.
$profile.<tab>
# Open the all-users, all-hosts profiles for editing.
# Note: Only works if the file already exists.
# Also, you must typically run as admin to modify all-user profiles.
Invoke-Item $profile.AllUsersAllHosts
Удобные функции для получения местоположения профиля и открытия профилей для редактирования:
Код ниже определяет:
Get-Profile
перечисляет профили, показывая их местоположение и существуют ли они на данном компьютере.
Edit-Profile
открывает профили для редактирования (используйте -Force
для их создания по требованию);обратите внимание, что для изменения профилей всех пользователей обычно требуется запуск с правами администратора.
function Get-Profile {
<#
.SYNOPSIS
Gets the location of PowerShell profile files and shows whether they exist.
#>
[CmdletBinding(PositionalBinding=$false)]
param (
[Parameter(Position=0)]
[ValidateSet('AllUsersAllHosts', 'AllUsersCurrentHost', 'CurrentUserAllHosts', 'CurrentUserCurrentHost')]
[string[]] $Scope
)
if (-not $Scope) {
$Scope = 'AllUsersAllHosts', 'AllUsersCurrentHost', 'CurrentUserAllHosts', 'CurrentUserCurrentHost'
}
foreach ($thisScope in $Scope) {
[pscustomobject] @{
Scope = $thisScope
FilePath = $PROFILE.$thisScope
Exists = (Test-Path -PathType Leaf -LiteralPath $PROFILE.$thisScope)
}
}
}
function Edit-Profile {
<#
.SYNOPSIS
Opens PowerShell profile files for editing. Add -Force to create them on demand.
#>
[CmdletBinding(PositionalBinding=$false, DefaultParameterSetName='Select')]
param (
[Parameter(Position=0, ValueFromPipelineByPropertyName, ParameterSetName='Select')]
[ValidateSet('AllUsersAllHosts', 'AllUsersCurrentHost', 'CurrentUserAllHosts', 'CurrentUserCurrentHost')]
[string[]] $Scope = 'CurrentUserCurrentHost'
,
[Parameter(ParameterSetName='All')]
[switch] $All
,
[switch] $Force
)
begin {
$scopes = New-Object Collections.Generic.List[string]
if ($All) {
$scopes = 'AllUsersAllHosts', 'AllUsersCurrentHost', 'CurrentUserAllHosts', 'CurrentUserCurrentHost'
}
}
process {
if (-not $All) { $scopes.Add($Scope) }
}
end {
$filePaths = foreach ($sc in $scopes) { $PROFILE.$sc }
$extantFilePaths = foreach ($filePath in $filePaths) {
if (-not (Test-Path -LiteralPath $filePath)) {
if ($Force) {
if ((New-Item -Force -Type Directory -Path (Split-Path -LiteralPath $filePath)) -and (New-Item -Force -Type File -Path $filePath)) {
$filePath
}
} else {
Write-Verbose "Skipping nonexistent profile: $filePath"
}
} else {
$filePath
}
}
if ($extantFilePaths.Count) {
Write-Verbose "Opening for editing: $extantFilePaths"
Invoke-Item -LiteralPath $extantFilePaths
} else {
Write-Warning "The implied or specified profile file(s) do not exist yet. To force their creation, pass -Force."
}
}
}
[1] PowerShell рассматривает профиль текущего пользователя, текущего хоста интересующий профиль , поэтому строковое значение $profile
содержит это значение.Обратите внимание, что для того, чтобы украсить экземпляр [string]
свойствами заметки, одного Add-Member
недостаточно;Вы должны использовать следующую идиому: $decoratedString = $string | Add-Member -PassThru propName propValue
- см. Add-Member
раздел справки .