如何运行PowerShell脚本而不向用户显示窗口或任何其他符号?
换句话说,脚本应该在后台安静地运行,而不需要向用户发出任何信号。
不使用第三方组件的答案可获得额外分数:)
如何运行PowerShell脚本而不向用户显示窗口或任何其他符号?
换句话说,脚本应该在后台安静地运行,而不需要向用户发出任何信号。
不使用第三方组件的答案可获得额外分数:)
当前回答
你可以像这样运行它(但这会显示一个窗口):
PowerShell.exe -WindowStyle hidden { your script.. }
或者您可以使用我创建的一个帮助文件来避免名为PsRun.exe的窗口,它正是这样做的。您可以在PowerShell中使用WinForm GUI运行计划任务中下载源文件和exe文件。我用它来完成计划好的任务。
已编辑:正如Marco所指出的,此-WindowStyle参数仅适用于V2及以上版本。
其他回答
powershell.exe -windowstyle hidden -noexit -ExecutionPolicy Bypass -File <path_to_file>
然后设置运行:最小化
应该像预期的那样工作,而没有添加隐藏窗口闪光的代码 只是稍微延迟了一点。
我创建了一个小工具,通过原始文件将调用传递给任何你想要启动无窗口的控制台工具:
https://github.com/Vittel/RunHiddenConsole
编译完成后,只需将可执行文件重命名为“<targetExecutableName>w.exe”(附加一个“w”),并将其放在原始可执行文件旁边。 然后你可以用通常的参数调用e.G. powershell .exe,它不会弹出一个窗口。
如果有人知道如何检查创建的进程是否等待输入,我会很高兴包括你的解决方案:)
创建一个调用PowerShell脚本的快捷方式,并将Run选项设置为最小化。这将防止窗口闪烁,尽管您仍然会在任务栏上运行脚本的瞬间闪烁。
下面是一行代码:
mshta vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""powershell -NoLogo -Command """"& 'C:\Example Path That Has Spaces\My Script.ps1'"""""", 0 : window.close")
虽然这可能会让窗口非常短暂地闪现,但这种情况应该很少发生。
答案是-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文件的路径中有空格时,所有示例都有效。