Help with if statement

Hi all,

Wonder if anyone more learned than myself with Powershell can help me out. As I say I’m a beginner so please bear with me if my request seems a bit simple. I am attempting to write a script that grabs the contents of a particular column in a csv file and then runs a command against it, in this instance ‘Get-SCOMMonitor’. Once it has run this it should then output it to a csv file.

Now, this actually works but here is the annoying part. As the script works its way through the spreadsheet, if it comes across a line that does not generate a valid result then it just skips it. What I want it to do on my outputted spread sheet is have some kind of message on the said line such as ‘Monitor not valid’ or something like that.

My original input csv file could be something like 600 lines long but after running my script it could say reduce to 200 lines and then I wouldn’t be able to match up the results with my original spreadsheet. I need the number of lines to match basically. My original script without any if statements look like: -

$csv = Import-Csv D:\Scripts\temp\monitors.csv
$output = foreach ($line in $csv) {
Get-SCOMMonitor -Name $line.MonitorName

$output | Export-csv -Path D:\Scripts\temp\output.csv -NoTypeInformation

I was hoping to use something like: if ($output -eq $null) { Write-Host “Monitor could not be determined” }

I couldn’t get it to work properly so hopefully someone will look at this and easily spot my problem.



i don’t use SCOM so not sure exactly what is returned from the cmdlet, however, you can’t just “write” to the csv file the way you are trying, my suggestion is to have 2 output files

$erroractionpreference = "stop"
$csv = Import-Csv D:\Scripts\temp\monitors.csv
$output = "D:\Scripts\temp\output.csv"
$erroroutput = "D:\Scripts\temp\errors.txt"
foreach ($line in $csv)
	Get-SCOMMonitor -Name $line.MonitorName|Export-Csv $output -NoTypeInformation -append
	"Monitor could not be determined for $($line.monitor)"|Out-File $erroroutput -append

I’m not familiar with the Get-SCOMMonitor either.

I believe you’re overwriting the files in the foreach. You should add the append parameter.

good catch Paal
i updated the code above to include appends

Thanks for the responses guys this helped! :slight_smile: