Author Posts

November 7, 2013 at 9:17 am

I am working on a Project in PowerShell Studio and can't figure out how to address spaces in a Service name property.

I am reading the running services into a data grid and allowing the user to pick a row.

If $serviceName = "ServiceName" (no spaces) the Invoke-Command works just fine.

If $serviceName = "Service Name" (has spaces) the PowerShell tells me "Cannot bind argument to parameter 'Name' because it is null." How can I address these services that have spaces in the name?

$serviceName = $datagridviewResults.CurrentRow.Cells['Name'].Value.ToString()
Invoke-Command -ComputerName $computerName -ScriptBlock {Restart-Service -Name $serviceName} -Credential $cred

November 7, 2013 at 9:42 am

Honestly, I'm not sure how that's working even with no spaces. The $serviceName variable doesn't exist in the remote session where that script block gets executed. Here's how it should be done:

Invoke-Command -ComputerName $computerName -ScriptBlock { Restart-Service -Name $args[0] } -Credential $cred -ArgumentList $serviceName

You can define a param block instead of using $args[0], if you like, but the basic idea is the same. Write the script block to accept positional arguments, and pass them via Invoke-Command's -ArgumentList parameter.

November 7, 2013 at 9:49 am

Thanks Dave. The built in examples only show the argument list being used to pass data to a ps1 script not a script block. I will file this away for future use.