Hi,
I’m having some issues getting my powershell function to work through pipeline and using regular command parameters. I’ve managed to get it working but with pipeline detection and re-writing my inputs in the “Process” section then treating the whole thing in the “End” section. Surely there is a better way?
Function Test {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false,ValueFromPipelineByPropertyName, Position=1)] [Alias('ComputerName','ServerName','Host','HostName','Computer','Path')]
[string[]]$Server,
[Parameter(Mandatory=$False, ValueFromPipelineByPropertyName, Position=2)]
[Alias('Instance','Name','ShareName')]
[string[]]$Share
)
Begin {
$ToProcess = @()
}
Process {
If ($MyInvocation.ExpectingInput) {
If ($Server -and $Share) {
$Obj = "" | Select Server,Share
If ($Server) {
$Obj.Server = $Server[0]
}
Else{$Obj.Server = $Server}
If ($Share) {
$Obj.Share = $Share[0]
}
Else{$Obj.Share = $Share}
$ToProcess += $Obj
}
ElseIf ($Share -and !$Server) {
$Obj = "" | Select Share
If ($Share) {$Obj.Share = $Share[0]}Else{$Obj.Share = $Share}
$ToProcess += $Obj
}
ElseIf ($Server -and !$Share) {
$Obj = "" | Select Server
If ($Server) {$Obj.Server = $Server[0]}Else{$Obj.Server = $Server}
$ToProcess += $Obj
}
}
Else {
If ($Server -and $Share) {
$Counter = 0
$Countershr = 0
$Server | %{
$Obj = "" | Select Server,Share
If ($Server.count -gt 1) {
If ($Server[$Counter] -ne $null) {$Obj.Server = $Server[$Counter]}
}
Else{$Obj.Server = $Server}
If ($Share -ne $null -and $Share.count -gt 1) {
If ($Share[$Countershr] -ne $null) {
$Obj.Share = $Share[$Countershr]
}
$Countershr++
}
ElseIf ($Share -ne $null) {$Obj.Share = $Share}
$ToProcess += $Obj
$counter++
}
}
ElseIf ($Share -and $Server -eq $null) {
$Counter = 0
$Share | %{
$Obj = "" | select Share
If ($Share -ne $null -and $Share.count -gt 1) {
If ($Share[$Counter] -ne $null) {
$Obj.Share = $Share[$Counter]
}
}
ElseIf ($Share -ne $null) {$Obj.Share = $Share}
$ToProcess += $Obj
$counter++
}
}
ElseIf ($Server -and $Share -eq $null) {
$Counter = 0
$Server | %{
$Obj = "" | Select Server
If ($Server -ne $null -and $Server.count -gt 1) {
$Obj.Server = $Server[$Counter]
}
ElseIf ($Server -ne $null) {$Obj.Server = $Server}
$ToProcess += $Obj
$counter++
}
}
}
}
End {
$ToProcess
}
}
Both these commands give the same results but I’m thinking my script is way more complicated than it has to be? …
$array = ’
[
{
“Server”: “server1”,
“Share”: “share1”
},
{
“Server”: “server2”,
“Share”: “share2”
}
]
’ | convertfrom-json
Test -Server Server1,Server2 -Share Share1,Share2
$array | Test