Common/ServerRake.Common.Interactive.ps1

#######################################
### COMMON FUNCTIONS: INTERACTIVE ###
#######################################

function Send-PowershellCommand {

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string[]] $ComputerName
    )

    $remoteScript = Read-Host "Enter your Powershell command"
    $remoteScript = [ScriptBlock]::Create($remoteScript)

    return Send-RemoteScript -ComputerName $ComputerName -RemoteScript $remoteScript

}

function Enter-VMSession {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string] $ComputerName
    )

    if (!$secret) {

        throw "No secret sessions are currently opened. Start a session with 'New-SecretSession' and try again."
    
    }

    try {
    
        Enter-PSSession -ComputerName $ComputerName -Credential $secret
    
    } catch {

        Write-Host "Could not establish interactive session with [$ComputerName]" -ForegroundColor Red

    }     

}

function Copy-ItemToServer {
    
    param (
        [Parameter(Mandatory=$true)]
        [String[]] $ComputerName,

        [Parameter(Mandatory=$true)]
        [String] $Jumphost,

        [Parameter(Mandatory=$true)]
        [String] $Path
    )

    $remotePath    =   "C:\Temp\File_Transfer\"
    $session = New-PSSession -ComputerName $Jumphost -Credential $secret

    Invoke-Command -Session $session -ArgumentList $remotePath {
        param($remotepath)
        New-Item -Path $remotepath -ItemType Directory -Force | Out-Null
        Remove-Item -Path "$($remotepath)\*" -Recurse -Force
    }

    Copy-Item -Path $Path -Destination $remotePath -ToSession $session
    Write-Host "`nFile(s) copied to [$Jumphost]. Copying to servers..."

    Invoke-Command -Session $session -ArgumentList $ComputerName, $secret, $remotePath -ScriptBlock {

        param ($ComputerName, $secret, $remotePath)

        foreach ($server in $ComputerName) {

            $session = New-PSSession -ComputerName $server -Credential $secret

            Invoke-Command -Session $session -ArgumentList $remotePath {
                param($remotepath)
                New-Item -Path $remotepath -ItemType Directory -Force | Out-Null
                Remove-Item -Path "$($remotepath)\*" -Recurse -Force

            }

            Copy-Item -Path "$($remotepath)\*" -Destination $remotePath -ToSession $session -Recurse
            
            Invoke-Command -Session $session -ArgumentList $remotePath -ScriptBlock {
                param ($remotePath) 
                Get-ChildItem -Path $remotePath | Unblock-File 
            }
            
            Remove-PSSession -Session $session
            Write-Host "File(s) copied to [$server]."
        
        }

    }

    Remove-PSSession -Session $session

}