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
Related
I need to create a powershell script that launch an exe file which also has two parameters, I want to put it in a group policy, so that it starts at the power on of each computer.
I tried this command:
$Username = 'user'
$Password = 'pass'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $pass
invoke-command -Credential $Cred -ScriptBlock {& 'C:\myfile.exe' --param1 value --param2}
It tells me
Invoke-Command : Impossibile risolvere il set di parametri utilizzando i parametri denominati specificati.
In riga:1 car:1
+ invoke-command -Credential $Cred -ScriptBlock { & 'C:\Program Files ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.InvokeCommandCommand
I also tried this:
invoke-command -Credential $Cred -ScriptBlock {Start-Process -FilePath 'C:\myfile.exe' -ArgumentList "--param1 value", "-psb4"}
but the error that appears is the same.
I'm new to PowerShell. I am trying to make it so I can setup a new computer connecting to the network to allow me to do certain tasks. When I run this:
$domain = "mydomain.com"
$mycred = get-credential
$credential = New-Object System.Management.Automation.PSCredential("$($domain)\$($mycred.Username)","$($mycred.Password)")
$compName = Read-Host -Prompt "Enter new computer name"
Add-Computer -DomainName $domain -newname $compName -Credential $credential -Restart
Pause
I get the error:
New-Object : Cannot find an overload for "PSCredential" and the argument count: "2".
At C:\Users\entername\Downloads\1-JoinDomainCred.ps1:7 char:15
... redential = New-Object System.Management.Automation.PSCredential("$($ ...
CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Where am I going wrong?
Get-Credential aready returns a proper credentials object. Just use that:
$mycred = Get-Credential; Add-Computer ... -Credential $mycred
PowerShell is not C#, pass the arguments as an array without the ():
$credential = New-Object System.Management.Automation.PSCredential "$($domain)\$($mycred.Username)",$mycred.Password
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
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
Sorry for my English.
I have VMs on VMWare ESXi running Windows 7. All of the machines are in domain, but sometimes they leave domain, so I need to rejoin it. I wrote simple script to do this:
$credential = New-Object System.Management.Automation.PsCredential("mydomain\user", (ConvertTo-SecureString "password" -AsPlainText -Force))
Add-Computer -WorkGroupName TEMP -Credential $credential
Add-Computer -DomainName "mydomain" -Credential $credential
Restart-Computer
But it doesn't work; I have this error:
Add-Computer : This command cannot be executed on target computer('') due to following error: An existing connection was forcibly closed by the remote host.
At C:\Tools\Re-Join.ps1:2 char:13
+ Add-Computer <<<< -WorkGroupName TEMP -Credential $credential
+ CategoryInfo : InvalidOperation: (:) [Add-Computer], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.AddComputerCommand<br>
If I manually join 'workgroup' and then run the script all works fine.
Here's the script I use to join domain:
$computer = Get-WmiObject Win32_ComputerSystem
$computer.JoinDomainOrWorkGroup("cloud.com" , "PASSWORD HERE", "USER", $null, 3)
Restart-Computer -Force
You may add an unjoin before the join, you won't need to reboot before rejoining the domain:
$computer.UnJoinDomainOrWorkGroup("PASSWORD HERE", "USER", 0)