Задержка запуска Windows Embedded Shell Launcher - PullRequest
0 голосов
/ 28 февраля 2019

Обновлен запрос Я пытаюсь настроить пользователя Windows в качестве пользователя "Киоска".Это сделано для того, чтобы они были полностью закрыты от функций Windows и имели доступ только к одному приложению.Я использую приложение для запуска встроенной оболочки Windows, чтобы назначить, какое приложение запускать с этим пользователем и до сих пор имело успех.

Проблема, с которой я сталкиваюсь, заключается в том, что приложению требуется лицензия от другого программного обеспечения, настроенного на запуск при запуске, но оболочка запускается быстро, и приложение, которое я хочу запустить, отображает ошибку лицензии на экране.Мне нужно отложить запуск оболочки.

Я использую сценарий power shell для настройки оболочки, но из исследования https://social.msdn.microsoft.com/Forums/en-US/d0d9fc55-ab03-43e7-9c3a-10ce85060386/how-to-custom-shell?forum=quebeccomponentsforum, этот скрипт просто устанавливает значение реестра HKLM\Software\Microsoft\Windows NT\CurrentVersion\WinlogonShell= "something.exe".

Таким образом, при запуске, даже если я установил задержку Start-Sleep или попытался выяснить, запущена ли программа лицензирования перед запуском приложения, программа никогда не запускается при запуске, так как используетрегистр.

Есть ли способ отложить запуск этой оболочки или отложить запуск этого регистра при запуске?Я добавил нижеприведенный сценарий, который я использую для настройки оболочек и ссылок, на основе которых я основал код https://docs.microsoft.com/en-us/windows/configuration/kiosk-shelllauncher

     #----- Function to Check if shell launcher license is enabled ------#
    function Check-ShellLauncherLicenseEnabled
    {
        [string]$source = @"
    using System;
    using System.Runtime.InteropServices;

    static class CheckShellLauncherLicense
    {
        const int S_OK = 0;

        public static bool IsShellLauncherLicenseEnabled()
        {
            int enabled = 0;

            if (NativeMethods.SLGetWindowsInformationDWORD("EmbeddedFeature-ShellLauncher-Enabled", out enabled) != S_OK) {
                enabled = 0;
            }
            return (enabled != 0);
        }

        static class NativeMethods
        {
            [DllImport("Slc.dll")]
            internal static extern int SLGetWindowsInformationDWORD([MarshalAs(UnmanagedType.LPWStr)]string valueName, out int value);
        }

    }
    "@

        $type = Add-Type -TypeDefinition $source -PassThru

        return $type[0]::IsShellLauncherLicenseEnabled()
    }

    [bool]$result = $false

    $result = Check-ShellLauncherLicenseEnabled
    "`nShell Launcher license enabled is set to " + $result
    if (-not($result))
    {
        "`nThis device doesn't have required license to use Shell Launcher"
        exit
    }

    $COMPUTER = "localhost"
    $NAMESPACE = "root\standardcimv2\embedded"

    # Create a handle to the class instance so we can call the static methods.
    try {
        $ShellLauncherClass = [wmiclass]"\\$COMPUTER\${NAMESPACE}:WESL_UserSetting"
        } catch [Exception] {
        write-host $_.Exception.Message; 
        write-host "Make sure Shell Launcher feature is enabled"
        exit
        }


    #-----Function to retrieve the SID for the user account on the machine-----#

    function Get-UsernameSID($AccountName) {

        $NTUserObject = New-Object System.Security.Principal.NTAccount($AccountName)
        $NTUserSID = $NTUserObject.Translate([System.Security.Principal.SecurityIdentifier])

        return $NTUserSID.Value
    }

    #---- Get the SID's for accounts-----# 

    $Operator_SID = Get-UsernameSID("Operator")
    $Admin_SID = Get-UsernameSID("Administrator")

    #----- Define actions to take when the shell program exits -----#

    $restart_shell = 0
    $restart_device = 1
    $shutdown_device = 2


    #----- Set Default Shell ----#
    # This example sets the command prompt as the default shell, and restarts the device if the command prompt is closed. 

    # $ShellLauncherClass.SetDefaultShell("cmd.exe", $restart_device)

    #----- Default Shell Display -----#
    # Display the default shell to verify that it was added correctly.

    $DefaultShellObject = $ShellLauncherClass.GetDefaultShell()

    "`nDefault Shell is set to " + $DefaultShellObject.Shell + " and the default action is set to " + $DefaultShellObject.defaultaction

    # ----- Operator Shell Set -----#
     $ShellLauncherClass.SetCustomShell($Operator_SID, "C:\Components\application.exe", ($null), ($null), $restart_shell)       
   # ----- Admin Shell Set -----#
    # Set Explorer as the shell for administrator.

     $ShellLauncherClass.SetCustomShell($Admin_SID, "explorer.exe")

    #-----Enable the Shell Launcher -----#

    $ShellLauncherClass.SetEnabled($TRUE)

    $IsShellLauncherEnabled = $ShellLauncherClass.IsEnabled()

    "`nEnabled is set to " + $IsShellLauncherEnabled.Enabled

    #-----Remove Custom Shell -----#
    # To remove a user shell, comment out the $ShelllauncherClass.SetCustomShell command and uncomment the required RemoveCustomShell command

    # $ShellLauncherClass.RemoveCustomShell($Admin_SID)

    # $ShellLauncherClass.RemoveCustomShell($Operator_SID)

    #----- Disable Shell Launcher -----# Uncomment to use

    # $ShellLauncherClass.SetEnabled($FALSE)

    # $IsShellLauncherEnabled = $ShellLauncherClass.IsEnabled()

    # "`nEnabled is set to " + $IsShellLauncherEnabled.Enabled

    #----- Display all the custom shells defined -----#

    "`nCurrent settings for custom shells:"
    Get-WmiObject -namespace $NAMESPACE -computer $COMPUTER -class WESL_UserSetting | Select Sid, Shell, DefaultAction

1 Ответ

0 голосов
/ 28 февраля 2019

Гораздо более сложный вариант - проверить, запущен ли ожидаемый вами процесс.

Если он работает в том же окне, используйте Get-Process, чтобы проверить, работает ли он.Или Get-NetTCPConnection, если он начинает прослушивать определенный порт (если к серверу лицензий обращаются через локальную сеть, тогда вы можете выбрать этот вариант).

do {
    sleep 10 
    $proc = Get-Process -Name licsrv -ea silentlycontinue
} until ($proc)

Start-process ...

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

$loop = 0
do {
    sleep 10 
    $proc = Get-Process -Name licsrv -ea silentlycontinue
    $loop++
} until ($proc -or $loop -ge 60) #wait until proc runs or 10 mins
If ($proc) {Start-process ... } # the process is running, not loop termination
Else {Throw "some error message"}
...