If / Else Помощь в Powershell - PullRequest
0 голосов
/ 15 мая 2019

Запуск оператора IF / Else и, если "false", я хочу, чтобы он запустил поиск текущего драйвера NVIDIA и сказал мне текущую версию, затем остановил скрипт. Пробовал пару разных вещей безрезультатно. В настоящее время он продолжает выполнение сценария и запускает «Get-WmiObject» в следующем порядке.


Function Namespace_Check
{    Write-Host "Checking available namepace" -ForegroundColor Green

     if ((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV'){return}

     else { return (Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like "*nvidia*"})}

     Write-Host "If Stopped, install latest NVIDIA driver from SWE"
     Write-Host "Complete" -ForegroundColor Green   

}

Вот весь сценарий, если в логике должны быть другие изменения


Function Namespace_Check
{    Write-Host "Checking available namepace" -ForegroundColor Green
     Write-Host "Complete" -ForegroundColor Green

     if ((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV'){return}

     else { 

     exit (Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like "*nvidia*"})
     Write-Warning "Install latest NVIDIA driver from SWE"
     Write-Host

     }       

}

Function InstallSWE
{
    Write-Host "Installing SWE Icon..." -ForegroundColor Green
    $ps = new-object System.Diagnostics.Process
    $ps.StartInfo.FileName = "\\nt-iss-1\setools\xsetup.exe"
    $ps.StartInfo.Arguments = " -Silent -NoPrompt -NoBanner"
    Write-Host "    Execute Software Express"
    [Void]$ps.start()
    $ps.WaitForExit()
    Write-Host "Complete" -ForegroundColor Green
}

Function CheckNVIDIADriver
{
    Write-Host "Checking NVIDIA Drivers..." -ForegroundColor Green
    $productName = Get-WmiObject -namespace "root\cimv2\nv" -Class Gpu | Select -ExpandProperty productName
    $driverVersion = Get-Wmiobject -namespace "root\cimv2\nv" -class System | Select -ExpandProperty verDisplayDriver | Select -ExpandProperty strValue
    Write-Host "    Product Name        : $productName"
    Write-Host "    Video Driver Version: $driverVersion"
    Write-Host "Complete" -ForegroundColor Green
}

Function SetNVIDIA3DGlobalPreset
{
    Write-Host "Setting NVIDIA 3D Global Preset..." -ForegroundColor Green
    $global3DPreset = "Dassault Systemes CATIA - compatible"
    $profileManager = Get-WmiObject -namespace "root\cimv2\nv" -Class ProfileManager
    "Change Global 3D Preset to $global3DPreset"
    [void](Invoke-WmiMethod -Path $profileManager.__PATH -Name setCurrentProfile3D -ArgumentList $global3DPreset, $null)
    Write-Host "Complete" -ForegroundColor Green
}

Function SetScreenSaver
{
    Write-Host "Setting Screen Saver..." -ForegroundColor Green
    $regkeypath = "HKCU:\Control Panel\Desktop"
    $screensaver = "C:\Windows\SysWOW64\CORPOR~1.SCR"
    Write-Host "    Change Screen Saver to Corporate Screen Saver"
    Set-ItemProperty -Path $regkeypath -Name "SCRNSAVE.EXE" -Value $screensaver
    Write-Host "Complete" -ForegroundColor Green
}

Function ChangePowerSettings
{
    Write-Host "Changing Power Settings..." -ForegroundColor Green
    Write-Host "    Disable Monitor Timeout"
    powercfg -x -monitor-timeout-ac 10
    powercfg -x -monitor-timeout-dc 10
    Write-Host "    Disable Disk Timeout"
    powercfg -x -disk-timeout-ac 0
    powercfg -x -disk-timeout-dc 0
    Write-Host "    Disable Standby Timeout"
    powercfg -x -standby-timeout-ac 0
    powercfg -x -standby-timeout-dc 0
    Write-Host "    Disable Hibernate and Hybrid Sleep"
    powercfg -x -hibernate-timeout-ac 0
    powercfg -x -hibernate-timeout-dc 0
    powercfg -h off
    Write-Host "Complete" -ForegroundColor Green
}

Function ChangeVirtualMemory
{ 
    Write-Host "Changing Virtual Memory Settings..." -ForegroundColor Green
    $mem = [Math]::Round((Get-WmiObject -Class Win32_ComputerSystem |Select -ExpandProperty TotalPhysicalMemory) / [Math]::pow(1024, 3))
    $initialSize = 2048 * $mem
    $maximumSize = 2 * $initialSize

    Write-Host "    Disable Automatic Managed Page File"
    $System = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges
    $System.AutomaticManagedPagefile = $False
    [Void]$System.Put()

    Write-Host "    Set Page File Size (Initial Size: $initialSize MB / Maximum Size: $maximumSize MB)"
    $PageFile = Get-WmiObject -class Win32_PageFileSetting
    $PageFile.InitialSize = $initialSize
    $PageFile.MaximumSize = $maximumSize
    [Void]$PageFile.Put()

    Write-Host "Complete" -ForegroundColor Green
}

Function EnableRDP
{
    Write-Host "Enabling Remote Desktop and User..." -ForegroundColor Green
    $computername = $(gc env:computername)
    $RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\CIMV2\TerminalServices
    Write-Host "    Enable Remote Desktop"
    $result = $RDP.SetAllowTsConnections(1, 1)

    Try
    {
        $user ="CAxILABRemoteUsers"
        $domain ='NW'
        $objUser = [ADSI]("WinNT://$domain/$user") 
        $objGroup = [ADSI]("WinNT://$computername/Remote Desktop Users") 
        Write-Host "    Add Remote Desktop User $domain\$user"
        $objGroup.PSBase.Invoke('Add',$objUser.PSBase.Path)
    }

    Catch
    {
    }

     Write-Host "Complete" -ForegroundColor Green
}

Function CheckAdministrator  
{  
    $user = [Security.Principal.WindowsIdentity]::GetCurrent();
    (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

# Filename: CAxILab_Final_Config.ps1
$pshost = get-host
$pswindow = $pshost.ui.rawui
$newsize = $pswindow.buffersize
$newsize.height = 999
$pswindow.buffersize = $newsize
$newsize = $pswindow.windowsize
#$newsize.height = 60
#$pswindow.windowsize = $newsize

$host.ui.RawUI.ForegroundColor = "White"
$isAdmin = CheckAdministrator

if ($isAdmin)
{
    Namespace_Check
    Write-Host
    InstallSWE
    Write-Host
    CheckNVIDIADriver
    Write-Host
    SetNVIDIA3DGlobalPreset
    Write-Host
    SetScreenSaver
    Write-Host
    ChangePowerSettings
    Write-Host
    ChangeVirtualMemory
    Write-Host
    EnableRDP
    Write-Host
}

else
{
    Write-Warning "Administrator rights is required to run this script"
    Write-Host
}

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# end of script

1 Ответ

0 голосов
/ 15 мая 2019

Если вы хотите, чтобы скрипт полностью останавливался, когда пространство имен не найдено, измените функцию Namespace_Check на что-то вроде этого:

Function Namespace_Check { 
     Write-Host "Checking available namepace" -ForegroundColor Green

     if (!((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV')) {
         # if we got here, the namespace is not found
         # output the current version, then stop the script
         $driver = Get-WmiObject Win32_PnPSignedDriver| 
                        Select-Object devicename, driverversion | 
                        Where-Object {$_.devicename -like "*nvidia*"}

         Write-Host "If Stopped, install latest NVIDIA driver from SWE"

         if ($driver) {
            Write-Host "Current driver(s)" -ForegroundColor Yellow
            $driver | Format-Table -AutoSize
         }
         else {
            Write-Warning "No nvidia drivers found"
         }

         Write-Host "Script Complete" -ForegroundColor Green 

         # stop the script
         exit
     }
}

В вашей версии вы пытаетесь записать в консоль после вы вышли из функции, используя оператор return.Поэтому эти строки никогда не будут выполнены.


Редактировать

В качестве альтернативы, вы можете заставить функцию Namespace_Check возвращать значение $ true или $ false, напримерthis:

Function Namespace_Check { 
     Write-Host "Checking available namepace" -ForegroundColor Green

     if (!((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV')) {
         # if we got here, the namespace is not found
         # output the current version, then stop the script
         $driver = Get-WmiObject Win32_PnPSignedDriver| 
                        Select-Object devicename, driverversion | 
                        Where-Object {$_.devicename -like "*nvidia*"}

         Write-Host "If Stopped, install latest NVIDIA driver from SWE"

         if ($driver) {
            Write-Host "Current driver(s)" -ForegroundColor Yellow
            $driver | Format-Table -AutoSize
         }
         else {
            Write-Warning "No nvidia drivers found"
         }

         Write-Host "Script Complete" -ForegroundColor Green 

         return $false
     }
     return $true
}

и в основной части вашего скрипта выполните

if ($isAdmin) {
    if (Namespace_Check) {
        Write-Host
        InstallSWE
        Write-Host
        CheckNVIDIADriver
        Write-Host
        SetNVIDIA3DGlobalPreset
        Write-Host
        SetScreenSaver
        Write-Host
        ChangePowerSettings
        Write-Host
        ChangeVirtualMemory
        Write-Host
        EnableRDP
        Write-Host
    }
}
else {
    Write-Warning "Administrator rights is required to run this script"
    Write-Host
}

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# end of script

. Это приведет к корректному завершению скрипта вместо использования оператора exit.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...