Home > OS >  Enter-PSSession doesn't execute command on remote computer
Enter-PSSession doesn't execute command on remote computer

Time:02-14

I want execute some of powershell comand on remote computer. My ps1 file is contain below data:

$secure_password = 'password' | ConvertTo-SecureString -AsPlainText -Force
$credential_object = New-Object System.Management.Automation.PSCredential -ArgumentList 'administrator', $secure_password 
$new_session = New-PSSession -Credential $credential_object -ComputerName  192.168.1.222
Enter-PSSession $new_session
{
  mkdir "C:\Users\Administrator\Desktop\new_folder"
}
Exit-PSSession  
Remove-PSSession $new_session

I want make a directory in my remote computer that ip is 192.168.1.222 but unfortunately doesn't make directory in remote computer. Why doesn't it work?

CodePudding user response:

You create PSSession when you want to execute multiple commands on a remote system. However, if you only need to run a single command/script, no need for a persistent PSSession.

You use Enter-PSSession for interactive work. However, when you using PSSession in a script/function, simply use Invoke-Command instead. It will be easier and faster.

Example

$secure_password = 'password' | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList 'administrator', $secure_password 

Invoke-Command -ComputerName 192.168.1.222 -Credential $cred -ScriptBlock { New-Item -Name "C:\Users\Administrator\Desktop\new_folder" -ItemType Directory }

Note: It is a bad idea to hardcode clear-text passwords into your scripts. Have a look at a native way to store credentials externally: SecretManagement

  • Related