Invoke-Command and spaces

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Russell Keith Russell Keith 3 years, 7 months ago.

  • Author
    Posts
  • #11268
    Profile photo of Russell Keith
    Russell Keith
    Participant

    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

  • #11270
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.

  • #11271
    Profile photo of Russell Keith
    Russell Keith
    Participant

    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.

You must be logged in to reply to this topic.