Reputation: 9459
I have a command line executable that I need to call repeatedly in PowerShell with different options.
On every occassion I wish to check that the exit code is 0.
Is there a way for wrapping the call and the parameters as a function?
& bob.bat -b
... error handling
& bob.bat -a -m "a path"
... error handling
Goes to something like:
function callBob ($paramList)
{
& bob.bat $paramList
... error handling
}
callBob -b
callBob -a -m "a path"
etc...
Unfortunately the above code doesn't appear to handle multiple parameters - I can't get things like the second to work, as callBob only takes a single parameter so I end up having to pass in a single string which seems to get quoted on being passed to & bob.bat.
Upvotes: 1
Views: 1112
Reputation: 314
There are few ways to do it.
1)Create a batch file and call the powershell script from it.
2)Create an exe and then invoke the powershell from it. You can get the exit code in the WPF application and then verify it.
It depends on the complexity and need of your application. I have used a WPF application to wrap the powershell, because we did not want others to run the script by going to powershell and executing. And also we provided a security login in WPF application.
Let me know if you need help if you decided to use WPF Applicaiton.
Upvotes: 0
Reputation: 301037
You can do something like this:
function callBob{
bob.bat $args
}
callBob -b
Also, try this wrapper if you want ( from PSAKE):
function Exec
{
[CmdletBinding()]
param(
[Parameter(Position=0,Mandatory=1)][scriptblock]$cmd,
[Parameter(Position=1,Mandatory=0)][string]$errorMessage = ($msgs.error_bad_command -f $cmd)
)
& $cmd
if ($lastexitcode -ne 0) {
throw ("Exec: " + $errorMessage)
}
}
Upvotes: 1
Reputation: 43459
You can user $args to access parameters:
function callBob
{
Write-Host "Length: $($args.Length)"
Write-Host "arg0: $($args[0])"
Write-Host "arg1: $($args[1])"
Write-Host "arg2: $($args[2])"
}
callBob -b
callBob -a -m "a path"
Upvotes: 1