如何运行PowerShell脚本而不向用户显示窗口或任何其他符号?

换句话说,脚本应该在后台安静地运行,而不需要向用户发出任何信号。

不使用第三方组件的答案可获得额外分数:)


您可以使用PowerShell社区扩展来完成以下操作:

start-process PowerShell.exe -arg $pwd\foo.ps1 -WindowStyle Hidden

你也可以用VBScript: http://blog.sapien.com/index.php/2006/12/26/more-fun-with-scheduled-powershell/这样做

计划隐藏的PowerShell任务(Internet Archive) 更多的乐趣与计划的PowerShell(互联网档案)

(通过这个论坛。)


你可以像这样运行它(但这会显示一个窗口):

PowerShell.exe -WindowStyle hidden { your script.. }

或者您可以使用我创建的一个帮助文件来避免名为PsRun.exe的窗口,它正是这样做的。您可以在PowerShell中使用WinForm GUI运行计划任务中下载源文件和exe文件。我用它来完成计划好的任务。

已编辑:正如Marco所指出的,此-WindowStyle参数仅适用于V2及以上版本。


我从c#运行时遇到了这个问题,在Windows 7上,“交互式服务检测”服务在以SYSTEM帐户运行隐藏的powershell窗口时弹出。

使用"CreateNoWindow"参数可以防止ISD服务弹出警告。

process.StartInfo = new ProcessStartInfo("powershell.exe",
    String.Format(@" -NoProfile -ExecutionPolicy unrestricted -encodedCommand ""{0}""",encodedCommand))
{
   WorkingDirectory = executablePath,
   UseShellExecute = false,
   CreateNoWindow = true
};

这里有一种不需要命令行参数或单独启动器的方法。它并不是完全不可见的,因为在启动时确实会暂时显示一个窗口。但它很快就消失了。如果你想通过双击资源管理器或通过开始菜单快捷方式(当然包括启动子菜单)启动脚本,我认为这是最简单的方法。我喜欢它是脚本本身代码的一部分,而不是外部的东西。

把这个放在你的脚本前面:

$t = '[DllImport("user32.dll")] public static extern bool ShowWindow(int handle, int state);'
add-type -name win -member $t -namespace native
[native.win]::ShowWindow(([System.Diagnostics.Process]::GetCurrentProcess() | Get-Process).MainWindowHandle, 0)

下面是一行代码:

mshta vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""powershell -NoLogo -Command """"& 'C:\Example Path That Has Spaces\My Script.ps1'"""""", 0 : window.close")

虽然这可能会让窗口非常短暂地闪现,但这种情况应该很少发生。


我认为在运行后台脚本时隐藏PowerShell控制台屏幕的最好方法是这个代码(“Bluecakes”答案)。

我将这段代码添加到需要在后台运行的所有PowerShell脚本的开头。

# .Net methods for hiding/showing the console in the background
Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'
function Hide-Console
{
    $consolePtr = [Console.Window]::GetConsoleWindow()
    #0 hide
    [Console.Window]::ShowWindow($consolePtr, 0)
}
Hide-Console

如果这个答案是帮助你,请在这篇文章中投票给“蓝蛋糕”。


我也有同样的问题。我发现如果你去任务调度器的任务,正在运行powershell.exe脚本,你可以点击“运行无论用户是否登录”,这将永远不会显示powershell窗口时,任务运行。


我创建了一个小工具,通过原始文件将调用传递给任何你想要启动无窗口的控制台工具:

https://github.com/Vittel/RunHiddenConsole

编译完成后,只需将可执行文件重命名为“<targetExecutableName>w.exe”(附加一个“w”),并将其放在原始可执行文件旁边。 然后你可以用通常的参数调用e.G. powershell .exe,它不会弹出一个窗口。

如果有人知道如何检查创建的进程是否等待输入,我会很高兴包括你的解决方案:)


这是一个有趣的演示控制控制台的各种状态,包括最小化和隐藏。

Add-Type -Name ConsoleUtils -Namespace WPIA -MemberDefinition @'
   [DllImport("Kernel32.dll")]
   public static extern IntPtr GetConsoleWindow();
   [DllImport("user32.dll")]
   public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'@

$ConsoleMode = @{
 HIDDEN = 0;
 NORMAL = 1;
 MINIMIZED = 2;
 MAXIMIZED = 3;
 SHOW = 5
 RESTORE = 9
 }

$hWnd = [WPIA.ConsoleUtils]::GetConsoleWindow()

$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.MAXIMIZED)
"maximized $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.NORMAL)
"normal $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.MINIMIZED)
"minimized $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.RESTORE)
"restore $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.HIDDEN)
"hidden $a"
Start-Sleep 2
$a = [WPIA.ConsoleUtils]::ShowWindow($hWnd, $ConsoleMode.SHOW)
"show $a"

ps1隐藏在任务调度程序和快捷方式中

    mshta vbscript:Execute("CreateObject(""WScript.Shell"").Run ""powershell -ExecutionPolicy Bypass & 'C:\PATH\NAME.ps1'"", 0:close")

下面是windows 10中不包含任何第三方组件的工作解决方案。它的工作原理是将PowerShell脚本包装到VBScript中。

第一步:我们需要改变一些windows特性,允许VBScript运行PowerShell,并默认使用PowerShell打开。ps1文件。

-运行并输入“regedit”。单击ok,然后允许它运行。

-粘贴此路径"HKEY_CLASSES_ROOT\Microsoft.PowerShellScript. "1\Shell”并按enter键。

-现在打开右边的条目并将值更改为0。

-以管理员身份打开PowerShell,输入“Set-ExecutionPolicy -ExecutionPolicy remotessigned”,按enter并确认更改“y”,然后输入。

步骤2:现在我们可以开始包装脚本了。

-将Powershell脚本保存为.ps1文件。

-创建一个新的文本文档并粘贴这个脚本。

Dim objShell,objFSO,objFile

Set objShell=CreateObject("WScript.Shell")
Set objFSO=CreateObject("Scripting.FileSystemObject")

'enter the path for your PowerShell Script
 strPath="c:\your script path\script.ps1"

'verify file exists
 If objFSO.FileExists(strPath) Then
   'return short path name
   set objFile=objFSO.GetFile(strPath)
   strCMD="powershell -nologo -command " & Chr(34) & "&{" &_
    objFile.ShortPath & "}" & Chr(34)
   'Uncomment next line for debugging
   'WScript.Echo strCMD

  'use 0 to hide window
   objShell.Run strCMD,0

Else

  'Display error message
   WScript.Echo "Failed to find " & strPath
   WScript.Quit

End If

-现在更改文件路径到你的。ps1脚本的位置,并保存文本文档。

-现在右键单击文件并重命名。然后将文件名扩展名更改为.vbs,按enter键,然后单击确定。

完成了!如果你现在打开.vbs,当你的脚本在后台运行时,你应该看不到控制台窗口。


我真的厌倦了通过答案,却发现它没有像预期的那样工作。

解决方案

创建vbs脚本运行一个隐藏的批处理文件,该文件将启动powershell脚本。为这个任务制作3个文件似乎很愚蠢,但至少总大小小于2KB,它从任务器或手动运行完美(你看不到任何东西)。

scriptName.vbs

Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:\Users\leathan\Documents\scriptName.bat" & Chr(34), 0
Set WinScriptHost = Nothing

scriptName.bat

powershell.exe -ExecutionPolicy Bypass C:\Users\leathan\Documents\scriptName.ps1

scriptName.ps1

Your magical code here.

c="powershell.exe -ExecutionPolicy Bypass (New-Object -ComObject Wscript.Shell).popup('Hello World.',0,'ОК',64)"
s=Left(CreateObject("Scriptlet.TypeLib").Guid,38)
GetObject("new:{C08AFD90-F2A1-11D1-8455-00A0C91F3880}").putProperty s,Me
WScript.CreateObject("WScript.Shell").Run c,0,false

等待Powershell执行,在vbs中获取结果

这是使用Exec()时Omegastripes代码隐藏命令提示符窗口的改进版本

将cmd.exe中混乱的响应拆分到一个数组中,而不是将所有内容放入一个难以解析的字符串中。

此外,如果cmd.exe执行过程中发生了错误,则该错误发生的消息将在vbs中被知道。

Option Explicit
Sub RunCScriptHidden()
    strSignature = Left(CreateObject("Scriptlet.TypeLib").Guid, 38)
    GetObject("new:{C08AFD90-F2A1-11D1-8455-00A0C91F3880}").putProperty strSignature, Me
    objShell.Run ("""" & Replace(LCase(WScript.FullName), "wscript", "cscript") & """ //nologo """ & WScript.ScriptFullName & """ ""/signature:" & strSignature & """"), 0, True
End Sub
Sub WshShellExecCmd()
    For Each objWnd In CreateObject("Shell.Application").Windows
        If IsObject(objWnd.getProperty(WScript.Arguments.Named("signature"))) Then Exit For
    Next
    Set objParent = objWnd.getProperty(WScript.Arguments.Named("signature"))
    objWnd.Quit
    'objParent.strRes = CreateObject("WScript.Shell").Exec(objParent.strCmd).StdOut.ReadAll() 'simple solution
    Set exec = CreateObject("WScript.Shell").Exec(objParent.strCmd)
    While exec.Status = WshRunning
        WScript.Sleep 20
    Wend
    Dim err
    If exec.ExitCode = WshFailed Then
        err = exec.StdErr.ReadAll
    Else
        output = Split(exec.StdOut.ReadAll,Chr(10))
    End If
    If err="" Then
        objParent.strRes = output(UBound(output)-1) 'array of results, you can: output(0) Join(output) - Usually needed is the last
    Else
        objParent.wowError = err
    End If
WScript.Quit
End Sub
Const WshRunning = 0,WshFailed = 1:Dim i,name,objShell
Dim strCmd, strRes, objWnd, objParent, strSignature, wowError, output, exec

Set objShell = WScript.CreateObject("WScript.Shell"):wowError=False
strCmd = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass Write-Host Hello-World."
If WScript.Arguments.Named.Exists("signature") Then WshShellExecCmd
RunCScriptHidden
If wowError=False Then
    objShell.popup(strRes)
Else
    objShell.popup("Error=" & wowError)
End If

当您计划任务时,只需在“常规”选项卡下选择“无论用户是否登录都运行”。

另一种方法是让任务以另一个用户的身份运行。


powershell.exe -windowstyle hidden -noexit -ExecutionPolicy Bypass -File <path_to_file>

然后设置运行:最小化

应该像预期的那样工作,而没有添加隐藏窗口闪光的代码 只是稍微延迟了一点。


答案是-WindowStyle Hidden,但窗口仍然会闪烁。

我从未见过窗口闪烁时调用cmd /c start /min ""。

您的机器或设置可能不同,但对我来说很好。

1. 调用文件

cmd /c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -File "C:\Users\username\Desktop\test.ps1"

2. 用参数调用文件

cmd /c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command ". 'C:\Users\username\Desktop\test me.ps1' -Arg1 'Hello' -Arg2 'World'"ps1'; -Arg1 'Hello' -Arg2 ' World'"

Powershell内容为2。调用带有参数的文件是:

Param
(
  [Parameter(Mandatory = $true, HelpMessage = 'The 1st test string parameter.')]
  [String]$Arg1,
  [Parameter(Mandatory = $true, HelpMessage = 'The 2nd test string parameter.')]
  [String]$Arg2
  )

Write-Host $Arg1
Write-Host $Arg2

3.用函数和参数调用文件

cmd /c start /min "" powershell -WindowStyle Hidden -ExecutionPolicy Bypass -Command ". 'C:\Users\username\Desktop\test me.ps1'; Get-Test -stringTest 'Hello World'"

Powershell内容为3。调用带有函数和参数的文件是:

function Get-Test() {
  [cmdletbinding()]
  Param
  (
    [Parameter(Mandatory = $true, HelpMessage = 'The test string.')]
    [String]$stringTest
    )
  Write-Host $stringTest
  return
}

如果你需要在任务调度器中运行这个,那么调用%comspec%作为程序/脚本,然后调用上面文件的代码作为参数。

注意:当PS1文件的路径中有空格时,所有示例都有效。


创建一个调用PowerShell脚本的快捷方式,并将Run选项设置为最小化。这将防止窗口闪烁,尽管您仍然会在任务栏上运行脚本的瞬间闪烁。


为了方便命令行使用,有一个简单的包装器应用程序:

https://github.com/stax76/run-hidden

命令行示例:

run-hidden powershell -command calc.exe

在我尝试过的所有解决方案中,这是迄今为止最好和最容易设置的。从这里下载hiddenw.exe - https://github.com/SeidChr/RunHiddenConsole/releases

假设您希望运行Powershell v5无控制台。只需将hiddenw.exe重命名为powershell .exe。如果您想为cmd执行此操作,则重命名为cmdw.exe。如果要为Powershell v7 (pwsh)执行此操作,则重命名为pwshw.exe。您可以创建多个副本的hidden .exe,只是重命名为实际进程与字母w在末尾。然后,只需将该流程添加到系统环境PATH中,这样就可以从任何地方调用它。或者复制到C:\Windows。然后,像这样调用它:

powershellw ps1 \操作。


我发现编译成exe是实现这一目标最简单的方法。有许多方法来编译一个脚本,但你可以尝试ISE类固醇

打开“Windows PowerShell ISE”,安装并运行ISESteroids:

Install-Module -Name "ISESteroids" -Scope CurrentUser -Repository PSGallery -Force

Start-Steroids

然后转到工具->将代码转换为EXE,选择“隐藏控制台窗口”,然后创建应用程序。 您可以直接从任务调度程序运行,而不需要包装器或第三方应用程序。


换句话说,脚本应该在后台安静地运行,而不需要向用户发出任何信号。 不使用第三方组件的答案可获得额外分数:)

我找到了一种方法,通过将PowerShell脚本编译为Windows可执行文件来实现这一点。需要第三方模块来构建可执行文件,但不需要运行它。我的最终目标是编译一行PowerShell脚本,在我的系统上弹出DVD:

(New-Object -com "WMPlayer.OCX.7").cdromcollection.item(0).eject()

我的目标系统是Windows 7。具体的WMF更新需要根据Windows版本有所不同:

下载并安装WMF 5.1包

所需的PowerShell模块应该适用于任何Windows版本。以下是我用来安装必要模块和编译exe的确切命令。您需要调整驱动器,目录和文件名的详细信息为您的系统:

mkdir i:\tmp\wmf
cd i:\tmp\wmf
pkunzip ..\Win7AndW2K8R2-KB3191566-x64.zip
c:\windows\system32\windowspowershell\v1.0\powershell.exe
Set-ExecutionPolicy RemoteSigned
.\Install-WMF5.1.ps1
<click> "Restart Now"
c:\Windows\System32\WindowsPowerShell\v1.0\powershell -version 3.0
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12  
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force
Install-Module -Name ps2exe -RequiredVersion 1.0.5
ps2exe i:\utils\scripts\ejectDVD.ps1 -noConsole