0

I have a nice little powershell script that works

$URL = $args[0]
$proxy = New-WebServiceProxy -Uri $URL -Namespace webservice -UseDefaultCredential
$result = $proxy.TestWebMethod()

usage from cmd: 
powershell.exe myscript.ps1 "http://somesite.com/someservice.asmx"

What I want to do is also be able to pass in the method name dynamically, something to the effect of:

$URL = $args[0]
$proxy = New-WebServiceProxy -Uri $URL -Namespace webservice -UseDefaultCredential
$result = $proxy.$args[1]

usage from cmd: 
powershell.exe myscript.ps1 "http://somesite.com/someservice.asmx" "TestWebMethod"

Is there some way to make it work dynamically the second way?

2 Answers 2

1

It is a little odd looking but in PowerShell V3 you can do this:

$proxy | Foreach $args[1]

You can also do it like this if the method takes no arguments:

$proxy."$args[1]"

And if you have arguments to the method:

$proxy."$args[1]".Invoke(<args here>)

Here's an example on V2 that uses a web service and takes an arg:

$URI = "http://www.webservicex.net/uszip.asmx?WSDL"
$zip = New-WebServiceProxy -uri $URI -namespace WebServiceProxy -class ZipClass
$method = "GetInfoByZIP"
$zip."$method".Invoke('80525')
Sign up to request clarification or add additional context in comments.

5 Comments

I like the idea, but I can't get it to work. For testing I stored the method in a variable: $Method = "TestWebMethod" and then I tried $proxy.$Method" and nothing happened it just returned to the next line. $proxy | Foreach $Method returned an error.
The first approach only works on PowerShell v3. You must on v1 or v2. With the quoted version on V2 do it this way $proxy."$method".Invoke().
Got Error: you cannot call a method on a null valued expression.
I would rather do it this way, just because it's simpler, but as of right now I can only get it to work using iex
Nevermind, you must be on at least V2 to use New-WebServiceProxy. Weird, I tested on V2 and that approach worked for me.
1

I don't have a service to test with, but have you tried invoke-expression (iex)?

$result = iex "`$proxy.$($args[1])()"

4 Comments

$Method = "TestWebMethod" and then iex "$proxy.$($Method)()" return an error An expression was expected after '('.`
I was able to use iex but had to do it on two lines using a single quote. >$serviceCall = '$proxy.' + $($args[1]) + '()' >$result = iex $serviceCall
One line version: $result = iex $('$proxy.' + $($args[1]) + '()')
My solution worked for me for calling the toUpper() function on a string. You may need to escape the $proxy variable. See updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.