Invoke-Command and spaces

Welcome Forums General PowerShell Q&A Invoke-Command and spaces

This topic contains 2 replies, has 2 voices, and was last updated by

5 years, 4 months ago.

  • Author
  • #11268

    Points: 0
    Rank: Member

    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

    Points: 0
    Rank: Member

    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

    Points: 0
    Rank: Member

    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.

The topic ‘Invoke-Command and spaces’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort