GreatSamps
GreatSamps

Reputation: 609

Build Powershell String Parameter From Pipeline

I need to dynamically build a string parameter using output from a pipe which is then passed to another command.

The source command is Get-VM which has an element called Name

The destination command is Move-VM, which accepts a parameter of -DestinationStoragePath

I need to dynamically manipulate this path based on the source Name to be D:\{0} where {0} is the VM Name.

I have this so far:

Get-VM | Move-VM -DestinationStoragePath [string]::Format("D:\{0}",$_.Name)

But it is throwing an exception, if i statically set the DestinationStoragePath parameter, then it works fine, so its just this little bit that is tripping it up.

Any ideas?

Upvotes: 2

Views: 1213

Answers (1)

Micky Balladelli
Micky Balladelli

Reputation: 9991

Get-VM | Move-VM -DestinationStoragePath [string]::Format("D:{0}",$_.Name)

is trying to pass the string [string]::Format("D:{0}",$_.Name) literally to the parameter -DestinationStoragePath.

What you need is execute the expression and return the result by surrounding your expression in parenthesis like this:

Get-VM | % { Move-VM -DestinationStoragePath ([string]::Format("D:{0}",$_.Name)) }

Upvotes: 7

Related Questions