简体   繁体   中英

cmdlets not recognized on the first run in powershell

I am facing an issue with the first run of powershell code.

  1. cmdlets and user defined function are not recognized in the first run but works fine if I run the code again
  2. user defined function takes values from previous run.ie basically we need to run the code twice to get the correct result

Code:

$resultVar=get-CPUAndMemUtilization -computername $computername -CPUCriteria $CPUCriteria -MemCriteria $MemCriteria
#Write-Host  "Mme:"$resultVar;
$CPUMem += [PSCustomObject] @{  
        CPULoad = "$($resultVar[0])" 
        MemLoad = "$($resultVar[1])" 
} 
Write-Host $CPUMem;


function get-CPUAndMemUtilization($computername,$CPUCriteria,$MemCriteria)
{

    $Memstatus=$null;
    $CPUstatus=$null;
    $AVGProc = Get-WmiObject -computername $computername win32_processor |  Measure-Object -property LoadPercentage -Average | Select Average 
    $OS = gwmi -Class win32_operatingsystem -computername $computername | 
    Select-Object @{Name = "MemoryUsage"; Expression = {“{0:N2}” -f ((($_.TotalVisibleMemorySize - $_.FreePhysicalMemory)*100)/ $_.TotalVisibleMemorySize) }} 
    $result += [PSCustomObject] @{  
        ServerName = "$computername" 
        CPULoad = "$($AVGProc.Average)%" 
        MemLoad = "$($OS.MemoryUsage)%" 
    } 

    if($AVGProc.Average -lt $CPUCriteria)
    {
        $Memstatus=1;
    }else{
        $Memstatus=0;
    }


    if($OS.MemoryUsage -lt $MemCriteria)
    {
        $CPUstatus=1;
    }else{
        $CPUstatus=0;
    } 

    $CPUstatus
    $Memstatus
return;
}

Code return the System CPU & Me usage of the system in CPU & Mem utilization for a system
Error:

get-CPUAndMemUtilization : The term 'get-CPUAndMemUtilization' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

You call the function before you import it (so it doesn't exist) into the powershell session, just swap those 2 things:

function get-CPUAndMemUtilization($computername,$CPUCriteria,$MemCriteria)
{
...
}
$resultVar=get-CPUAndMemUtilization -computername $computername -CPUCriteria $CPUCriteria -MemCriteria $MemCriteria
#Write-Host  "Mme:"$resultVar;
$CPUMem += [PSCustomObject] @{  
        CPULoad = "$($resultVar[0])" 
        MemLoad = "$($resultVar[1])" 
} 
Write-Host $CPUMem;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM