locked
New to Powershell. Script not working on remote server. RRS feed

  • Question

  • Hey guys.

    Not quite sure if this is the correct spot to post but I will give it a try.

    Over the past 3-4 weeks I have been trying to learn powershell. I have made a script (with the help of youtube, SS64 + other resources) and modified it a bit to work on remote servers in my domain environment. I have enabled WinRM and I am able to connect to other Clients/Servers in my network. I have also "Get-ExecutionPolicy" on unrestricted on all clients/servers I am trying to launch my script into.

    Problem:

    So basically I made a script which lets me view processes and services on my local or remote client/server. It basically lets me view and kill a process, and view, start or stop a service. 

    I have laid the block of code in a function and I am using an if/else statement to access either the local machine or a remote machine (using enter-pssession with the hostname). 

    When I enter the remote part of my if/else statement and run my function it looks like it is working normally. I get prompted to login with my username etc, but after I choose "List all processes" or another part of my script it basically lists the results from my local host, and not my remote host. Once I exit the script I check if I am indeed connected to the remote-host and it seems that I am, and when I type "Get-Process" it gives my the correct information for that remote-server.

    I have no idea what I am doing wrong here so I'll post the code (it's rather messy since it is my first "real" script I've made).

    Script: http://textuploader.com/dscz4

    clear
    $PROCESS_ID = 0
    $CONFIRM_TERMINATE = "No" 
    $RUN_AGAIN = "Yes" 
    $SERVICES = "" 
    $SERVICE_TO_STOP = "" 
    $SERVICE_TO_START = ""
    $SERVICE_FOUND = "No"
    $UserReplyRunningService = ""
    $RemoteComputer = ""
    $AdminLogin = "Administrator"
    $LocalorRemote
    
    function scriptmain {
    While($RUN_AGAIN -eq "Yes" -or $RUN_AGAIN -eq "Y"){
        Write-Host ""
        Write-Host "-----------Select a Menu Item-----------"
        Write-Host "List all processes                   [1]"
        Write-Host "Stop a process                       [2]"
        Write-Host "List all services                    [3]"
        Write-Host "Stop a running service               [4]"
        Write-Host "Start a running service              [5]"
        Write-Host "Script Author                        [6]"
        Write-Host "Quit the program?                    [7]"
        Write-Host ""
        $MY_SELECTION = Read-Host "Enter your selection: "
        Write-Host ""
        Switch ($MY_SELECTION)
            {
                1 {Get-Process}
                2 {
                    $PROCESS_ID = Read-host "What process ID do you want to stop?"
                    $PROCESSES = Get-Process
                    foreach($Process in $Processes){
                        if($Process.ID -eq $PROCESS_ID){
                        $CONFIRM_TERMINATE = Write-Host $Process.ProcessName "Will be terminated (Yes/No)"
                            $CONFIRM_TERMINATE = Read-Host "Terminate Process (Yes/No)"
                            if($CONFIRM_TERMINATE -eq "Yes" -or $CONFIRM_TERMINATE -eq "Y"){
                                Write-Host "Terminate confirmed by the user. Ending process." $Process.ProcessName
                                Stop-Process -Id $PROCESS_ID -Force
                            }else{
                                Write-Host "Terminate not confirmed no action taken."
                            }
                        }
                    }
                }
                3 {Get-Service}
                4 {
                    $SERVICE_FOUND = "No"
                    $SERVICE_TO_STOP = Read-Host "What is the Name of the service you would like to stop? (Note: Not the DisplayName)"
                    $SERVICES = @(Get-Service)
                        foreach($SERVICE in $SERVICES){
                            if($SERVICE.Name -eq $SERVICE_TO_STOP){
                                if($SERVICE.Status -eq "Running"){
                                    $SERVICE_FOUND = "Yes"
                                    Write-Host $SERVICE.Name "Service found."
                                    Write-Host "Stopping service now."
                                    Stop-Service $SERVICE_TO_STOP -Force
                                    Get-Service | ? {$_.Name -eq $SERVICE_TO_STOP}
                                }elseif($SERVICE.Status -eq "Stopped"){
                                    $SERVICE_FOUND = "Yes"
                                    Write-Host "The service is already stopped."
                                }
                        }
                    }
                    if($SERVICE_FOUND -eq "No"){
                        Write-Host "We did not find the service you entered, please try again."
                        }
                }
                5 {
                
                Write-Host "You want to start a running service?"
                $UserReplyRunningService = Read-Host "Yes/No?"
                    if($UserReplyRunningService -eq "Yes" -or $UserReplyRunningService -eq "Y"){
                            $SERVICE_FOUND = "No"      
                            $SERVICE_TO_START = Read-Host "What is the Name of the service you would like to start? (Note: Not the DisplayName)"
                            $SERVICES = @(Get-Service)
                                foreach($SERVICE in $SERVICES){
                                    if($SERVICE.Name -eq $SERVICE_TO_START){
                                        if($SERVICE.Status -eq "Stopped"){
                                            $SERVICE_FOUND = "Yes"
                                            Write-Host $SERVICE.Name "Service found."
                                            Write-Host "Starting service now."
                                            Start-Service $SERVICE_TO_START
                                            Get-Service | ? {$_.Name -eq $SERVICE_TO_START}
                                        }elseif($SERVICE.Status -eq "Running"){
                                            $SERVICE_FOUND = "Yes"
                                            Write-Host "The service is already running."
                                        }
                                    }
                                }
                                if($SERVICE_FOUND -eq "No"){
                                    Write-Host "We did not find the service you entered, please try again."
                                    } 
                        }
                        elseif($UserReplyRunningService -eq "No"){
                            $RUN_AGAIN = Read-Host "Type 'Yes' or 'No' to run the program again"
                            }                                                
                }
                6 {
            Write-Host "     
            Script made by 'Blablabla' @ 31.08.2016
    
               ________________
             |'-.--._ _________:
             |  /    |  __    __\
             | |  _  | [\_\= [\_\
             | |.' '. \.........|
             | ( <)  ||:       :|_
              \ '._.' | :.....: |_(o
               '-\_   \ .------./
               _   \   ||.---.||  _
              / \  '-._|/\n~~\n' | \
             (| []=.--[===[()]===[) |
             <\_/  \_______/ _.' /_/
             ///            (_/_/
             |\\            [\\
             ||:|           | I|
             |::|           | I|
             ||:|           | I|
             ||:|           : \:
             |\:|            \I|
             :/\:            ([])
             ([])             [|
              ||              |\_
             _/_\_            [ -'-.__
            <]   \>            \_____.>
              \__/
            
            "
                }
                7 {exit}  
                default{"Error you did not select a valid option"}
            }
        Write-Host ""
        Write-Host ""
        $RUN_AGAIN = Read-Host "Type 'Yes' or 'No' to run the program again"
        }
    }
    
    Write-host "Local or Remote PC?"
    Write-host ""
    $LocalorRemote = read-host "Type Local/Remote"
    	if($LocalorRemote -eq "Local" -or $LocalorRemote -eq "L"){
    	scriptmain
    	}elseif($LocalorRemote -eq "Remote" -or $LocalorRemote -eq "R"){
    	Write-Host "Type in the host-name of the computer you would like to remote into:"
    	$RemoteComputer = read-host "Type the Host-Name"
    	Enter-PSSession -Computername $RemoteComputer -credential $AdminLogin
    	scriptmain
    	}else{
    	Write-host "Invalid"
    }


    - MPC

    Edit: Sorry for the late reply.

    Yes, I got the help I needed. Thanks for making it as correct.


    • Edited by MPCPRO Wednesday, October 19, 2016 11:37 AM
    Wednesday, September 21, 2016 10:56 AM

Answers

  • Hi MPC,

    basically, Enter-PSSession is only for interactive use, not as part of a script. The rest of the script will continue to run on your local computer.

    To run a scriptblock on a target system, you can create a session with "New-PSSession", then use Invoke-Command with the -Session parameter. You can't ask user input in thus invoked scriptblocks, so you need to return results, ask for input locally and finally execute the user's decision on the target system.

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Proposed as answer by Hello_2018 Thursday, September 22, 2016 2:02 AM
    • Marked as answer by Hello_2018 Thursday, September 29, 2016 8:01 AM
    Wednesday, September 21, 2016 12:24 PM

All replies

  • Hi MPC,

    basically, Enter-PSSession is only for interactive use, not as part of a script. The rest of the script will continue to run on your local computer.

    To run a scriptblock on a target system, you can create a session with "New-PSSession", then use Invoke-Command with the -Session parameter. You can't ask user input in thus invoked scriptblocks, so you need to return results, ask for input locally and finally execute the user's decision on the target system.

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Proposed as answer by Hello_2018 Thursday, September 22, 2016 2:02 AM
    • Marked as answer by Hello_2018 Thursday, September 29, 2016 8:01 AM
    Wednesday, September 21, 2016 12:24 PM
  • Hi,

    >> get prompted to login with my username etc, but after I choose "List all processes" or another part of my script it basically lists the results from my local host, and not my remote host.

    This line: 1 {Get-Process} I'd prefer to use :

     foreach($remote_computer in $RemoteComputer )
     {
        Invoke-Command -ScriptBlock{Get-Process} -ComputerName $remote_computer
     }

    $RemoteComputer = get-content computernames.txt

    Besides, I suppose you could try to use visual studio develop environment to develop a viewable tool.

    Best regards,

    Andy_Pan


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.


    • Edited by Hello_2018 Thursday, September 22, 2016 2:05 AM
    Thursday, September 22, 2016 2:02 AM
  • Hi,

    As this thread has been quiet for a while, we will mark it as ‘Answered’ as the information provided should be helpful. If you need further help, please feel free to reply this post directly so we will be notified to follow it up. You can also choose to unmark the answer as you wish.
     
    BTW, we’d love to hear your feedback about the solution. By sharing your experience you can help other community members facing similar problems. Thanks for your understanding and efforts.

    Best regards,

    Andy


    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    Thursday, September 29, 2016 8:01 AM