Home > Back-end >  Make a PowerShell script silent when called from a shortcut
Make a PowerShell script silent when called from a shortcut

Time:10-25

The following shortcut is created in SendTo and calls a PowerShell script. I want this script to be invisible (-WindowStyle Hidden) as the script uses Add-Type -AssemblyName System.Windows.Forms; $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{ InitialDirectory = $parent } and processes results based on the item selected in the OpenFileDialog.

$oShell = New-Object -ComObject Shell.Application
$lnk = $WScriptShell.CreateShortcut("$Env:AppData\Microsoft\Windows\SendTo\Get Info.lnk")
$lnk.TargetPath = "%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe"
$lnk.Arguments = "-WindowStyle Hidden -NoProfile -File `"C:\Scripts\Get Info.ps1`""
$lnk.Save()

However, the script is not silent, and throws up a blue PowerShell window briefly before the OpenFileDialog. How can I make the script completely silent when called by the shortcut?

CodePudding user response:

Only way I know about to ensure this is using to launch your .ps1 script. It goes as follows:

  • Launcher.vbs

0 as argument in objShell.Run command,0 stands for Hide the window (and activate another window.)

Set objShell = CreateObject("WScript.Shell")
path = WScript.Arguments(0)

command = "powershell -NoProfile -WindowStyle Hidden -ExecutionPolicy ByPass -File """ & path & """"

objShell.Run command,0
  • myScript.ps1
Add-Type -AssemblyName System.Windows.Forms

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    InitialDirectory = $parent
}

$FileBrowser.ShowDialog()

Now in your shortcut's Target field you can use use:

wscript path\to\launcher.vbs path\to\myScript.ps1

You can read more about this method in this site.

  • Related