Работающая функция powershell не выполняет свою работу при вызове из C # - PullRequest
0 голосов
/ 10 января 2019

Похоже, я объяснил свою проблему недостаточно хорошо. Итак, вот мой Edit:

У меня есть функция powershell для открепления плиток меню Пуск в Windows. Исходя из этого: imgur.com / a / 0hRhDkW на это: imgur.com / a / rMCkfR9

Функция делает то, что должна, отлично работает без ошибок. Я могу вызвать файл * .ps1 через bat следующим образом:


    c:\Windows\System32\windowspowershell\v1.0\powershell.exe -NoProfile -executionpolicy remotesigned -File "C:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\self-deleting-script_user-settings.ps1"

или просто запустите его через powershell ISE.

Итак, это функция powershell, о которой мы говорим:


    function UnpinTiles
    {
        (New-Object -Com Shell.Application).
            NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').
            Items() | %{ $_.Verbs() } | ?{$_.Name -match 'Un.*pin from Start'} | %{$_.DoIt()}
    }

Функция является частью скрипта User-config. Может быть, кто-то заинтересован во всем этом. Вот, пожалуйста:


    #Info#
    #   administative privileges are needed, to write to locations that are shared by multiple users.
    #   therfore, you can only write to HKEY_CURRENT_USER and that's all we need!
    #Info#



    ## load into memory, Self deleting
    Remove-Item $MyINvocation.InvocationName


    ## Window Design
    [console]::ForegroundColor = "Blue"
    [console]::BackgroundColor = "White"
    #title
    $host.ui.RawUI.WindowTitle = "Flex - Configure User"
    cls

    #-------------------------------------------------------------#



    ## unpin all start menu tiles (english only. maybe change ?{$_.Name -match 'Un.*pin from Start'} for different language)
    function UnpinTiles
    {
        (New-Object -Com Shell.Application).
            NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').
            Items() | %{ $_.Verbs() } | ?{$_.Name -match 'Un.*pin from Start'} | %{$_.DoIt()}
    }


    #----------------------RegTweaks-START----------------------#
    ##________________________________________________________________________Format
    #Write-Host "   what i am doing" -ForegroundColor Gray
    #If (!(Test-Path "HKCU:\")) {
    #    New-Item -Path "HKCU:\" >$null 2>&1
    #}
    #Set-ItemProperty -Path "HKCU:\" -Name "" -Type DWord -Value 0 >$null 2>&1
    ##________________________________________________________________________Format


    try 
    {

    #Error Silent
    $ErrorActionPreference = 'SilentlyContinue'
        function RegTweaks
        {
            #Disable Windows Hello Notifications
            Write-Host "    Disable Windows Hello Notifications" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.HelloFace")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.HelloFace" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.HelloFace" -Name "Enabled" -Type DWord -Value 0 >$null 2>&1

            #Disable News Notifications
            Write-Host "    Disable News Notifications" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.BingNews_8wekyb3d8bbwe!AppexNews")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.BingNews_8wekyb3d8bbwe!AppexNews" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.BingNews_8wekyb3d8bbwe!AppexNews" -Name "Enabled" -Type DWord -Value 0 >$null 2>&1

            #Disable Edge Notifications
            Write-Host "    Disable Edge Notifications" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge" -Name "Enabled" -Type DWord -Value 0 >$null 2>&1

            #Disable Suggested Notifications
            Write-Host "    Disable Suggested Notifications" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.Suggested")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.Suggested" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.Suggested" -Name "Enabled" -Type DWord -Value 0 >$null 2>&1

            #Disable Store Notifications
            Write-Host "    Disable Store Notifications" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.WindowsStore_8wekyb3d8bbwe!App")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.WindowsStore_8wekyb3d8bbwe!App" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Microsoft.WindowsStore_8wekyb3d8bbwe!App" -Name "Enabled" -Type DWord -Value 0 >$null 2>&1

            #Disable Security and Maintenance Notifications
            Write-Host "    Disable Security and Maintenance Notifications" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.SecurityAndMaintenance")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.SecurityAndMaintenance" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.SecurityAndMaintenance" -Name "Enabled" -Type DWord -Value 0 >$null 2>&1

            #Disable Hotkey to Toggle Color Filters On or Off in Windows 10
            Write-Host "    Disable Hotkey to Toggle Color Filters On or Off in Windows 10" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\ColorFiltering")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\ColorFiltering" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\ColorFiltering" -Name "HotkeyEnabled" -Type DWord -Value 0 >$null 2>&1

            #Add This PC Desktop Icon
            Write-Host "    Add This PC Desktop Icon" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel" -Name "{20D04FE0-3AEA-1069-A2D8-08002B30309D}" -Type DWord -Value 0 >$null 2>&1

            #Taskbar, Hide Task View Button
            Write-Host "    Taskbar, Hide Task View Button" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "ShowTaskViewButton" -Type DWord -Value 0 >$null 2>&1

            #Taskbar, Hide Search
            Write-Host "    Taskbar, Hide Search" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Search" -Name "SearchboxTaskbarMode" -Type DWord -Value 0 >$null 2>&1

            #Show File Name Extensions
            Write-Host "    Show File Name Extensions" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "HideFileExt" -Type DWord -Value 0 >$null 2>&1

            #Prevent Sticky Keys
            Write-Host "    Prevent Sticky Keys" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\Control Panel\Accessibility\StickyKeys")) {
                New-Item -Path "HKCU:\Control Panel\Accessibility\StickyKeys" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\Control Panel\Accessibility\StickyKeys" -Name "Flags" -Type String -Value 506 >$null 2>&1

            #Make Desktop Menus Appear Faster
            Write-Host "    Prevent Sticky Keys" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\Control Panel\Desktop")) {
                New-Item -Path "HKCU:\Control Panel\Desktop" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name "MenuShowDelay" -Type String -Value 200 >$null 2>&1

            #Taskbar, Hide People Button
            Write-Host "    Prevent Sticky Keys" -ForegroundColor Gray
            If (!(Test-Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People")) {
                New-Item -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People" >$null 2>&1
            }
            Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced\People" -Name "PeopleBand" -Type String -Value 0 >$null 2>&1
        }    
    }
    catch 
    {}
    #------------------------RegTeaks-END-----------------------#








    #==========================================
    # EXECUTION 
    #==========================================
    cls
    $EXcount = 1
    Write-Host "        ========================================" -ForegroundColor Black
    Write-Host "        =========== Configuring User ===========" -ForegroundColor Black
    Write-Host -NoNewline "        ====== " -ForegroundColor Black
    Write-Host -NoNewline "Do not close this window!!" -ForegroundColor Red
    Write-Host " ======" -ForegroundColor Black
    Write-Host "        ========================================" -ForegroundColor Black
    Write-Host "`n"

    ## unpin all start menu tiles
    Write-Host "`n$EXcount. Unpin StartMenu tiles."
    $EXcount++
    UnpinTiles
    Write-Host -NoNewline "______________________________________________________|"
    Write-Host "Done!" -ForegroundColor Green


    ##Registry tweaks
    Write-Host "`n$EXcount. Adding Registry Tweaks"
    $EXcount++
    RegTweaks
    Write-Host -NoNewline "______________________________________________________|"
    Write-Host "Done!" -ForegroundColor Green

Теперь к моей проблеме. Как сказано, все работает нормально, только не тогда, когда я пытаюсь вызвать * .ps1 из программы на C #, например:

    Process.Start("C:\\Windows\\System32\\windowspowershell\\v1.0\\powershell.exe", $"-ExecutionPolicy ByPass -File {PathToFile}"); 

Функции выполняются, но плитки меню Пуск в Windows все еще там. И я должен понять, какого черта он не может этого сделать.

So

  • я называю это через летучую мышь, он может удалить плитки меню Пуск.
  • я называю это через C #, он не может удалить плитки меню звезды Windows.

1 Ответ

0 голосов
/ 11 января 2019

Если это ...

PathToFile

… - это полный UNC для скрипта с этой функцией, тогда, как отмечает TheIncorrigible1, вы просто вызываете скрипт, а не функцию в нем, пока не измените то, что вы опубликовали в этом.

function UnpinTiles
{
    (New-Object -Com Shell.Application).
        NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').
        Items() | %{ $_.Verbs() } | ?{$_.Name -match 'Un.*pin from Start'} | %{$_.DoIt()}
}

# Call the function
UnpinTiles

Если вы просто хотите запустить этот блок при вызове скрипта, просто сделайте это.

(New-Object -Com Shell.Application).
NameSpace('shell:::{4234d49b-0245-4df3-b780-3893943456e1}').
Items() | 
%{ $_.Verbs() } | 
?{$_.Name -match 'Un.*pin from Start'} | 
%{$_.DoIt()}

Если вы говорите, что в сценарии есть несколько функций, то вы запускаете файл для загрузки сценария, который вам все равно придется вызывать в качестве функции, которую предлагает TheIncorrigible1.

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