2

Main Script

$Computers = Get-Content .\computers.txt

If ( test-path .\log.txt ) {
    $Log_Successful = Import-CSV .\log.txt | Where-Object {$_.Result -eq "Succesful"}
} ELSE {
    Add-Content "Computer Name,Is On,Attempts,Result,Time,Date"
}
$Log_Successful | format-table -autosize

Issues:

Log_Successful."Computer Name" works fine, but if i change 4 to read as the following

$Log_Successful = Import-CSV .\log.txt | Where-Object {$_.Result -eq "Failed"}

Log_Successful."Computer Name" no longer works... Any ideas why?

Dataset

Computer Name,Is On,Attempts,Result,Time,Date
52qkkgw-94210jv,False,1,Failed,9:48 AM,10/28/2012
HELLBOMBS-PC,False,1,Successful,9:48 AM,10/28/2012
52qkkgw-94210dv,False,1,Failed,9:48 AM,10/28/2012
2
  • 2
    Please use Set-PSDebug -strict in every script in order to catch misspelled variables. Commented Oct 28, 2012 at 6:51
  • 1
    In addition, the usual convention for Powershell keywords is to use lowercase. Prefer the .Net case when you use stuff from .Net libraries like [Regex]::GetGroupNames(). IF{...}ELSE{...} looks like SQL and If{}...ELSE{} looks just plain weird. Commented Oct 28, 2012 at 6:57

2 Answers 2

3

In case of "Successful" a single object is returned. It contains the property "Computer Name". In case of "Failed" an array of two objects is returned. It (the array itself) does not contain the property "Computer Name". In PowerShell v3 in some cases it is possible to use notation $array.SomePropertyOfContainedObject but in PowerShell v2 it is an error always. That is what you probably see.

You should iterate through the array of result objects, e.g. foreach($log in $Log_Successful) {...} and access properties of the $log objects.

And the last tip. In order to ensure that the result of Import-Csv call is always an array (not null or a single object) use the @() operator.

The code after fixes would be:

$logs = @(Import-Csv ... | where ...)
# $logs is an array, e.g. you can use $logs.Count

# process logs
foreach($log in $logs) {
    # use $log."Computer Name"
}
Sign up to request clarification or add additional context in comments.

1 Comment

OMFG i love you!!!!! Thank you soo much, I have been playing with every combination I could think of for like 9 hours!! thank you, i would up-vote this a 100 times!!
0

I'm not sure if this is the problem but you have a typo, in Where-Object you compare against "Succesful" and the value in the file is "Successful" (missing 's').

Anyway, what's not working?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.