Как копировать файл на удаленный компьютер с помощью power shell

Dimitri Koens

PowerShell provides some commands to manipulate services, but that might not work on remote computers! The script below demonstrates that stopping a service on a remote computer using Stop-Service is not working.

First I verify that the MSDTC service is running on the local machine and a remote machine: server2. If I want to stop the service on both machines I use the Stop-Service cmdlet. But this command doesn’t work on server2 when I’m piping the output from Get-Service to Stop-Service.

There are two solutions. The first is you can use the InputObject parameter as part of Stop-Service.

You can also use WMI to stop a remote service. Just retrieve the specific service from a remote computer by using the Get-WmiObject cmdlet and use the StopService method to stop the service.

WMI is intended to work remote so this command gives the correct result! 🙂

Thanks to Martin Tengvall for pointing out the -InputObject variant.

When working in a mixed environment, PowerShell and SSH make for a good remote management combination.

When Microsoft made its PowerShell automation tool open source in 2016, part of the reason was to develop cross-platform compatibility to include macOS and Linux systems. It came as no surprise when the PowerShell team implemented SSH connectivity to enable PowerShell remoting to Linux boxes. SSH is widely considered to be the standard for remoting. Learn how PowerShell remoting over SSH is different from traditional remote management methods in a Windows environment and the basics of how to use remoting over SSH to both Windows and Linux machines.

What is the difference between remoting with SSH and WinRM?

The conventional method for managing Windows remotely is with Windows Remote Management (WinRM), which is Microsoft’s version of the Web Services-Management protocol.

To start the WinRM service on Windows, enter the command from the Run menu. WinRM is a Windows native service that PowerShell has supported since version 2.0 on Windows 7 and Windows Server 2008.

SSH is the standard remoting tool for Linux. Microsoft added native support on clients running at least Windows 10 1809 and servers running at least Windows Server 2019 with the optional OpenSSH capability installed.

However, if you are introducing Windows into a Linux environment where your configuration management tool, such as Ansible, is already configured for SSH on port 22, then it is reasonable to stick with SSH. Ansible supports managing Windows over SSH, although it is considered experimental at this stage.

The prerequisites for PowerShell remoting over SSH are PowerShell 7+ and SSH.

The target computer requires an SSH server, and the source computer requires an SSH client. For Windows, OpenSSH is recommended for both server and client in its respective variant.

https://youtube.com/watch?v=Atbl7D_yPug%3Fautoplay%3D0%26modestbranding%3D1%26rel%3D0%26widget_referrer%3Dhttps%3A

How to set up OpenSSH on Windows

OpenSSH feature check
Figure 1. Use PowerShell to check the status of OpenSSH on the system.
Add-WindowsCapability -Online -Name "OpenSSH.Server~~~~0.0.1.0"

Lastly, start the SSH service:

SSH remoting configuration
Figure 2. The Enable-SSHRemoting cmdlet handles updates to the SSHD service and other tasks related to SSH configuration.

Run the help for the cmdlet to see all the work this PowerShell command performs related to SSH remoting:

The last step is to restart the service:

How to set up OpenSSH for PowerShell on Linux

sudo apt install powershell
sudo apt install openssh-client
sudo apt install openssh-server

Next, use the same PowerShell module and command used with Windows to install RemotingTools and run the cmdlet and restart sshd, the SSH service:

Install-Module Microsoft.PowerShell.RemotingTools
Enable-SSHRemoting
service sshd restart

How to perform PowerShell remoting over SSH

The difference is that using the PowerShell command uses the PowerShell endpoint.

You can finish the session with the command.

PowerShell remoting over SSH does not require named endpoints like WinRM. Instead, you can use an IP address.

works from Windows or Linux to a Windows machine or a Linux machine as long as you have met the prerequisites.

:/>  Команды ms dos echo

How to run scripts with a PowerShell remoting session

is great for interactive use, but running a script remotely requires a different approach. You want to use to create a session object and then run commands with the cmdlet. The command starts a persistent session to the remote machine, while enables running commands on local and remote machines.

First, generate and configure SSH keys needed to pass a password to the cmdlets. The process to set up SSH keys is outside the scope of this article, but producing them for PowerShell is the same as making them for typical SSH activities.

After creating the SSH keys, create a PowerShell session object:

remote machine processes
Figure 3. Use the Invoke-Command cmdlet to see the processes running on the remote machine.

How do I perform advanced PowerShell remoting procedures?

The script has no OS checks because works the same in Windows and Linux.

In this example script, you can find all computers with a certain file path:

How to troubleshoot PowerShell remoting over SSH issues

If you find yourself unable to connect to a remote device over SSH after checking through the prerequisites, then you can use PowerShell to troubleshoot.

First, check that you have restarted the sshd service with this command:

Next, test SSH connectivity:

Test-NetConnection -ComputerName 10.0.0.10 -Port 22

Lastly, test to see if SSH is working by using SSH without PowerShell:

Why you should consider SSH remoting with PowerShell

Even if WinRM-based PowerShell remoting is the recommended method for Windows device management, you can see the possibilities that open up with SSH remoting. As long as you don’t need remote endpoint configuration or JEA, then SSH works in most scenarios. If you want to have a consistent remoting experience across Windows and Linux, then it’s time to get SSH up and running.

  • Add -Wait to your remote Start-Process call to ensure that wusa.exe runs to completion before returning from the remote Invoke-Command call.

    • Otherwise, with an ad-hoc remoting session implicitly created via use of the -ComputerName parameter, the Start-Process-launched process is automatically terminated when the Invoke-Command call returns.
  • Code executed via PowerShell’s remoting runs invisibly on the target machines, so the use of -Verb RunAs is pointless:


Therefore, with synchronous execution:

# ... credential construction code ($Cred) omitted
# Note: If the *current user* is allowed to make remoting calls,
# you may not need to construct credentials and don't need the
# -Credential parameter below.
# Note the use of -Wait, removal of -Verb RunAs
Invoke-Command -ComputerName 8HPF31J7V6.domain.local -Credential $Cred -ScriptBlock { Start-Process -Wait wusa.exe -ArgumentList 'C:\Temp\windows10.0-kb5032189-x64_0a3b690ba3fa6cd69a2b0f989f273cfeadba745f.msu'
}

If you don’t want the Invoke-Command call to wait for the remotely launched process (wusa.exe) to terminate, you have two options:

  • In the simplest case, add the -AsJob switch to the call above, which makes Invoke-Command return a job object that can be queried for output and completion later, on demand, with Receive-Job and Wait-Job, as shown below.

  • Create a remote session explicitly, via New-PSSession, and pass it to Invoke-Command‘s -Session parameter. Such a session stays open until it is either explicitly removed with Remove-PSSession or times out due to inactivity.

    • However, to make the call asynchronous, you must then not use -Wait with Start-Process, and track the lifetime of the process in the remote session, by adding -PassThru to output a process-information object that you must capture in a variable, and consult again in a later Invoke-Command call with the same -Session argument.

Asynchronous variant with -AsJob, which additionally demonstrates how to report the remote process’ exit code:

# ... credential construction code omitted
# Note the use of -AsJob and the use of -PassThru with Start-Process
# so as to be able to report the process' exit code.
$remoteJob = Invoke-Command -AsJob -ComputerName 8HPF31J7V6.domain.local -Credential $Cred -ScriptBlock { ( Start-Process -Wait -PassThru wusa.exe -ArgumentList 'C:\Temp\windows10.0-kb5032189-x64_0a3b690ba3fa6cd69a2b0f989f273cfeadba745f.msu' ).ExitCode }
# ... perform foreground activity here.
# Now wait for the remote job to complete - which happens when
# wusa.exe terminates - and report its exit code.
$exitCode = $remoteJob | Receive-Job -Wait -AutoRemoveJob 

Command Line Interface on WindowsCommand Prompt Application first comes to your mind. However, another great Command Line Interface is Windows Terminal i.e. Windows Powershell which can be also useful.

:/>  Скачать W10Privacy на русском - блокировщик служб Windows 10.

If you want to perform Remote Command Execution on some other Remote Computers, then the Powershell on Windows will be used. This article will discuss the steps to Execute Remote Commands on Windows Powershell

What is Remote Command Execution on Windows?

If you are on any local Windows OS & want to perform some actions on the Windows PowershellExecution of Remote Command will be the only option. The Remote Command Execution enables the method to access other Windows Powershell Applications from any single device with the help of the IP Address.

Once, you enter the Computer Name or IP Address of the Windows, those two computers will be associated only with Powershell. That means, the Powershell of two Windows Computers will be connected & from your device you can execute some commands on the Remote Device. Here, two entire Windows OS are not completely connected.

How to Enable Remote Command Execution on Powershell?

Note: By default, the Remote Command Execution on Windows Powershell is disabled. So, if you have to work on the concept, you have to Enable Powershell Remote Command Execution

2--Windows-Powershell-(Admin)

Command: 

1--Enable

How to Check Remote Command Execution Connection on Powershell?

Command: Test-WSMan <IP Address Or Remote Computer>

2--Testing

How to Run Remote Command Execution on Powershell?

Command: Enter-PSSession -ComputerName <IP Address Or Remote Computer>

3--Connection

4--Enter-Details

Step 3: Now, you will find the Computer Name will appear from the IP Address. Along with the Directory of Powershell will be changed. It is the indication that the Remote Connection is Successfully Created

5--Details

What are the Benefits of Remote Command Execution on Powershell?

Now, it is time to discuss the Benefits of Windows Powershell Remote Command Execution. There are multiple reasons behind to Use of Remote Execution of Commands on Powershell. Let us check all of those reasons one by one.

  • Efficiency:
  • Scalability:
  • Consistency: Consistency can be maintained when you execute the Remote Command Execution. In this case, the Constant Configuration Settings can be changed in other devices from a single device.

From the above discussion, we conclude that Configuring Remote Command Execution on Powershell is a very simple task. You have to just enter the Windows Powershell Commands there properly. Also, you have to take care of the IP Address of the Remote Device as it will be inserted into the system for the connection.

How to Run Remote Command Execution on Powershell – FAQs

How to Run Remote Command Execution on Powershell?

  1. Execute the Command as Enter-PSSession -ComputerName <IP Address Or Remote Computer>
  2. The Remote Command Execution will be done.

How to Enable Remote Command Execution on Powershell?

  1. Execute the command as Enable-PSRemoting -Force.
  2. Check the connection status as Test-WsMan <IP Address Or Remote Computer>.

What is Remote Command Execution?

The Remote Command Execution is the process where you can access the Powershell of another computer placed at a distance. You have to use the IP Address of that Remote Device & hence two devices will get connected with the help of some Windows Commands. This helps to manage different devices at the same time.

How could I know the Remote Command Execution is connected?

Once, you have connected the Remote Command with the Remote Computer, you can see the Directory Change in the Local Powershell Application. You can see that the Remote Command Name will appear before the Powershell Directory. It is an indication that the Local Powershell is now acting as the Remote Powershell.

Why I should use Remote Command Execution?

There are multiple reasons present for which you can use the Remote Command Execution process. If you want to increase the Efficiency where with a single Local Device you can access many other Powershell of other computers, the Remote Command can be used. It also increases the Scalability & Consistency.

Please to comment…

PowerShell Copy File to Remote Computer

Next, we’ll take a quick look at the simple steps involved in copying file to a remote computer using powershell, and then we’ll go into more detail in the next section:

:/>  Пропал курсор на ноутбуке: как вернуть и что делать?

1: Create a New Remote Session

2: Verify the Session Properties

3: Copy File / Item from One Location to Another

4: Verify Whether the File Has Been Copied

5: Terminate the Remote Session

How to Copy File to Remote Computer Using PowerShell

Run PowerShell

Windows Powershell

Create a Connection to Remote Computer

$Session = New-PSSession -ComputerName “XXX” -Credential “XXX”

New PSSession

Note : You can type Credential Manager in the search box on the taskbar and open it to view credentials.

Verify the Session Properties

Then, you will see the returned command output.

Copy a File

Copy-Item “C:\Folder\test.txt” -Destination “D:\Folder_Copy\” -ToSession $Session

Copy Item command

Note : You can also use the FromSession parameter to copy files from the remote computer to local.

Verify Whether the File Has Been Copied

Then, you will see the returned command output.

Terminate the Remote Session

Remove-PSSession -Session $SESSION

Other Commands for Copying Items in Remote Session

Copy a folder to a remote computer

Copy-Item “D:\Folder\” -Destination “C:\Folder_Copy\” -ToSession $Session

No subfolders or files are copied if the Recurse parameter is not used.

Recursively copy the entire contents of a folder to a remote computer

Copy-Item “D:\Folder\” -Destination “C:\Folder_Copy\” -ToSession $Session -Recurse

Using the Rescue parameter, the subfolder is copied with its file tree intact.

Copy a file to a remote computer and rename the file

Copy-Item “D:\Folder\test.txt” -Destination “C:\Folder_Copy\test_copy.txt” -ToSession $Session

To rename the file, do not add the / symbol at the end of the file or folder name.

Copy a file from a remote computer to local

Copy-Item “C:\Folder\test.txt” -Destination “D:\Folder_Copy\” -FromSession $Session

The FromSession parameter is used for the copy command from the remote computer.

Copy Files to Remote Computer with Remote Access Software

Copying files to a remote computer using PowerShell commands can be challenging for those who are not tech-savvy. There are other methods to transfer files remotely, one of which is using the file transfer feature of third-party remote access software.

AirDroid Remote Support serves as a versatile remote access tool for seamless connectivity, instant online communication, and fast file transfer. You can easily transfer files within a chat dialog with the remote computer. Plus, you can explore additional features such as unattended access, black screen mode, and more.

AirDroid Remote Support File Transfer

Conclusion

After introducing the operation of using PowerShell to copy files to a remote computer, you will become familiar with Copy-Item command and learn to use it. Alternatively, you can use the file transfer feature of third-party remote access software, which is also a great way to copy files to different locations.