I am trying to send and extract the zip file to azure VM but unable make the connection to the remote Azure VM.
Code
$cred = Get-Credential
$SO = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption $SO
Send-File -Path C:\testArchive.zip -Destination C:\ -Session $session
Expand-Archive -Path C:\testArchive.zip -DestinationPath C:\ -Session $session
Error
New-PSSession : [xx.xx.xxx.xxx] Connecting to remote server xx.xx.xxx.xxx
failed with the following error message : The client cannot connect to the
destination specified in the request. Verify that the service on the
destination is running and is accepting requests. Consult the logs and
documentation for the WS-Management service running on the destination, most
commonly IIS or WinRM. If the destination is the WinRM service, run the
following command on the destination to analyze and configure the WinRM
service: "winrm quickconfig". For more information, see the
about_Remote_Troubleshooting Help topic.
At line:4 char:12
+ $session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:Re
moteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed
Below is the output when i run 'winrm quickconfig' command on azure VM
WinRM service is already running on this machine.
WinRM is already set up for remote management on this computer.
When I run the 'Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-admin'
Enter-PSSession : Connecting to remote server LoadTestVm failed with the following error
message : The WinRM client cannot process the request because the server name cannot be
resolved. For more information, see the about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ Enter-PSSession -ComputerName LoadTestVm -Port 3389 -Credential qa-ad ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (LoadTestVm:String) [Enter-PSSession], PSRem
otingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
WINRM will run on either ports 5985 and 5986. The port 5985 is for HTTP and 5986 is for HTTPS. By default, it uses port 5985 if you have not specified it with -port. You should specify port 5985 instead of 3389, also enable it in your NSG if you have. So you could run Enter-PSSession -ComputerName "PublicIPaddress of VM" -Port 5985 -Credential $cred.
This works on my side.
Copy-Item -Path D:\nancy\4.zip -Destination C:\ –ToSession $session
Invoke-Command -Session $session -ScriptBlock { Expand-Archive -Path C:\4.zip -DestinationPath C:\ }
More references:
https://www.assistanz.com/access-azure-windows-vm-through-powershell/
https://geekdudes.wordpress.com/2016/11/16/enabling-remote-powershell-connection-to-azure-virtual-machine/
https://mohitgoyal.co/2016/11/10/enable-powershell-remoting-on-azure-rm-virtual-machines/
This is not really a best practice risk management/Security-wise.
<#
$username = 'qa-admin'
$pass = ConvertTo-SecureString -string 'xxxxxxxx' -AsPlainText -Force
#>
This ...
<#
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
#>
... there is a built-in cmdlet for this.
Never pass clear text passwords in a script. Either:
prompt for them
Read them from a secure pre-created file
Quickly and securely storing your credentials – PowerShell
Working with Passwords, Secure Strings and Credentials in Windows
PowerShell
from Windows credential manager
CredentialManager 2.0
Accessing Windows Credentials Manager from PowerShell
How to Manage Secrets and Passwords with CredentialManager and
PowerShell
$cred = Get-Credential -Credential $env:USERNAME
This...
$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
...is not correct. You cannot do this. You need the results of the above to pass to the -SessionOption param.
Get-Help -Name New-PSSessionOption -Examples
<#
NAME
New-PSSessionOption
SYNOPSIS
Creates an object that contains advanced options for a PSSession.
Example 1: Create a default session option
PS C:\>New-PSSessionOption
...
This command creates a session option object that has all of the default values.
Example 2: Configure a session by using a session option object
PS C:\>$pso = New-PSSessionOption -Culture "fr-fr" -MaximumReceivedObjectSize 10MB
PS C:\>New-PSSession -ComputerName Server01 -SessionOption $pso
...
Example 3: Start an interactive session
PS C:\>Enter-PSSession -ComputerName Server01 -SessionOption (New-PSSessionOption -NoEncryption -NoCompression)
...
Example 4: Modify a session option object
PS C:\>$a = New-PSSessionOption
...
PS C:\> $a.UICulture = (Get-UICulture)
PS C:\> $a.OpenTimeout = (New-Timespan -Minutes 4)
PS C:\> $a.MaximumConnectionRedirectionCount = 1
PS C:\> $a
...
Example 5: Create a preference variable
PS C:\>$PSSessionOption = New-PSSessionOption -OpenTimeOut 120000
...
Example 6: Fulfill the requirements for a remote session configuration
PS C:\>$skipCN = New-PSSessionOption -SkipCNCheck
PS C:\>New-PSSession -ComputerName 171.09.21.207 -UseSSL -Credential Domain01\User01 -SessionOption $SkipCN
...
Example 7: Make arguments available to a remote session
PS C:\>$team = #{Team="IT"; Use="Testing"}
PS C:\>$TeamOption = New-PSSessionOption -ApplicationArguments $team
PS C:\>$s = New-PSSession -ComputerName Server01 -SessionOption $TeamOption
PS C:\>Invoke-Command -Session $s {$PSSenderInfo.SpplicationArguments}
...
PS C:\>Invoke-Command -Session $s {if ($PSSenderInfo.ApplicationArguments.Use -ne "Testing") {.\logFiles.ps1} else {"Just testing."}}
...
#>
So, yours is...
$SO = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$session = New-PSSession -ConnectionUri 'http://xx.xx.xxx.xxx:3389' -Credential $cred -SessionOption $SO
# Process other actions
Send-File -Path C:\testArchive.zip -Destination C:\ -Session $session
Expand-Archive -Path C:\testArchive.zip -DestinationPath C:\ -Session $session
Related
I'm using a PowerShell to open a session in a VM. I can run some code to write in a local folder, but I'm unable to write in a server. Even if I have all rights it gives me "Access Denied".
I'm trying to write on the server first/make folders in the server. I'm using a simple PowerShell that creates a folder.
$secpasswd = ConvertTo-SecureString 'PassWord' -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("UserName", $secpasswd)
$s = New-PSSession -ComputerName NameVM -Credential $mycreds
Invoke-Command -Session $s -ScriptBlock {
C:\Users\MyName\Documents\CreateFolder.ps1
}
+ CategoryInfo : PermissionDenied: (\\X\X\TestFolderVM:String) [New-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand
+ PSComputerName : VMNAME
You got the wrong idea here. PowerShell New-PSSession creates an interactive prompt to the new computer. What you should probably be using instead is something along the lines of:
Invoke-Command -ComputerName HOSTNAME -ScriptBlock CONTENTSOFPS1 -Credentials $creds
I'm trying to set up PS Remoting/Win-RM and have the following:
$primary = 'server1'
$user = $env:UserName
$admUser = Get-Credential -UserName "domain\adm-$user" -Message 'Enter your *ADMIN* password:'
Enter-PSSession -ComputerName $primary -Credential $admUser {
hostname
}
However, this is returning the following error (I've tested this from a console and it works, so there's something wrong with my script):
Windows PowerShell credential request.
Enter your *ADMIN* password:
Password for user domain\adm-user1: ***************
Enter-PSSession : A positional parameter cannot be found that accepts argument '
hostname
'.
At line:5 char:1
+ Enter-PSSession -ComputerName $primary -Credential $admUser {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Enter-PSSession], ParameterBindingException
+ FullyQualifiedErrorId :PositionalParameterNotFound,Microsoft.PowerShell.Commands.EnterPSSessionCommand
What am I doing wrong? Thanks in advance!
Enter-PSSession opens a console connection to a remote system.
If you want to run a command on a remote system, you'd want to use Invoke-Command.
Also, you 100% always need to pass scriptblocks into some parameter (minus some edge cases where it's accepted by default). In this case, we need to use -Scriptblock.
Example:
Invoke-Command -ComputerName $primary -Credential $admUser -ScriptBlock {
hostname
}
or
$session = New-PSSession -ComputerName $primary -Credential $admUser
Invoke-Command -Session $session -ScriptBlock {hostname}
Invoke-Command -Session $session -ScriptBlock {$env:USERNAME}
Disconnect-PSSession -Session $session
I am getting the below error, please advise how to fix this error for null-valued expression
You cannnot call a method on a null-valued expression
+CategoryInfo : InvalidOoperation: (:)[], RuntimeException
+FullyQualifiedErrorId: InvokeMethodonNull
+PSComputerName: DC1
Code below
function myfunction (){
$remoteserver = 'DC1'
$Session = New-PSSession -Computername $remoteserver -Credential $Cred
Import-Module ActiveDirectory
$local= $env:COMPUTERNAME
Invoke-Command -ComputerName $remoteserver -Credential $cred -ScriptBlock
{$using:local
if($local.substring(5,3) -imatch "Sys") {
Get-ADComputer $local | Move-ADObject -Targetpath "ou=PRD,ou=Servers,dc=com,dc=Companycorp,dc=net"}
}
} #end function
Invoke-Command -ComputerName $remoteserver -ScriptBlock ${Function:myFunction}
What you're looking for is the $using: scope. If you define variables that you want to use in your remote execution, you need to access them like:
$PC = $env:ComputerName
Invoke-Command -Computer DC01 -ScriptBlock { $using:PC <# logic #> }
If you mean you want to remote into DC01 to run commands against localhost, you're going to run into the second-hop problem due to Kerberos.
Update: Your new example looks pretty convoluted. Here's an example that should work:
$MyPC = $env:ComputerName
$Session = New-PSSession -Credential (Get-Credential) -ComputerName 'DC1'
Invoke-Command -Session $Session -ScriptBlock {
Import-Module -Name 'ActiveDirectory'
$PC = $using:MyPC
If ($PC.Substring(5,3) -eq 'sys')
{
Get-ADComputer -Identity $PC |
Move-ADObject -TargetPath 'ou=PRD,ou=Servers,dc=com,dc=Companycorp,dc=net'
}
}
What I think you're asking is 'how do I open a session on a remote pc, but then still run commands on my local PC'. If that's so, then let's walk through it.
First, we can open a remote connection to another computer in PowerShell by creating a new PSSession, as you're doing here:
$session = New-PSSession -Computername DC01 -Credential $cred
You can then either step into the remote computer wholly using Enter-PSSession, or just send individual commands to the remote computer using:
Invoke-Command -ScriptBlock {#Commands to run on the remote PC}`
-Session $session
Once you enter the remote PC, you can return to your own PC using the Exit-PSSession command.
#Enter Remote PC
Enter-PSSession $session
DC01> hostname
*DC01*
#Step out of Remote PC
Exit-PSSession
PS> hostname
*YOURPCNAME*
If this isn't what you want to do, let me know and we'll get you sorted.
You have to use Invoke-Command :
$session = New-PSSession -Computername DC01 -Credential $cred
Invoke-Command -Session $session -ScriptBlock {
$remoteComputerName = $env:computername
}
I have gone through many blogs for finding solution for this issue, but never find a solution.
$CompName = "test.domain.com"
$Printer = "\\122.21.10.11\PRINTER-NAME-1"
Invoke-Command -ComputerName $CompName -Scriptblock {
Param($p)
(New-Object -Com Wscript.Network).AddWindowsPrinterConnection($p)
} -ArgumentList $Printer
I have even tried PSRemoting and tried to execute the ps1 file from remote machine. the same script is working in local and not working remote.
Enter-PSSession -ComputerName "testserver.testdomain.com" -Authentication Credssp -Credential Get-Credential
Error:
Exception calling "AddWindowsPrinterConnection" with "1" argument(s): "The printer name is invalid. (Exception from HRESULT: 0x80070709)"
Updates:
Working without CredSSP:
Invoke-Command -ComputerName remotemac.mydomain.com -ScriptBlock {
Get-ChildItem C:\Users\myusername\Desktop
}
Working with CredSSP:
Invoke-Command -ComputerName remotemac.mydomain.com -ScriptBlock {
Get-ChildItem \\sharedmac\sharef
} -Authentication Credssp -Credential mydomain\myusername
Script is working, but not showing network printers:
Invoke-Command -ComputerName remotemac.mydomain.com -ScriptBlock {
(New-Object -ComObject WScript.Network).EnumPrinterConnections()
} -Authentication Credssp -Credential mydomain\myusername
Script gives error: Invalid Printer name
$Printer = "\\172.26.30.13\SDB1-FLOOR1-B2" # I have tried this input in single, double, with and without escape character
Invoke-Command -ComputerName remotemac.mydomain.com -ScriptBlock {
Param($p)
(New-Object -Com WScript.Network).AddWindowsPrinterConnection("$p")
} -ArgumentList $Printer -Authentication Credssp -Credential mydomain\myusername
I'm totally stuck.
I heard we can use Group Policy, is there anyway we can automate this using group policy?
I have a re-usable script that I've been using with success calling a remote ps1 file but now I'm trying to call a remote batch file and I get the following error message -
Invoke-Command : The value of the FilePath parameter must be a Windows
PowerShell script file. Enter the path to a file with a .ps1 file name
extension and try the command again.
This is the script -
#Admin Account
$AdminUser = "domain\svc_account"
$Password = Get-Content D:\scripts\pass\crd-appacct.txt | convertto-securestring
$Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminUser, $Password
$FileName = "runme.bat"
$ItemLocation = "D:\path\to\bat\"
#Invoke Script Remotely
Invoke-Command -ComputerName Servername -filepath "$ItemLocation$FileName" -Authentication CredSSP -Credential $Credential
You should use -ScriptBlock parameter instead of -FilePath:
Invoke-Command -ComputerName Servername -ScriptBlock {& "$using:ItemLocation$using:FileName"} -Authentication CredSSP -Credential $Credential
Or if you are using PowerShell v2, which does not have $using:VariableName syntax:
Invoke-Command -ComputerName Servername -ScriptBlock {param($ItemLocation,$FileName) & "$ItemLocation$FileName"} -ArgumentList $ItemLocation,$FileName -Authentication CredSSP -Credential $Credential