Reputation: 131
Background: I wrote a little script for our 1st level tech support that does some validation (naming convention/ip address range) and updates dns records for the printer ranges.
It takes input from the command line Or a file, and if no input is given on the command line it prompts from within the script.
The original issue was that the script just executed and closed when a user right clicked the update-PrinterDNS.ps1 and "run with PowerShell". Adding a pause statement at the end of the script allows the user to see the output. However this throws a wrench into the automation side when the script is called and passed parameters.
I've considered adding a -noPause switch to the command line, or pushing out a shortcut that calls PowerShell with -noExit, but those seem more like workarounds instead of solutions.
the Question:) I'd like to know if it can be determined within the script if it was started by the 'run with windows PowerShell' in order to conditionally pause at the end.
Upvotes: 4
Views: 1480
Reputation: 33
Using $MyInvocation should be fine in the main body of the script. It will not work however when used to test from a function.
Example:
function ConditionalPause()
{
if ($MyInvocation.Line -ne "")
{
pause #will ALWAYS pause
}
# $MyInvocation.Line will be always the name of the function, i.e.: "ConditionalPause"
# $MyInvocation.Line -ne "" will always return true
}
Upvotes: 0
Reputation: 1690
The invocation line is populated with the command used to launch the script. I would expect it to always have a value if invoked from a PowerShell prompt, but it is empty when doing a Run with PowerShell.
echo "hello world"
if ($MyInvocation.Line -eq "")
{
pause
}
Upvotes: 3
Reputation: 354356
Run with PowerShell has the following command line (by default, subject to change in future versions, etc.):
powershell.exe "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
You can see how you were called in the $MyInvocation
variable.
Another way is to check the execution policy, which is explicitly set here. Unless you started PowerShell with -ExecutionPolicy Bypass
the following will only be true for the case when your script was run via the context menu:
(Get-ExecutionPolicy -Scope Process) -eq 'Bypass'
As far as hacky workarounds go, I'd say this should work for a while. No guarantees, though.
Upvotes: 5