Mock Command that returns a multi-line string from an external command

108 views
Skip to first unread message

Matthew Hatch

unread,
Jan 26, 2015, 4:01:50 PM1/26/15
to pes...@googlegroups.com
I have a function that uses Invoke-Command to return the results of a non-powershell command..  The function then takes the string that is returned, grabs certain items from the results and adds them as properties to a PSObject

I call Invoke-Command like this:
Invoke-Command -ComputerName 'Server01' -ScriptBlock {$results = & listcaches /a;Write-Output $results}


And Mock it like this:
Mock -CommandName Invoke-Command -ModuleName NCache {
        $results = @"
Listing registered caches on SOMESERVER:8250
Cache-ID:       mypartitionedcache
Scheme:         partitioned-server
Status:         Stopped
Cache-ID:       somecache
Scheme:         replicated-server
Status:         Running
Cluster size:   2
                1.2.12.60:7802
                1.4.45.36:7802
UpTime:         11/24/2014 6:27:16 AM
Capacity:       250 MB
Count:          0
Cache-ID:       SomeOtherCache_DEV
Scheme:         replicated-server
Status:         Running
Cluster size:   2
                1.2.12.60:7804
                1.4.45.36:7804
UpTime:         11/24/2014 6:27:26 AM
Capacity:       1000 MB
Count:          16
Cache-ID:       SomeOtherCache_dev2
Scheme:         replicated-server
Status:         Running
Cluster size:   2
                1.2.12.60:7803
                1.4.45.36:7803
UpTime:         11/24/2014 6:27:32 AM
Capacity:       1000 MB
Count:          0
Cache-ID:       myreplicatedcache
Scheme:         replicated-server
Status:         Stopped
Cache-ID:       mycache
Scheme:         local-cache
Status:         Stopped
"@ 
    Write-Output $results   
    }

But when I try to invoke the replace method on the string I get -- Method invocation failed because [System.Char] does not contain a method named 'Replace'.
So it looks like its being treated as a Char. 

Has anyone tried to use a mock to return a string from an external (non-powershell) command?

Dave Wyatt

unread,
Jan 26, 2015, 4:34:35 PM1/26/15
to pes...@googlegroups.com
The problem is that you're returning a single string in your mock, whereas the normal command returns an array of strings (one per line).  You can just split your mock string on newlines to get the same effect:

Write-Output ($results -split '\r?\n')

Matthew Hatch

unread,
Jan 26, 2015, 5:38:17 PM1/26/15
to pes...@googlegroups.com
That's it... Thanks!
Reply all
Reply to author
Forward
0 new messages