Powershell executable switch parameter not working

Support for all customers who have purchased a PrimalScript product license. This forum does not offer a response time guarantee.
Forum rules
DO NOT POST SUBSCRIPTION NUMBERS, LICENSE KEYS OR ANY OTHER LICENSING INFORMATION IN THIS FORUM.
Only the original author and our tech personnel can reply to a topic that is created in this forum. If you find a topic that relates to an issue you are having, please create a new topic and reference the other in your post.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
User avatar
peter_mclean@dodo.com.au
Posts: 85
Joined: Fri Jul 08, 2011 5:51 pm

Powershell executable switch parameter not working

Post by peter_mclean@dodo.com.au » Thu Nov 24, 2011 11:14 am

PS 2011 V6.0.155 Windows XP SP3
I has defined a script switch parameter, ie Param ([switch]$ClearEventLogs), at the very top of my powershell script. This is so that I can execute the script and nominate whether I delete the event logs or not. When I use the powershell command line, ie powershell .GetEventLogFailureAudits.ps1 -ClearEventLogs, the script works fine and the event logs are cleared, However when I compile/check the script and run the executable it does not work, as in GetEventLogFailureAudits.ps1 -ClearEventLogs. Debugging the script with write-host commands shows that the switch is always set to false, whether or not you pass the ClearEventsLogs switch parameter to the executable or not.
Since adding this post I have tried using the $args[0] method and that does work for both the powershell command line and the script executable ie use if ($args[0]) in the script to check if switch is $true or $false, and not if ($ClearEventLogs) to check if switch is $true or $false.pmclean@labelmakers.com.au2011-11-24 19:32:13

User avatar
Alexander Riedel
Posts: 6970
Joined: Tue May 29, 2007 4:43 pm

Powershell executable switch parameter not working

Post by Alexander Riedel » Fri Nov 25, 2011 7:28 am

When hosted as an executable your script is not executed as a script, which would require a temporary file. It is executed as a script block directly fed to the PowerShell engine. PowerShell works differently in that mode and does not resolve parameters that way.

PowerShell's command line handling is very inconsistent, so I am sorry that I have no ready solution.

The only thing I can make work consistently is using the args collection and processing parameters myself.
Alexander Riedel
SAPIEN Technologies, Inc.

User avatar
peter_mclean@dodo.com.au
Posts: 85
Joined: Fri Jul 08, 2011 5:51 pm

Powershell executable switch parameter not working

Post by peter_mclean@dodo.com.au » Fri Nov 25, 2011 1:10 pm

Thanks Alex. I understand and will live with this. It is not too inconvenient to use the args collection. In fact this is what I always use in Vbscript.