Powershell 的知识串联I PSDrive 与 PSProvider
Powershell 的知识串联I PSDrive 与 PSProvider
前言
微软在官方文档中对 PSDrive 的描述不尽深入
- PSDrive: 显示由提供程序公开的驱动器与 Windows 逻辑驱动器
- PSProvider: 一种允许文件系统访问数据存储的接口
这些驱动与接口跟以下命令相关:
- *-Alias: 操作命令别名
- *-Item: 操作文件,注册表等
- *-Variable: 操作变量
PSDrive 与 PSDrive
Get-PSProvider
一般给我们输出以下结果:
Name | Capabilities | Drives |
---|---|---|
Registry | ShouldProcess | {HKLM, HKCU} |
Alias | ShouldProcess | {Alias} |
Environment | ShouldProcess | {Env} |
FileSystem | Filter, ShouldProcess, Credentials | {C, D} |
Function | ShouldProcess | {Function} |
Variable | ShouldProcess | {Variable} |
Certificate | ShouldProcess | {Cert} |
WSMan | Credentials | {WSMan} |
Get-PSDrive
则给我们输出以下结果:
Name | Used (GB) | Free (GB) | Provider | Root |
---|---|---|---|---|
Alias | Alias | |||
C | 145.31 | 33.75 | FileSystem | C:\ |
Cert | Certificate | \ | ||
D | 124.35 | 161.19 | FileSystem | D:\ |
Env | Environment | |||
Function | Function | |||
HKCU | Registry | HKEY_CURRENT_USER | ||
HKLM | Registry | HKEY_LOCAL_MACHINE | ||
Temp | 145.31 | 33.75 | FileSystem | C:\Users\Sie\AppData\Local\Temp\ |
Variable | Variable | |||
WSMan | WSMan |
Alias 驱动器
Get-Alias
的效果与Get-ChildItem Alias:
是一致的- 相似的
Get-ChildItem Alias:cls
等同于Get-Alias cls
- 上边的两种方式都返回 System.Management.Automation.AliasInfo 对象(数组)
Variable 驱动器
Get-ChildItem Variable:
在全新的会话中,可以获得自动变量1列表 与 首选项变量2列表Set-Variable -Name newOne -Value 1
与New-Item -Path Variable:newOne -Value 1
和$newOne=1
是一致的Remove-Item Variable:newOne
与Remove-Variable newOne
和$newOne=$null
是一致的(Set-Variable -Name newVar -Value 1 -PassThru) -eq (Get-Item Variable:newVar)
的结果为 trueSet-Variable -Name newO -Value 1 -PassThru | foreach { $newO; Remove-Item "Variable:$($_.Name)"; $newO -eq $null }
输出 1 和 true
Env 驱动器
$env:PATH
与[System.Environment]::GetEnvironmentVariable('Path')
可以获得计算机的 PATHNew-Item -Path "Temp:$(New-Guid).txt"
与New-Item -Path (Join-Path $env:TMP "$(New-Guid).txt")
是一致的
持久化环境变量
[Environment]::SetEnvironmentVariable('Foo', 'Bar', 'Machine')
: 设置到计算机域中- 对于
pwsh
会话,notepad $PROFILE
3,添加$Env:Foo='Bar'
- 使用高级系统属性:
& SystemPropertiesAdvanced.exe
HKLM 与 HKCU 驱动器
- 这两个都由 Registry 提供, 关联 regedit.exe 编辑器, 可由
Set-Location HKLM:
进入 Get-Item -Path HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem | Set-Variable fs -PassThru | % {$fs.GetValueNames()} | Select-Object @{n='键';e={$_}},@{n='值';e={$fs.GetValue($_)}}
打印FileSystem
路径下的所有键值对, 包含常见的长路径定义 LongPathsEnabled
注
Get-ChildItem Variable:
返回的列表不可再声明, 如 $input 是后台任务 Job 的一个单一输入Import-Module $moduleName
可用于导入 PSProvider 和 PSDrive