在「開關」中修改正在評估的變量並使其更改匹配,有沒有辦法?在switch語句中更改評估程序
$var = "a"
switch ($var){
"a" {Write-Host "1st match for 'a'"}
"b" {Write-Host "1st match for 'b'"}
"a" {Write-Host "2nd match for 'a'"; $var = "b" ; continue}
"b" {Write-Host "2st match for 'b'"}
}
我希望能夠得到上面的匹配:
爲對 'B'
$Destination = "vmstores:\[email protected]\Training\Local-B\David" #is a param of my function, which could be a bunch of different types of object.
$DestinationType = $Destination.GetType().Name
switch ($DestinationType){
"String" {
if ((Test-Path $Destination) -eq $true){
if ((Get-Item $Destination).GetType().Name -eq "DatastoreFolderImpl"){
$DestinationType = "DatastoreFolderImpl"
if ((Test-Path $Destination.Insert($Destination.Length,"\").Insert(($Destination.Length)+1,$SourceVMXShort)) -eq $true){
Write-Warning "Destination File exists..."
$DestinationExists = $true
}
}
elseif ((Get-Item $Destination).GetType().Name -eq "DatastoreFileImpl"){
$DestinationType = "DatastoreFileImpl"
Write-Warning "Destination File exists..."
$DestinationExists = $true
}
}
; continue
}
"DirectoryInfo" {
if ((Test-Path $Destination.Insert($Destination.Length,"\").Insert(($Destination.Length)+1,$SourceVMXShort)) -eq $true){
Write-Warning "Destination File exists..."
$DestinationExists = $true
}
; break
}
"FileInfo" {
if ((Test-Path $Destination) -eq $true){
Write-Warning "Destination File exists..."
$DestinationExists = $true
}
; break
}
"DatastoreFileImpl" {
if ((Test-Path $Destination) -eq $true){
Write-Warning "Destination File exists..."
$DestinationExists = $true
}
; break
}
"DatastoreFolderImpl" {
if ((Test-Path $Destination.Insert($Destination.Length,"\").Insert(($Destination.Length)+1,$SourceVMXShort)) -eq $true){
Write-Warning "Destination File exists..."
$DestinationExists = $true
}
; break
}
"NasDatastoreImpl" {
New-PSDrive -Name "DestMount" -Root \ -PSProvider VimDatastore -Datastore $Destination | Out-Null
if ((Test-Path ("DestMount:").insert(10,"\").Insert(11,$SourceVMXShort)) -eq $true){
Write-Warning "Destination File exists..."
$DestinationExists = $true
}
$Destination = ("DestMount:").insert(10,"\")
; break
}
"VMFSDatastoreImpl" {
New-PSDrive -Name "DestMount" -Root \ -PSProvider VimDatastore -Datastore $Destination | Out-Null
if ((Test-Path ("DestMount:").insert(10,"\").Insert(11,$SourceVMXShort)) -eq $true){
Write-Warning "Destination File exists..."
$DestinationExists = $true
}
$Destination = ("DestMount:").insert(10,"\")
; break
}
}
'一'
第二節比賽 'A'
第二節比賽第一個比賽
正如你所看到的,如果我可以更新$ DestinationType,那麼我可以在其他開關塊中重新使用該語句,而不是額外的「ifs」,這將更加優雅
我正在寫一個函數,其中一個參數可能是一些類型的對象,其中一個字符串是一個。如果它匹配'字符串',那麼我想改變我打開的變量的值,所以我不必在我的語句塊中編寫額外的'ifs'。 – wint3r