【发布时间】:2021-06-06 08:11:42
【问题描述】:
我正在尝试编写 2 个函数:
- 第一个 (Get-Lab) 检索 [Lab] 对象
- 第二个(remove-Lab)删除一个 [Lab] 对象
[Lab] 是我的模块中定义的一个类。
当运行 Get-Lab 时,我使用正确的类型正确检索了我的实验室实例:
当我运行 Remove-Lab -Lab (Get-Lab -Name Mylab) 时,操作正确执行:
但是当我尝试通过管道传递 [Lab] 对象时它失败了。
函数没有通过管道接收对象。但是,我使用 ValueFromPipeline=$true 将 -Lab 参数设置为强制。
Function Remove-Lab{
[CmdletBinding(DefaultParameterSetName='Lab')]
param (
[Parameter(ValueFromPipeline=$true,ParameterSetName='Lab',Position=0,Mandatory=$true)]
[Lab]
$Lab,
# Parameter help description
[Parameter(Position=1,Mandatory=$false)]
[switch]
$Force=$false
)
begin {
Write-host ("`tLabName : {0}" -f $Lab.Name) -ForegroundColor Yellow
if ($null -ne $Lab) {
$LabToRemove = $Lab
}
if (-not [string]::IsNullOrEmpty($LabId)) {
$LabToRemove = Get-Lab -Id $LabId
}
if (-not [string]::IsNullOrEmpty($Name)) {
$LabToRemove = Get-Lab -Name $Name
}
if ($null -eq $LabToRemove) {
throw "There is no Lab with specified characteristics. Please check your input"
}
}
process {
$DoRemoval = $true
if ($Force.IsPresent -eq $false) {
while ($null -eq $UserInput -or $UserInput -notin @('Y','N')) {
$UserInput = Read-HostDefault -Prompt "Are you sure want to remove the selected Lab and all its components ? [Y]es, [N]o" -Default 'N'
if ($UserInput -eq 'N') {
$DoRemoval = $false
}
}
Write-Host ("`tUser Input : {0}" -f $UserInput) -ForegroundColor Green
}
if ($DoRemoval -eq $true) {
Write-Host ("`tAbout to Remove the following Lab : {0}" -f $LabToRemove.Name) -ForegroundColor Green
}
}
end {
}
}
你对这个问题有什么想法吗?
【问题讨论】:
-
可能很傻,但是您是否尝试将
Get-Lab的值添加到变量并将该变量传递给Remove-Lab。老实说,我自己从来没有做过,但也许你的Get-Lab函数不是'pipable'。 -
您无法访问
begin中的管道输入,$Lab在到达process块之前将不可用 -
@Alex_P :已经尝试过但不是解决方案。解决方案由 Matthias 提出
标签: powershell