Hi, newbie Powershell person needing some assistance…
I’ve written a powershell script that checks all my servers for disk space (yep, the usual first powershell script), and compares it to the last time the script was run. This all works OK.
I am now trying to covert this to functions, and I have run across a problem.
The first function accepts a list of computernames and outputs the disk space results as custom objects. This gets exported to a an XML file so that it can be used for comparison the next time the script is run.
$ServerList = "CN1", "CN2", "CN3" $CurrentDriveStats = Get-DriveStats -ComputerName $ServerList $CurrentDriveStats | Export-Clixml "C:\temp\statfile.xml"
My object looks like this:
PS C:\temp> $CurrentDriveStats | gm TypeName: System.Management.Automation.PSCustomObject Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() ComputerName NoteProperty System.String ComputerName DriveLetter NoteProperty System.String DriveLetter DriveSizeInGB NoteProperty System.Int32 DriveSizeInGB DriveSpaceInGB NoteProperty System.Int32 DriveSpaceInGB DriveSpaceInPercent NoteProperty System.Int32 DriveSpaceInPercent
This all works OK.
Next time it is run, the XML file is imported so that it can be used as a comparison:
$PreviousDriveStats = Import-Clixml "C:\temp\statfile.xml"
I then pass the previous stats and the current stats to a comparison function (which matches up the previous and current objects and outputs new objects):
Compare-DriveStats $PreviousDriveStats, $CurrentDriveStats | Format-Table -AutoSize
Function Compare-DriveStats ($PreviousDriveStats, $CurrentDriveStats)
{
Begin {}
Process {
ForEach ($C in $CurrentDriveStats) {
ForEach ($P in $PreviousDriveStats) {
# Write-Output $P.ComputerName, $P.DriveLetter, $C.ComputerName, $C.DriveLetter
If (($P.ComputerName -eq $C.ComputerName) -And ($P.DriveLetter -eq $C.DriveLetter)) {
#Build hash table of results - NB [Ordered] omitted as PS3+ only
$Props = @{'ComputerName' = $P.ComputerName;
'DriveLetter' = $P.DriveLetter;
'DriveSizeInGB' = $P.DriveSizeInGB;
'PreviousDriveSpaceInGB' = $P.DriveSpaceInGB;
'PreviousDriveSpaceInPercent' = $P.DriveSpaceInPercent;
'CurrentDriveSpaceInGB' = $C.DriveSpaceInGB;
'CurrentDriveSpaceInPercent' = $C.DriveSpaceInPercent}
#Create object to be returned
$Obj = New-Object -TypeName PSObject -Property $Props
#Return the object
Write-Output $Obj
}
}
}
}
End {}
}
Now this works as a script but not as a function. I’ve been looking at this for a few days on and off and I can’t work out if I have made a silly mistake or I have a not understood a concept somewhere.
I would be really grateful if someone could point out where I am going wrong - maybe I am attacking the problem the wrong way?
Thanks and regards,