Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell v2 | Script Won't Declare Variable, need help debugging

Tags:

powershell

Alright there seems to be several issues with the script and i can't seem to figure out any of them, also some feedback on the script would be greatly apperciated. This is still my first script so it probably needs lots of little tweaks so please tell me whatever suggestions comes to mind.

Issues: Mostly all issues revolve around the logging.

  1. Log file is not being checked so the script keeps adding computers to the log file over and over.

  2. The log file does not update the information that is generated such as os,mac,ip, etc.

Issues Being Displayed:

Property 'Result' cannot be found on this object. Make sure that it exists. At W:\Powershell Scripting\Test Lab\TestFunction.ps1:86 char:17 + IF ($Computer. <<<< Result -ne "Successful") { + CategoryInfo : InvalidOperation: (.:OperatorToken) [], RuntimeException + FullyQualifiedErrorId : PropertyNotFoundStrict

The Script

Set-PSDebug -strict
Set-StrictMode -Version latest
$consoleObject = (Get-Host).UI.RawUI

# Adjustable Variables
$Computers_Path = ".\computers.txt"
$Log_Path = ".\Log.txt"
$Log_MaxTick = 5
$RunOnServers = 0

# Multi-Threading Variables
$Jobs_MaxAtOnce = 20
$SleepTimer = 500

# Script Specific Variables
$ScriptTitle = "Local Admin Check"

# Validate Adjustable Variables
$Computers = @(Import-CSV $Computers_Path -header "Name","MAC")

# Framework Specific Variables (Pre-Setting Variables)
$Run = 0; $Succssful = 0; $Jobs_Count = 0; $Log_Tick= 0; $WriteToLog = "No"

# Misc
$Total = $Computers.length
IF (!(Test-Path $Log_Path)) { Add-Content $Log_Path "Name,OS,Mac,IPAddress,Status,Attempts,Result,LastAttempt" }
$Log = @(Import-Csv $Log_Path)
$Successful = ($Log | Where-Object {$_.Result -eq "Successful"} | Select-String -inputobject {$_.Name} -pattern $Computers | Measure-Object).Count

# Load Functions
Function GetOS {
    $RegCon = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer.Name )
    $RegKey = $RegCon.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\")
    $RegValue = $RegKey.GetValue("ProductName")
    $RegCon.Close()
    $Computer.OS = $RegValue
}

Function SmartLogging {

    If ($Args[0] -eq "AddComputer") {
        Add-Content ($Computer.Name + "," + $Computer.OS + "," + $Computer.Mac + "," + $Computer.IPAddress + "," + $Computer.Status + "," + $Computer.Attempts + "," + $Computer.Result + "," + $Computer.LastAttempt) -path .\log.txt
    } ELSEIF ( $Log_Tick -eq $Log_MaxTick -OR $Args -eq "Update" ) {
        $Log_Tick = 0;
        Get-Content $Log_Path | Foreach-Object {$_ -replace "$Computer.Name,.*", ($Computer.Name + "," + $Computer.OS + "," + $Computer.Mac + "," + $Computer.IPAddress + "," + $Computer.Status + "," + $Computer.Attempts + "," + $Computer.Result + "," + $Computer.LastAttempt)} | Set-Content $Log_Path
    } ELSEIF ($Args[0] -eq "CheckComputer") {
         IF (!($Log | Select-String -pattern $Computer.Name -SimpleMatch)) {
            $Log += New-Object PSObject -Property @{ Name = $Computer.Name; OS = $NULL; Mac = $Computer.MAC; IPAddress = $NULL; Status = $NULL; Attempts = 0; Result = $NULL; LastAttempt = $NULL;}
            $Computer = $Log | Where-Object {$_.Name -eq $Computer.Name}
            SmartLogging AddComputer
        } ELSE {
            $Computer = $Log | Where-Object {$_.Name -eq $Computer.Name}
        }
    } ELSEIF (-not $Args[0]) {
        "Log Ticked"
        $Log_Tick++
    }
}

Function GetIPAddress {
    $IPAddress = [System.Net.Dns]::GetHostAddresses("TrinityTechCorp") | Where-Object {$_.IPAddressToString -like "*.*.*.*"};
    $Computer.IPAddress = $IPAddress.IPAddressToString
}

Function WindowTitle {
    [int]$Successful_Percent = $Successful / $Total * 100
    $consoleObject.WindowTitle = “$ScriptTitle - $Successful Out Of $Total ($Successful_Percent%) Successful `| Run`: $Run”
}

# Start Script
while ( $Successful -le $Total ) {
    $Run++
    ForEach ($Computer in $Computers) {
        WindowTitle 
        SmartLogging CheckComputer
        IF ($Computer.Result -ne "Successful") {
            IF (test-connection $Computer.Name -quiet ) {
                $Computer.Status = "Awake"
                IF (!$Computer.OS){GetOS}
                IF (!$Computer.IPAddress){GetIPAddress}
                ## Start Script ##
                    $CheckComputer = [ADSI]("WinNT://" + $Computer.Name + ",computer")
                    $Group = $CheckComputer.psbase.children.find("Administrators")
                    $members= $Group.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
                    ForEach($user in $members) {
                        $Result = $Computer.Name + "," + $user.ToString()
                        Add-Content $Result -path .\Result.csv
                    }
                ## End Script ##
                SmartLogging Update
                $Computer.Result = "Successful"
                $Successful += 1
            } ELSE {
                $Computer.Status = "Unknown"
            }
            $Computer.Attempts = [int] $Computer.Attempts + 1
            $Computer.LastAttempt = Get-Date -uFormat "%I:%M:%S%p %d%b%y"
        }
    SmartLogging
    }
}
Write-Output "Script Completed"
like image 773
Nick W. Avatar asked Feb 20 '26 14:02

Nick W.


2 Answers

This declaration of $Computers collection....

$Computers = @(Import-CSV $Computers_Path -header "Name","MAC")

...will not work with this condition:

IF ($Computer.Result -ne "Successful")

The exception message explicitly states this, and where:

Property 'Result' cannot be found on this object. Make sure that it exists. \TestFunction.ps1:86 char:17

To resolve this, I would recommend initializing the property of Result, most likely like so:

$Computers = @(Import-CSV $Computers_Path -header "Name","MAC","Result")
like image 132
D3vtr0n Avatar answered Feb 22 '26 04:02

D3vtr0n


The problem this time is that you don't have Result member in $Computers collection member, only Name and MAC. Unless you add such a member later on your code, which I don't really want to read, as it already is about 100 rows and contains a lot of code that is not related to the actual problem statement.

$Computers = @(Import-CSV $Computers_Path -header "Name","MAC")

Have you tried debugging the script on Powershell ISE? It's built-in debugger for Powershell 2. Take a look at a Technet article about it.

like image 37
vonPryz Avatar answered Feb 22 '26 06:02

vonPryz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!