如何使 PowerShell 提示输入未签名的脚本



我的环境中的执行策略是AllSigned

PS E:\Temp> Get-ExecutionPolicy 全部签名

当我尝试执行不受信任的脚本时,它会抛出错误:

&: 无法加载文件 C:\temp\anz.ps1。文件 C:\temp\any.ps1 不是 数字签名。 不能在当前系统上运行此脚本。有关以下内容的更多信息 运行脚本和设置执行策略,请参阅about_Execution_Policies http://go.microsoft.com/fwlink/?LinkID=135170。 行:1 字符:3 + & .\any.ps1 +   ~~~~~~~~~~~~~~~~~~~~~~~~~ + 类别信息 : 安全错误: (:) [], PSSecurityException + 完全限定错误 ID : 未经授权访问

如何让 PowerShell 提示我是否要执行脚本?

像这样:

安全警告
仅运行您信任的脚本。 虽然来自 Internet 的脚本可能很有用,但此脚本可能会损害您的计算机。 是否要运行 .\temp.ps1?
[D] 不要运行 [R] 运行一次 [S] 暂停:

注意:我不想绕过或按下提示。

您可以添加一个函数来先检查文件:

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:tempanz.ps1")) {
# run the script
}
else {
# do nothing, the user cancelled
}

您可以尝试以管理员身份在 Power shell 中运行以下命令

解决方法是运行设置执行策略并更改执行策略设置。

设置-执行策略 -

范围进程 -执行策略绕过

"绕过"表示未阻止任何内容,也不会显示任何警告、提示或消息。

相关内容

  • 没有找到相关文章

最新更新