Remote Control Shortcut Script

    Imagine that you have a table with the names and addresses of devices and services and you can easily get many shortcuts from it to launch a browser, putty, remote desktop or telnet to manage these devices. In the picture below, this is schematically shown:

    Here's a beautiful picture of how dry lines of a spreadsheet become miraculous labels.
    Why is this even necessary? For example, a new system has come to your operation or examination, or some test environment has been transferred to you for use. In order not to drive addresses or copy from the file every time you connect to the hosts, you can run the script once and create all the shortcuts at once.

    The powershell script processes the CSV file, finds the columns “name”, “address”, “description”, “access”, creates shortcuts. The command for the shortcut is formed based on the value of “access” (http, https, rdp, telnet), the arguments are from the value of “address”. By the way, the “address” may not be an IP address, but a host name, for example. The "description" field falls into the comment of the label. You can also use shortname, address, method and desc as the field name. (I think it’s clear that there is something). The following parameters are accepted:
    • source <source_file> : path to the CSV file
    • folder <folder> : path to the folder in which you want to create shortcuts
    • noreplace : the parameter must be specified if the shortcuts were changed manually and you want to save these changes the next time you run the script
    • namePolicy shortname | shortname_addr | addr_shortname | shortname_lastoct | shortname_last2octs : a way to create a shortcut name. As you can see, this is one of the options: the value of the “name” column from the source file, the value “name” + “address”, “address” + “name” or “name” with the addition of one or two last octets of “address”.

    For example, like this:
    PS C:\temp>.\create-shortcuts.ps1 -source MyNewFriends.csv -folder d:\job\new –noreplace –namePolicy shortname_addr

    By default, data is taken from the source.csv file in the current directory, shortcuts are also created in the current directory.
    The paths to putty and Internet Explorer are set at the beginning of the script. Of course, for all connection methods you can use any other programs. The main thing to consider is the method of passing the parameter. For example, in mstsc, the host name for the connection is passed not just through a space, but as / v: <address> .
    Also, of course, you can add other connection methods. Here you already have to edit the createShct function , section #Shortcut command .
    Yes, if this is your first time running a powershell script, be sure to run:
    PS C:\temp>set-executionpolicy -executionpolicy unrestricted -scope currentuser

    And here is the script itself:
    ####################################################
    # Remote access shortcuts creation script
    # v0.9
    #
    # Defaults:
    #
    #    * Create shortcuts in current directory
    #    * Overwrite all shortcuts
    #    * Shortcut name is "shortname" column value
    #    * Shortcut comment is "desc" column value
    ####################################################
    # Создания ярлыков удалённого управления скрипт
    # версия 0.9
    #
    # По умолчанию:
    #
    #    * Ярлыки создаются в текущем каталоге
    #    * Все ярлыки перезаписываются
    #    * Имя ярлыка – столбец "имя"
    #    * Комментарий ярлыка - столбец "описание"
    ####################################################
    # Arguments
    param (
        [switch]$noreplace, # 'Do not overwrite shortcuts on creation' default is to overwrite
        $folder = '', # 'Target folder path' default is current dir
        $source = 'source.csv', # 'Source data file path' default
        $namePolicy = 'shortname' # 'Shortcut naming policy' default
    )
    $csvPath = $source # Source data file path
    $shPath = $folder # Target folder path
    $shNoReplace = $noreplace # Do not overwrite shortcuts on creation
    $shHTTPcmd = '"C:\Program Files\Internet Explorer\iexplore.exe"'
    $shRDPcmd = 'mstsc.exe'
    $shSSHcmd = '"C:\Program Files\PuTTY\putty.exe"'
    $shTELNETcmd = 'telnet.exe'
    $shNamePolicy = $namepolicy # Shortcut naming policy
    function createShctFile($shText,$shCmd,$shArgs, $desc = '')
    { # creating shortcut file
        $shPathSh = "$shPath\$shText.lnk"
        if ( (test-path -path $shPathSh) -and $shNoReplace ) {return}
        $shct = $oshell.CreateShortcut($shPathSh)
        $shct.TargetPath = $shCmd
        $shct.Arguments = $shArgs
        $shct.Description = $desc
        $shct.Save()
    }
    function createShct($shortname,$desc='',$addr,$method)
    { # preparing shortcurt parameters
        # Shortcut name
        $shText = $shortname
        if (!$shortname)
        {
            write-host '(i) No shortcut name defined'
            return
        }
        switch ($shNamePolicy) {
            'shortname' {
                $shText = $shortname
            }
            'shortname_addr' {
                $shText = "$shortname $addr"
            }
            'addr_shortname' {
                $shText = "$addr $shortname"
            }
            'shortname_lastoct' {
                $octs = ($addr -split '\.')
                if ($octs[3]) {$shText += ' ' + $octs[3]}
            }
            'shortname_last2octs' {
                $octs = ($addr -split '\.')
                if ($octs[3]) {$shText += ' ' + $octs[2]+ '.' + $octs[3]}
            }
        }
        #Shortcut command
        $shArgs = ''
        switch ($method) {
            'http' {
                $shCmd = $shHTTPCmd
                $shArgs = "http://$addr"            
            }
            'https' {
                $shCmd = $shHTTPCmd
                $shArgs = "https://$addr"            
            }
            'rdp' {
                $shCmd = $shRDPCmd
                $shArgs = "/v:$addr"
            }
            'ssh' {
                $shCmd = $shSSHcmd
                $shArgs = $addr
            }
            'telnet' {
                $shCmd = $shTELNETcmd
                $shArgs = $addr
            }        
        }
        createShctFile -shText $shText  -shCmd $shCmd -shArgs $shArgs -desc $desc
    }
    ##### Main
    # Init
    $oshell = New-Object -comObject WScript.Shell
    $basePath = (get-location).path # Working dir
    [System.IO.Directory]::SetCurrentDirectory($basePath) # Set working dir to script working dir
    # Env check
    if (!(test-path -pathtype leaf -path $csvPath))
    { # Cheking for source CSV path
        write-host "(!) Path to source CSV not found: $csvPath"
        exit
    }
    if (!($shPath)) {$shPath = $basePath }
    if (!(test-path -pathtype container -path $shPath))
    { # Cheking for target folder path
        write-host "(!) Path for shortcuts not found: $shPath"
        exit
    }
    # Run
    $csv = get-content $csvPath | Convertfrom-CSV -UseCulture
    foreach ($str in $csv)
    {
        $shrt = $str.shortname
        if ($str.имя) {$shrt = $str.имя}
        $addr = $str.addr
        if ($str.адрес) {$addr = $str.адрес}
        $accs = $str.method
        if ($str.доступ) {$accs = $str.доступ}
        $desc = $str.desc
        if ($str.описание) {$desc = $str.описание}
        createShct -shortname $shrt -desc $desc -addr $addr -method $accs
    }
    

    Also popular now: