OpsaC - Operating as PowerShell code
published: January 29, 2019 author: Tinu tags: PowerShell categories: PowerShell-Remoting
WSMan-Protocol must have a listener configured, an inbound firewall rule for TCP port 5985/86 must be enabled, and the WinRM service must be started.
winrm quickconfig
Enabled on Windows Server 2012 Operating Systems or later. Disabled by default on all Client and earlier Server OS’s.
Enable-PSRemoting -Force
Computers in a workgroup, or different domain, should be added to allow authentication.
Get-Item WSMan:\localhost\Client\TrustedHosts
Set-Item WSMan:\localhost\Client\TrustedHosts -value [IP, Computer, Domain, *]
Clear-Item WSMan:\localhost\Client\TrustedHosts -Force
The Enter-PSSession cmdlet starts an interactive session with a single remote computer.
$RemoteHost = Read-Host 'Enter the computer to connect'
$userprincipalname = "$(($env:USERNAME).ToLower())@domain.com"
$creds = (Get-Credential -Message 'Enter the credentials' -UserName $userprincipalname)
Enter-PSSession -ComputerName $RemoteHost -Credential $creds
During the session, the commands that you type run on the remote computer, just as though you were typing directly on the remote computer. You can have only one interactive session at a time.
Typically, you use the ComputerName parameter to specify the name of the remote computer. However, you can also use a session that you create by using the New-PSSession cmdlet for the interactive session. However, you cannot use the Disconnect-PSSession, Connect-PSSession, or Receive-PSSession cmdlets to disconnect from or re-connect to an interactive session.
Indicates that this cmdlet adds an interactive security token to loopback sessions. The interactive token lets you run commands in the loopback session that get data from other computers. For example, you can run a command in the session that copies XML files from a remote computer to the local computer.
Indicates that the PSSession runs as administrator.
To end the interactive session and disconnect from the remote computer, use the Exit-PSSession cmdlet, or type „exit“.
The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. By using a single Invoke-Command command, you can run commands on multiple computers.
To run a single command on a remote computer, use the ComputerName parameter. To run a series of related commands that share data, use the New-PSSession cmdlet to create a PSSession (a persistent connection) on the remote computer, and then use the Session parameter of Invoke-Command to run the command in the PSSession. To run a command in a disconnected session, use the InDisconnectedSession parameter. To run a command in a background job, use the AsJob parameter.
To establish a persistent connection to a remote computer, use the New-PSSession cmdlet.
$RemoteHost = Read-Host 'Enter the computer to connect'
$userprincipalname = "$(($env:USERNAME).ToLower())@domain.com"
$creds = (Get-Credential -Message 'Enter the credentials' -UserName $userprincipalname)
$rsession = New-PSSession -ComputerName $RemoteHost -Credential $creds
if($rsession.State -eq 'Opened'){
# Remove items on the remote computer
Invoke-Command -Session $rsession -ScriptBlock {
if(Test-Path 'C:\Admin\Scripts'){remove-item 'C:\Admin\Scripts' -Recurse -Force}
}
# Copy some scripts to the remote computer
Copy-Item -ToSession $rsession -Path "$($PSScriptRoot)\scripts\" -Destination 'C:\Admin' -Force -Recurse
Write-Host "Copy $($PSScriptRoot)\scripts to $($rsession.ComputerName) C:\Admin"
}
Specifies a local script that this cmdlet runs on one or more remote computers.
The script must reside on the local computer or in a directory that the local computer can access.
Invoke-Command -ComputerName BigServer -FilePath 'C:\Services.ps1'
Invoke-Command -ComputerName BigServer -ScriptBlock {Get-Culture}
<#
.SYNOPSIS
Start PSSession
.DESCRIPTION
Start a single PSSession to the given Host
.NOTES
Author: Martin Walther
Date created: 24.04.2018
#>
<# Logoff
cd /; Remove-Item C:\Admin\Scripts -Recurse -Force; Exit-PSSession
Remove-PSSession -Session $rsession; $rsession
#>
#region code
[CmdletBinding()]
param (
[Parameter (Mandatory = $false)]
[string] $Location = "$($env:USERPROFILE)\RemoteHosts"
)
# -- Control
Write-Host "`n$($MyInvocation.MyCommand.Name)`n" -ForegroundColor Green
Write-Host "`nYou are connectet to the local computer => $($env:Computername)" -ForegroundColor Yellow
$RemoteHost = Read-Host 'Enter the computer to connect'
if(!([String]::IsNullOrEmpty($RemoteHost))){
#Add Computers to TrustedHosts
Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*' -Force
Write-Host "You are connectet to the local computer => $($env:Computername)" -ForegroundColor Yellow
try{
$userprincipalname = "$(($env:USERNAME).ToLower())@domain.com"
if([String]::IsNullOrEmpty($creds)){
$creds = (Get-Credential -Message 'Enter the credentials' -UserName $userprincipalname)
}
# Start a persistent connection to a remote computer
$rsession = New-PSSession -ComputerName $RemoteHost -Credential $creds
if($rsession.State -eq 'Opened'){
# Copy some scripts to the remote computer
Invoke-Command -Session $rsession -ScriptBlock {
if(Test-Path 'C:\Admin\Scripts'){remove-item 'C:\Admin\Scripts' -Recurse -Force}
}
Copy-Item -ToSession $rsession -Path "$($PSScriptRoot)\scripts\" -Destination 'C:\Admin' -Force -Recurse
Write-Host "Copy $($PSScriptRoot)\scripts to $($rsession.ComputerName) C:\Admin"
# Start the interactive session to the remote computer
Write-Host "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss'): Start an interactive PSRemoteSession to $RemoteHost"
Enter-PSSession -Session $rsession; $creds = $null
Write-Host "`nYOU ARE CONNECTED TO THE REMOTE HOST => $($RemoteHost)" -ForegroundColor Red
Write-Host "`nTo leave enter the following code:" -ForegroundColor Red
Write-Host 'cd /; Remove-Item C:\Admin\Scripts -Recurse -Force; Exit-PSSession' -ForegroundColor Red
Write-Host 'Remove-PSSession -Session $rsession; $rsession' -ForegroundColor Red
Write-Host "`nYOU ARE CONNECTED TO THE REMOTE HOST => $($RemoteHost)" -ForegroundColor Red
}
}
catch{
Write-Host "`nThe following error has occurred:" -ForegroundColor Red
[PSCustomObject]@{
Activity = $($_.CategoryInfo).Activity
Message = $($_.Exception.Message)
Category = $($_.CategoryInfo).Category
Exception = $($_.Exception.GetType().FullName)
TargetName = $($_.CategoryInfo).TargetName
}
$error.clear()
$creds = $null
}
#Clear the trustedhosts value
Clear-Item WSMan:\localhost\Client\TrustedHosts -Force
}
#endregion
$Session = New-PSSession myTargetMachine
Add-FunctionToPsSession $session -FunctionInfo (Get-Command Test-IsAdministrator)
$myVar = Get-Date
Add-VariableToPsSession -Session $Session -Variable (Get-Variable myVar)
$params = @{
Module = (Get-Module -List AutomatedLab.Common)[0]
Session = (New-PSSession -ComputerName Host1, Host2, Host3)
IncludeDependencies = $true
Scope = 'CurrentUser'
}
Send-ModuleToPSSession @params
Running Remote Commands on Microsoft Docs