Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

Creating custom object in a loop

$
0
0

I found a function (in the TechNet gallery) that get's the run-as accounts for services and tasks on a local or remote machines. I'm trying to re-arrange the parts to suit my needs. I'll post my snippet below. 

The way I want to run it, is: .\script.ps1 -ToCheck 'tasks'. When I do, I get the following error: 

Item has already been added. Key in dictionary: 'Type' Key being added: 'Type'
At C:\shared\test2.ps1:196 char:17
+ $output += $outputtask
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException

The snippet looks like this: 

CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [string[]]$ComputerName = "localhost",
        [string]$RunAsUser,
        [string]$Logfile,
        [string]$ToCheck = 'services'
    )
Function Get-ScheduledTask {
# Helper function by Claus Nielsen
# http://www.powershellmagazine.com/2011/11/21/managing-scheduled-tasks-in-your-environment-part-i
    [CmdletBinding()]
        param(
            [Parameter(
            Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true)]
            [String[]]$Computer,

            [Parameter(Mandatory=$false)]
            [String[]]$RunAsUser,

            [Parameter(Mandatory=$false)]
            [String[]]$TaskName,

            [parameter(Mandatory=$false)]
            [alias("WS")]
            [switch]$WithSpace
         )

    Begin {
        $Script:Tasks = @()
    }
    Process {
        $schtask = schtasks.exe /query /s $Computer /V /FO CSV | ConvertFrom-Csv
        Write-Verbose  "Getting scheduled Tasks from: $Computer"

        if ($schtask)
        {
            foreach ($sch in $schtask)
            {
                if ($sch."Run As User" -match "$($RunAsUser)" -and $sch.TaskName -match "$($TaskName)")
                {
                    Write-Verbose  "$Computer ($sch.TaskName).replace('\','') $sch.'Run As User'"
                    $sch  | Get-Member -MemberType Properties | ForEach -Begin {$hash=@{}} -Process {
                        If ($WithSpace)
                        {
                            ($hash.($_.Name)) = $sch.($_.Name)
                        }
                        Else
                        {
                            ($hash.($($_.Name).replace(" ",""))) = $sch.($_.Name)
                        }
                    } -End {
                        $script:Tasks += (New-Object -TypeName PSObject -Property $hash)
                    }
          }
            }
        }
    }
    End {
        $Script:Tasks
    }
}

#Begin script
If (($ToCheck -eq 'Tasks') -OR ($ToCheck -eq 'All')) {
    Foreach ($computer in $ComputerName) {
        If ($RunAsUser) {
            $tasks = Get-ScheduledTask -Computer $computer -RunAsUser $RunAsUser | Select-Object taskname,runasuser
        }
        Else {
            $tasks = Get-ScheduledTask -Computer $computer | Select-Object taskname,runasuser
        }
    
        If ($tasks) {
            Foreach ($task in $tasks) {
                Write-Verbose "Processing task $($task.taskname)"

                $outputtask = @{}
                $outputtask.Computername = $computersystem.name
                $outputtask.Connectivity = "Success"
                $outputtask.Type = "ScheduledTask"
                $outputtask.Name = $task.taskname
                $outputtask.RunAsAccount = $task.runasuser
                $output += $outputtask
            }
        }
        Else {
            $outputinfo = @{}
            $outputinfo.Computername = $($computer)
            $outputinfo.Connectivity = "Failed (ping)"
            $outputinfo.Type = $null
            $outputinfo.Name = $null
            $outputinfo.RunAsAccount = $null
            $output += $outputinfo
        }
    }
}
If (($ToCheck -eq 'Services') -OR ($ToCheck -eq 'All')) {
    Foreach ($computer in $ComputerName) {
        Get-RunAsAccountWorker -Computer $computer
    }
}

The error is complaining about the first instance of "$output += $outputtask" and I'm not sure why. I have that same block of code to create the $output object in another function (in the same .ps1) and it works fine. 

Thanks.


Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>