Олаф предоставил важный указатель в комментарии:
$profile | select * # short for: $profile | Select-Object -Property *
показывает все расположения файлов профиля, независимо от того, существуют ли отдельные файлы профиля.
Например, на моей машине Ubuntu с установленной в /home/jdoe/.powershell
оболочкой 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
Обратите внимание на наличие стандартного свойства Length
типа [string]
, которое можно было бы опустить, если бы вы использовали вместо него
$profile | select *host*
.
То, что таким образом можно получить местоположения профилей, не очевидно, учитывая, что $profile
является строковой переменной (тип [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
Convenience functions for getting profile locations and opening profiles for editing:
Код ниже определяет:
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
раздел справки.
person
mklement0
schedule
07.04.2019
$profile | Select-Object -Property *
? - person Olaf   schedule 07.04.2019