PowerShell:try 语句缺少 catch 或 finally 块

时间:2021-04-15 20:48:17

标签: powershell try-catch

我正在尝试使用 foreach 循环创建一个 try 语句。我查找的所有内容都显示此代码应该是正确的,但出于某种原因它说

The try statement is missing its catch or Finally block 我有 0 想法为什么会发生这种情况我确保 ALL { 和 } 匹配。即使我将其从 foreach 循环中取出,try 捕获也不起作用。

Clear-Host
Clear-Content .\PS.txt
$args1 = Get-Content .\names.txt
$args1 = $args1.Split(",")
$ArrComputers =  $args1

$i = 0
foreach ($Computer in $ArrComputers) 
{
 $Computer = $Computer.Trim(" ")

    try{
        $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled}
        

        "PASS " + $Computer +'|'
        $HDDInfo = ""
        $getIP, $computerSystem, $computerCPU, $hdds, $computerOS, $OS  = " "
        $i +=1
        $z = 0
        [string]$hdd = ""
        $getIP =[string](Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias Ethernet).IPAddress
        $myOBJ = "" | Select-Object "computer"
        $computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer
        $computerCPU = get-wmiobject Win32_Processor -Computer $Computer
        $hdds = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter drivetype=3
        $computerOS = get-wmiobject Win32_OperatingSystem -Computer $Computer
        $OS = $computerOS.caption + ", Service Pack: " + $computerOS.ServicePackMajorVersion
            write-host "System Information for: " $computerSystem.Name -BackgroundColor DarkCyan
            "CPU: " + $computerCPU.Name
            foreach ($computerhdd in $hdds) { 
                $z +=1
                If($z -eq 1){
                $PRHDDName = [string]$computerhdd.DeviceID
                } else {
                    $SECHDDName = [string]$computerhdd.DeviceID
                }

                $HDDInfo = [string]($HDDInfo+"<"+$computerhdd.DeviceID+">" + "HDD Capacity/" + "{0:N2}" -f ($computerHDD.Size/1GB) + "GB" )
                "HDD Drive Letter: " + $HDDInfo
            [string]$hdd = ([string]($computerHDD.Size/1GB) + [string]"," + [string]$hdd)
            }
            "RAM: " + "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB) + "GB"
            "OS: " + $OS
        
        
            $temp = [string]$myOBJ.computer
            [string]$myOBJ.computer = [string]("| !" + $Computer + ".! , +" + $getIP + '.+, a[' + $computerCPU.Name + ".] , ~" + $HDDInfo+ " ~, {" + $OS + ".} a|") 
            Add-Content .\PS.txt $myOBJ.computer
    } 
     #End of try
        catch[System.UnauthorizedAccessException]{
        Add-Content .\PS.txt "| Failed |"
        
    }catch{
        Add-Content .\PS.txt "| Failed |"
        "FAIL" + $_.Exception.GetType().FullName
    }


}

1 个答案:

答案 0 :(得分:2)

“catch”和“[System.UnauthorizedAccessException]”之间缺少空格