【发布时间】:2017-09-27 01:09:19
【问题描述】:
我有一些脚本可以为远程实例创建多个 PSDrive 实例。我想确保创建的每个PSDrive 实例都被清理干净。
我有一个如下所示的 Powershell 模块。这是我实际运行的简化版本:
function Connect-PSDrive {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
$Root,
[String]
$Name = [Guid]::NewGuid().ToString(),
[ValidateSet("Registry","Alias","Environment","FileSystem","Function","Variable","Certificate","WSMan")]
[String]
$PSProvider = "FileSystem",
[Switch]
$Persist = $false,
[System.Management.Automation.PSCredential]
$Credential
)
$parameters = @{
Root = $Root;
Name = $Name;
PSProvider = $PSProvider;
Persist = $Persist;
}
$drive = $script:drives | Where-Object {
($_.Name -eq $Name) -or ($_.Root -eq $Root)
}
if (!$drive) {
if ($Credential) {
$parameters.Add("Credential", $Credential)
}
$script:drives += @(New-PSDrive @parameters)
if (Get-PSDrive | Where-Object { $_.Name -eq $Name }) {
Write-Host "The drive '$Name' was created successfully."
}
}
}
function Disconnect-PSDrives {
[CmdletBinding()]
param ()
$script:drives | Remove-PSDrive -Force
}
每次调用Connect-PSDrive函数时,我都可以看到成功创建了一个新驱动器,并为$script:drives添加了一个引用。在调用脚本的末尾,我有一个调用 Disconnect-PSDrives 的 finally 块,但失败并出现以下异常。
Remove-PSDrive : Cannot find drive. A drive with the name 'mydrive' does not exist.
At C:\git\ops\release-scripts\PSModules\PSDriveWrapper\PSDriveWrapper.psm1:132 char:22
+ $script:drives | Remove-PSDrive -Force
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (mydrive:String) [Remove-PSDrive], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.RemovePSDriveCommand
我想知道为什么在$script:drives 中可以找到对我创建的PSDrive 对象的引用,而Remove-PSDrive 却无法找到这些对象。
我还想知道如何管理这些PSDrive 实例,而无需将每个实例返回到调用脚本,这样Disconnect-PSDrives 就可以工作。
一些额外的说明:
- 我正在创建这些驱动器,并将
Persist标志设置为 false。 - 多次运行这些错误,与计算机建立的多个连接过多。这就是为什么我认为连接没有被清理。如果我的假设是错误的,请解释为什么要清理连接。
【问题讨论】:
-
PowerShell 驱动器的作用域为:
New-PSDrive Test FileSystem C:\; & { New-PSDrive Test FileSystem D:\; Get-PSDrive Test }; Get-PSDrive Test。因此,除非您使用.调用Connect-PSDrive,否则当函数完成时,由该函数创建的驱动器将超出范围。 -
@PetSerAl 你是对的 :) 我添加了
-Scope参数,它似乎工作正常。我错过了一些如此明显的东西。
标签: windows powershell