Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

You cannot call a method on a null-valued expression

Status
Not open for further replies.

woter324

Technical User
Jan 26, 2007
179
GB
Hi All,

I'm writing a PS function to add to my Exchange 2007 migration script that will stop migrating users if the log disk space gets too low, thus breaking the CCR and SCR.

I am very new to PS and this is one of my first attempts so please bare with me. Here is the script thus far:

Code:
function getFreeSpace([string]$server, [string]$sg){
$volumes = Get-WmiObject Win32_Volume -computername $server
	foreach ($vol in $volumes){
		#$label = $vol.Label
		#Write-Host $label
		$strSG = "Logs " + $sg
		if($vol.Label.contains($strSG)){
			[math]::round($vol.freespace/[long]$vol.Capacity,2)*[int]100
		}
	}
}

if(getFreeSpace "svr-excca06" "SG6" -lt [int]99){
	$strFS = getFreeSpace "svr-excca06" "SG6"
	"Free Space = $strFS %"
	#I'll do something else here later on
}

I am thinking that one of the volumes doesn't have a label, thus when I call contains it returns null. Fair enough. So rather than creating the $label variable, I put it straight into the if statement. In my head, if $vol.Label.contains is null, then, surely it should ignore it and not complain?

The output eventually returns what I want, after the error:
Code:
ERROR: You cannot call a method on a null-valued expression.
ERROR: At line:22 char:25
ERROR: +         if($vol.Label.contains( <<<< $strSG)){
ERROR: You cannot call a method on a null-valued expression.
ERROR: At line:22 char:25
ERROR: +         if($vol.Label.contains( <<<< $strSG)){
Free Space = 99.00 %

*** PowerShell Script finished. ***

If any of you geni out there have any pointers for me, I'd be very greatful if you would share them.

Many thanks

Woter
 
Ok, I've worked it out, so I don't get any errors by telling the script to ignore null entries. I also had the evaluation wrong too. It might still be wrong, but it works for what I want :) Still open to suggestions though.

Code:
function getFreeSpace([string]$server, [string]$sg){
$volumes = Get-WmiObject Win32_Volume -computername $server
	foreach ($vol in $volumes){
		if($vol.Label -ne $NULL){
			$strSG = "Logs " + $sg
			if($vol.Label.contains($strSG)){
				$freeSpace = [math]::round($vol.freespace/[long]$vol.Capacity,2)*[int]100
			}
		}
	}
if($freeSpace -lt [int]25) {
	return $TRUE
}
}

if(getFreeSpace "svr-exccp05" "SG6" = $TRUE){
	"Stop processing users."
	}
else{ 
	"Continue..."
}

Hope it may help someone else.

Thanks

Woter
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top