如果使用System.Management.Automation(SMA)实现自定义PowerShell主机,则所有自动变量都是可用的,除非它似乎$PROFILE是空的.怎么会重新创建呢?
它始终在UserProfile +中\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1吗?或者我是否需要担心它在其他地方?
澄清一下,我只关心CurrentUserCurrentHost个人资料.
鉴于此PowerShell脚本:
Write-Output "_Profiles_"
Write-Output "CurrentUserCurrentHost = '$($Profile.CurrentUserCurrentHost)'"
Write-Output "CurrentUserAllHosts = '$($Profile.CurrentUserAllHosts)'"
Write-Output "AllUsersCurrentHost = '$($Profile.AllUsersCurrentHost)'"
Write-Output "AllUsersAllHosts = '$($Profile.AllUsersAllHosts)'"
Run Code Online (Sandbox Code Playgroud)
针对系统PowerShell运行它具有以下输出:
_Profiles_ CurrentUserCurrentHost = 'C:\Users\rob\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1' CurrentUserAllHosts = 'C:\User\rob\Documents\WindowsPowerShell\profile.ps1' AllUsersCurrentHost = 'C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1' AllUsersAllHosts = 'C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1'
使用自定义C#PowerShell主机(System.Management.Automation.Host.PSHost实现)运行它显示:
_Profiles_ CurrentUserCurrentHost = '' CurrentUserAllHosts = '' AllUsersCurrentHost = '' AllUsersAllHosts = ''
https://github.com/chocolatey/choco/issues/667
这已经在PowerShell v3/System.Managment.Automation(SMA)v3中进行了测试,但它可以在其他PowerShell版本中轻松证明.
作为一个可能的解决方案,这就是我想出的。但是,这确实意味着$profile始终应位于“文档”文件夹中。
var documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify);
var currentUserCurrentHostProfile = _fileSystem.combine_paths(documentsFolder, "WindowsPowerShell\\Microsoft.PowerShell_profile.ps1");
var profileFix = @"
if ((Test-Path(""{0}"")) -and ($profile -eq $null -or $profile -eq '')) {{
$global:profile = ""{1}""
}}
".format_with(documentsFolder, currentUserCurrentHostProfile);
pipeline.Commands.Add(new Command(profileFix, isScript: true, useLocalScope: false));
Run Code Online (Sandbox Code Playgroud)
这是因为像 LocalSystem 这样的特殊帐户没有配置文件文件夹。
注意:.format_with是一个字符串格式化程序,因此当它完成字符串格式化时,您看到的{{和}}将转换为{和。}