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

PS script errors at 'Begin {}'

$
0
0

I found a script on blog.powershell.no, and am trying to adjust it to fit my needs. I've pasted my revisions below. 

When I run the script (.\script.ps1 -ToCheck All), I should get a list of the run-as accounts for all services and scheduled tasks on localhost. Instead, I'm getting the error: 

Begin : The term 'Begin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\shared\test.ps1:184 char:1
+ Begin {
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (Begin:String) [],
CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
Get-Process : Cannot evaluate parameter 'Name' because its argument is specified as a script block and there is no input. A script block cannot be evaluated without input.
At C:\shared\test.ps1:190 char:9
+ Process {
+ ~
+ CategoryInfo : MetadataError: (:) [Get-Process], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.GetProcessCommand
End : The term 'End' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At C:\shared\test.ps1:224 char:1
+ End {
+ ~~~
+ CategoryInfo : ObjectNotFound: (End:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

I don't understand why it doesn't like the Begin/Process/End blocks. Here is the entire script:

<#
.SYNOPSIS
    Get 'Run As'' value for services and/or scheduled tasks on a user-specified list of computers.
.DESCRIPTION
    Users WMI and schtasks.exe to get the 'Run As' value for services and/or scheduled tasks on a user-specified list of computers. The script requires PowerShell version 2.
.NOTES
    Author: Jan Egil Ring
    Blog: http://blog.powershell.no
    LastEdit: 22.11.2011
.LINK
.PARAMETER ComputerName
    Default value: localhost. The computer to perform action against. Accepts ValueFromPipeline and ValueFromPipelineByPropertyName.
.PARAMETER RunAsUser
    Filters returned objects based on user or domain name.
.PARAMETER ToCheck

.PARAMETER Logfile
    Path to log-file (only errors are logged).
.EXAMPLE
    .\getRunAsAccounts-Parameterized.ps1 -ComputerName srv01 -RunAsUser managed
    This example checks srv01 for services and scheduled tasks that have a "Run As" account with 'managed' in the name.
.EXAMPLE
    .\getRunAsAccounts-Parameterized.ps1 -ComputerName srv01 -RunAsUser srvc
    This example checks srv01 for services and scheduled tasks that have a "Run As" account with 'srvc' in the name.
.EXAMPLE
    .\getRunAsAccounts-Parameterized.ps1 -ComputerName (Get-Content c:\computernames.txt)
    This example get's a list of computer names from c:\computernames.txt and returns the run-as accounts for all services.
.EXAMPLE
    Get-ADComputer -filter * | .\getRunAsAccounts-Parameterized.ps1 | Out-File c:\output.csv -NoTypeInformation
    This example get's a list of all computers in Active Directory and returns the run-as accounts for all services to a CSV file.
#>
#Requires -Version 2.0

[CmdletBinding()]
param(
    [Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
    [string[]]$ComputerName = "localhost",
    [string]$RunAsUser,
    [ValidateSet("Services","Tasks","All")]
    [string]$ToCheck,
    [string]$Logfile
)

Function Get-RunAsAccountWorker {
    param($ComputerName)
    
    Try {
        If ((Test-Connection -ComputerName $ComputerName -Quiet) -and ($ComputerSystem = Get-WmiObject -Class win32_ComputerSystem -Computername $ComputerName -ErrorAction Stop)) {
            Write-Verbose "Connected to computer $ComputerName"
            #$services = Get-WmiObject Win32_Service -filter "(StartName Like '[^NT Authority]%') AND (StartName <> 'localsystem')" -ComputerName $ComputerName -ErrorAction Stop | Select name,Startname,startmode
            $services = Get-WmiObject Win32_Service -Filter "(StartName Like '%$runAsUser%')" -ComputerName $ComputerName -ErrorAction Stop | Select-Object name,startname,startmode

            $output = @()

            If ($services) {
                Foreach ($service in $services) {
                    Write-Verbose "Processing NIC $($service.name)"

                    $outputService = @{}
                    $outputService.Computername = $computerSystem.name
                    $outputService.Connectivity = "Success"
                    $outputService.Type = "Service"
                    $outputService.Name = $service.name
                    $outputService.RunAsAccount = $service.startName
		            $outputService.StartupType = $service.startMode
		            $outputService.Status = $null
                    $output += $outputService
                }
            }

            
        }
        Else {
            $outputinfo = @{}
            $outputinfo.Computername = $($ComputerName)
            $outputinfo.Connectivity = "Failed (ping)"
            $outputinfo.Type = $null
            $outputinfo.Name = $null
            $outputinfo.RunAsAccount = $null
		    $outputinfo.StartupType = $null
		    $outputinfo.Status = $null
            $output += $outputinfo
        }
    } 
    Catch {
        Write-Verbose "An error occured connecting to computer $ComputerName"
        Write-Verbose $error[0].exception
        $outputinfo = @{}
        $outputinfo.Computername = $($ComputerName)
        $outputinfo.Connectivity = "Failed (RPC)"
        $outputinfo.Type = $null
        $outputinfo.Name = $null
        $outputinfo.RunAsAccount = $null
		$outputinfo.StartupType = $null
		$outputinfo.Status = $null
        $output += $outputinfo

        If ($logfile) {
            $ComputerName | Out-File -FilePath $Logfile -Append
            $error[0].exception | Out-File -FilePath $Logfile -Append
        }
    }

    Write-Verbose "Writing output object"
    If ($output) {
        Foreach ($ht in $output) {
            New-Object -TypeName PSObject -Property $ht
        }
    }
    Else {
        $outputinfo = @{}
        $outputinfo.Computername = $($ComputerName)
        $outputinfo.Connectivity = "Success"
        $outputinfo.Type = $null
        $outputinfo.Name = $null
        $outputinfo.RunAsAccount = $null
	    $outputinfo.StartupType = $null
	    $outputinfo.Status = $null

        New-Object -TypeName PSObject -Property $outputinfo
    }
}

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[]]$ComputerName,

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

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

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

    BEGIN {
        $Script:Tasks = @()
    }

    PROCESS {
        $schtasks = schtasks.exe /query /s $ComputerName /V /FO CSV | ConvertFrom-Csv
        Write-Verbose  "Getting scheduled tasks from: $ComputerName"

        If ($schtasks) {
            Foreach ($task in $schtasks) {
                If ($task."Run As User" -match "$($RunAsUser)" -and $task.TaskName -match "$($TaskName)") {
                    Write-Verbose  "$ComputerName ($task.TaskName).replace('\','') $task.'Run As User' $task.Status"
                    $task  | Get-Member -MemberType Properties | ForEach -BEGIN {$hash=@{}} -PROCESS {
                        If ($WithSpace) {
                            ($hash.($_.Name)) = $task.($_.Name)
                        }
                        Else {
                            ($hash.($($_.Name).replace(" ",""))) = $task.($_.Name)
                        }
                    } -END {
                        $script:Tasks += (New-Object -TypeName PSObject -Property $hash)
                        }
                }
            }
        }
    }

    END {
        $Script:Tasks
    }
}

Begin {
    If ($LogFile) {
        New-Item -Path $Logfile -ItemType File -Force | Out-Null
    }
}

Process {
    If (($ToCheck -eq 'Services') -OR ($ToCheck -eq 'Both')) {
        Foreach ($computer in $ComputerName) {
            Get-RunAsAccountWorker -ComputerName $computer
        }
    }
    If (($ToCheck -eq 'Tasks') -OR ($ToCheck -eq 'Both')) {
        If ($RunAsUser) {
            $tasks = Get-ScheduledTask -ComputerName $ComputerName -RunAsUser $RunAsUser | Select-Object taskname,runasuser,status
        }
        Else {
            $tasks = Get-ScheduledTask -ComputerName $ComputerName | Select-Object taskname,runasuser,status
        }

        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
	            $outputtask.StartupType = $null
	            $outputTask.Status = $task.Status
                $output += $outputtask
            }
        }
    }
}
End {
    Write-Host 'end'
}


Viewing all articles
Browse latest Browse all 15028

Trending Articles



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