Quantcast
Channel: Windows PowerShell Forum
Viewing all articles
Browse latest Browse all 2562

Execute user input in ScriptBlock

$
0
0

So I am trying to get [1] this code to work. What I would like is to have is a script that, when run, asks for a command. I would enter the command I want run on the computers I specify, and the script would execute that command on computers in a remote session.

Right now, I either get an error (varies) or no error (but the code doesn't run). Here are the iterations of the specific line I have tried (with "$cmd" being the command to execute):

Invoke-Command -Session $session -ScriptBlock {$cmd}

Invoke-Command -Session $session -ScriptBlock {invoke-expression $cmd}   

Invoke-Command -Session $session -ScriptBlock {$args[0]} -ArgumentList $cmd

I have also tried creating a ScriptBlock before hand using different commands, but no combination has worked. So far for all my searching I have yet to find someone discuss passing user input into "Invoke-Command." Everyone seems to only pass pre-defined commands, which I have no problems running.

Here is the code I am using:

#Get Credentials
$name = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$cred = Get-Credential $name

#Get Computer(s)
$comp = read-host "Enter the computer name you would like to run commands on"

#Open Session with specified computer(s)
$session = New-PSSession -ComputerName $comp -Credential $cred

#Execute remote command
$cmd = read-host "Enter the command string to run"
Invoke-Command -Session $session -ScriptBlock {$cmd}

#Close Session
Remove-PSSession $session
In this instance I am trying to run the command "slmgr.vbs /ato" on the remote machine. I know that the command itself works when initiated manually. Do I need to escape the "/"? Also I have tried to use parameters and creating the ScriptBlock separately, but none of these things have worked. Thanks in advance.

Viewing all articles
Browse latest Browse all 2562

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>