我有一些脚本可以为远程实例创建多个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
。在调用脚本结束时,我有一个调用finally
的{{1}}块,但是失败并出现以下异常。
Disconnect-PSDrives
我想知道为什么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
中提供了我创建的PSDrive
对象的引用,但$script:drives
无法找到对象。
我还想知道如何管理这些Remove-PSDrive
实例,而无需将每个实例都返回到调用脚本,以便PSDrive
可以正常工作。
一些额外的说明:
Disconnect-PSDrives
标记创建这些驱动器为false。