0

So I am fairly new at PowerShell and I am trying to do something that seems like it should be very simple but I have not been able to find any way to do it or anything on the internet. Honestly I think that might be more because I am unfamiliar with the terminology. Anyways here goes:

All I am trying to do is get Set-Service to use user input to target which service it would like to use. I thought this would be as simple as

Start-Service -Name $Services

But it always comes back as null.

and I am using

$Services = Read-Host "Service Name"

to define $Service, also I have attempted to use $Service as a string which seemed like it was causing the issue but it always came back as string empty.

I believe this is because I am not using the correct data type but I am unsure. If someone could help me with this simple problem I would greatly applicate it. It really annoying that something that seems like it should be very simple is causing me so much trouble.

Thanks,

Edit: Also I should add the full line I am attempting is

Invoke-Command -ComputerName $Server -Credential $UserCreds -ScriptBlock {Start-Service -Name $Services}

1 Answer 1

1

The problem is that your remote script can't access the local variable. That's why you should always test something in the most simple scenario possible to see if it works. Here the problem lies not in the Read-Host or the variable, like you are assuming.

To make local variables available to the remotely running script, you need to to this:

Invoke-Command -ComputerName $Server -Credential $UserCreds -ScriptBlock { param($Services) Start-Service -Name $Services } -ArgumentList $Services

Have a look here for more details: https://technet.microsoft.com/en-us/library/hh849719.aspx

Sign up to request clarification or add additional context in comments.

1 Comment

This worked like a charm, thank you very much. I was using a more "experienced" co-workers script and making some changes I was focusing on my additions but didn't think to check their additions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.