简体   繁体   English

在Powershell的首次运行中无法识别cmdlet

[英]cmdlets not recognized on the first run in powershell

I am facing an issue with the first run of powershell code. 我在第一次运行Powershell代码时遇到了问题。

  1. cmdlets and user defined function are not recognized in the first run but works fine if I run the code again cmdlet和用户定义的函数在第一次运行中无法识别,但是如果我再次运行代码,则可以正常工作
  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 代码返回系统的CPU和内存使用率
Error: 错误:

get-CPUAndMemUtilization : The term 'get-CPUAndMemUtilization' is not recognized as the name of a cmdlet, function, script file, or operable program. get-CPUAndMemUtilization:术语“ get-CPUAndMemUtilization”未被识别为cmdlet,函数,脚本文件或可运行程序的名称。 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: 在将函数导入(因此它不存在)到powershell会话中之前,请先调用该函数,只需交换以下两点即可:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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