Как заставить PowerShell запрашивать неподписанные скрипты - PullRequest
0 голосов
/ 12 июня 2018

Политика выполнения в моей среде: AllSigned:

PS E:\Temp> Get-ExecutionPolicy
AllSigned

Когда я пытаюсь выполнить ненадежный скрипт, он выдает ошибку:

& : File C:\temp\anz.ps1 cannot be loaded. The file C:\temp\any.ps1 is not
digitally signed.
You cannot run this script on the current system. For more information about
running scripts and setting execution policy, see about_Execution_Policies at
http://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3
+ & .\any.ps1
+   ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

Как мне сделатьPowerShell подскажет мне, хочу ли я выполнить скрипт или нет?

Что-то вроде:

Предупреждение безопасности
Запускать только те сценарии, которым вы доверяете.Хотя сценарии из Интернета могут быть полезны, этот сценарий может нанести вред вашему компьютеру.Хотите запустить. \ Temp.ps1?
[D] Не запускать [R] Выполнить один раз [S] Приостановлено:

Примечание: я не хочу обходить или подавлятьпроворная.

Ответы [ 2 ]

0 голосов
/ 04 декабря 2018

Вы можете попробовать выполнить следующую команду в Power Shell как и администратор

Исправление заключается в запуске Set-ExecutionPolicy и изменении параметра политики выполнения.

Set-ExecutionPolicy -Область действия процесса -ExecutionPolicy Bypass

«Обход» означает, что ничего не заблокировано, и никакие предупреждения, подсказки или сообщения не будут отображаться.

0 голосов
/ 13 июня 2018

Вы можете добавить функцию для проверки файла:

function Test-FileSafety {
    # This function simply returns $true when the file is ok or the user decided to
    # go ahead and run it even though he/she was warned.
    # If the user decided it was too tricky and bailed out, the function returns $false
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [ValidateScript({Test-Path $_ -PathType Leaf})] 
        [Alias ('Path')]
        [string]$FileName
    )

    Add-Type -AssemblyName System.Windows.Forms
    $letsGo = $true

    # first test if the file was downloaded from internet (and was not already unblocked)
    if (Get-Item $FileName -Stream zone*) {
        $message  = "Run only scripts that you trust.`r`n"
        $message += "While scripts from the Internet can be useful this script can potentially harm your computer.`r`n`r`n"
        $message += "Do you want to allow '$FileName' ?"

        $result = [System.Windows.Forms.MessageBox]::Show($message, "Security Warning", 3)
        # evaluate the users response and act upon it
        switch ($result) {
            Yes    { <# user wants to run #> Unblock-File -Path $FileName ; break }
            No     { <# user decided not to run the script #> ; $letsGo = $false; break }
            Cancel { <# user bailed out #> ; $letsGo = $false; break }
        }
    }

    # next test if the file is digitally signed or not
    if ($letsGo -and (Get-AuthenticodeSignature -FilePath $FileName).Status -eq 'NotSigned') {
        $message  = "Run only scripts that you trust.`r`n"
        $message += "The script is not digitally signed.`r`n`r`n"
        $message += "Do you still want to run '$FileName' ?"

        $result = [System.Windows.Forms.MessageBox]::Show($message, "Security Warning", 3)
        # evaluate the users response and act upon it
        switch ($result) {
            Yes    { <# user wants to run even though the script is not digitally signed #> ; break}
            No     { <# user decided it was too dangerous and does not want to run the script #> ; $letsGo = $false; break}
            Cancel { <# user bailed out #> ; $letsGo = $false; break}
        }
    }

    return $letsGo
}

и использовать его как:

if ((Test-FileSafety -FileName "C:\temp\anz.ps1")) {
    # run the script
}
else {
    # do nothing, the user cancelled
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...