Created
July 9, 2025 06:23
-
-
Save FSharpCSharp/17891b47a373967ef1c1ad40088aafb6 to your computer and use it in GitHub Desktop.
This script demonstrates how to execute an external program with arguments in PowerShell. It allows you to choose between inline execution and using Start-Process, and displays the exact command before running it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .SYNOPSIS | |
| Example script to execute a program with arguments in PowerShell, supporting both inline call and Start-Process. | |
| .DESCRIPTION | |
| This script demonstrates how to build an argument array for a program call and execute it either inline or via Start-Process. | |
| The execution method can be controlled using the -UseInline script parameter. | |
| The script also displays the exact command as it will be executed. | |
| .PARAMETER UseInline | |
| If $true, the program is executed inline (&). If $false, Start-Process is used. | |
| .EXAMPLE | |
| .\Example.ps1 -UseInline $true | |
| .NOTES | |
| For more information, see: | |
| PowerShell about_Parameters: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_parameters | |
| Start-Process documentation: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/start-process | |
| #> | |
| param( | |
| [Parameter(Mandatory = $true)] | |
| [bool]$UseInline | |
| ) | |
| # Build the argument array | |
| $args = @() | |
| $args += "FunctionName" | |
| $args += "--Timeout" | |
| $args += "10:00:00" | |
| $args += "--Function" | |
| $args += "Test" | |
| $args += "--TestInt" | |
| $args += "10000" | |
| $args += "--TestFloat" | |
| $args += "1.23" | |
| # Helper function to format arguments for display (quotes arguments with spaces or quotes) | |
| function Format-ArgsForDisplay($args) { | |
| $args | ForEach-Object { | |
| if ($_ -match '\s|["]') { '"{0}"' -f $_ } else { $_ } | |
| } -join ' ' | |
| } | |
| # Show the actual command as it will be executed | |
| $displayCall = ".\Test.exe " + (Format-ArgsForDisplay $args) | |
| Write-Host "The program will be executed as:" | |
| Write-Host $displayCall | |
| # Execute the program | |
| if ($UseInline) { | |
| & .\Test.exe @args | |
| } | |
| else { | |
| Start-Process -FilePath ".\Test.exe" -ArgumentList $args -Wait | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment