In this script below. When I enter the whole script into the powershell command line then call it with a server name, it works fine. But when i call it from this script:
`sl C:\PowershellScripts
. ./psscript_Get-FreeSpaceFrag.ps1
$svl = gc 'C:\PowershellScripts\ebi_serverlist.txt'
$x = {foreach ($s in $svl) {write-host "Getting Disk Info for Server $s" -
foregroundcolor "Green"; Get-FreeSpaceFrag $s; start-sleep -s 5; }}
$x.invoke() | export-csv "C:\PowershellScripts\DiskInfo.csv" -NoTypeInformation`
It will not work, meaning that the csv file is empty after it processes for a while.
Function Get-FreeSpaceFrag ($s)
{
trap {write-host "Can't connect to WMI on server $s" -ForeGroundColor "Red"
continue
}
$dt = get-date
$Scope = new-object System.Management.ManagementScope "\\$s\root\cimv2"
$query = new-object System.Management.ObjectQuery "SELECT * FROM Win32_Volume"
$searcher = new-object System.Management.ManagementObjectSearcher $scope,$query
$SearchOption = $searcher.get_options()
$timeout = new-timespan -seconds 10
$SearchOption.set_timeout($timeout)
$SearchOption
$searcher.set_options($SearchOption)
$volumes = $searcher.get()
$fr = {foreach ($v in $volumes | where {$_.capacity -gt 0}){
$frag=($v.defraganalysis().defraganalysis).totalPercentFragmentation
$v | Add-Member -Name Frag -MemberType NoteProperty -Value $frag -Force -
PassThru
} }
$fr.invoke() | select @{N="Server";E={$_.Systemname}}, DriveLetter, Label,
Capacity, FreeSpace, @{N="PercentFree";E={"{0,9:N0}" -f
(($_.FreeSpace/1gb)/($_.Capacity/1gb)*100)}}, Frag, @{N="InfoDate";E={$dt}}
}
I think you’re making this a bit harder than it should be i.e. I’m not sure why you need part of the code in an anoymous scriptblock? Try this instead:
Not sure if it will solve the problem but you can also simplify this part of your function:
BTW rather than invoking a scriptblock like this
$fr.invoke()the canonical way in PowerShell is to use the call operator like so&$fr.