How to copy file to Ubuntu from Windows via PowerShell script - windows

Source is Windows and destination is Ubuntu (installed on VMware player).
I ran below script in Windows:
$targetComputerName = "192.168.22.130"
$Username = 'zahid'
$Password = 'Z#hid1212'
$Pass = ConvertTo-SecureString -AsPlainText $Password -Force
$SecureString= $pass
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString
$Session = New-PSSession $targetComputerName -Credential $MySecureCreds
$DestinationPath = "/home/zahid/Downloads"
$Source = 'D:\zahid.txt'
Copy-Item -Path $Source -ToSession $Session -Destination $DestinationPath
$Session | Remove-PSSession
and got error:
New-PSSession : [192.168.22.130] Connecting to remote server 192.168.22.130 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 C:\Users\DELL\Desktop\Untitled1.ps1:8 char:12
+ $Session = New-PSSession $targetComputerName -Credential $MySecureCre ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed
Copy-Item : Cannot validate argument on parameter 'ToSession'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
At C:\Users\DELL\Desktop\Untitled1.ps1:12 char:36
+ Copy-Item -Path $Source -ToSession $Session -Destination $Destination ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Copy-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.CopyItemCommand
Do I need to setup winrm service on destination (here is Ubuntu) also? How can I achieve that?

I used to use WinScp with PowerShell, or Posh-SSH.
These two ways allow you exploit conventional SSH on Linux.
Begining with PowerShell 6 you can use PowerShell remoting over SSH, this link show you the setup on Windows and Ubuntu.

Related

Powershell: Passing Credentials in a PSSession to a machine returns Incorrect network password

Just some notes:
The issue that is being faced does not happen on every machine, only 1 in 20
I know it is not a powershell issue, but need to know from a health perspective what could cause this
The machine allows a connection with an Admin account over the PS Port, but after that the machine does not see the rights of the account
If I pass the Credentials using a Get-Credential rather than a PS Credential Object, it works however this is not an acceptable solution as the script it being wrapped in an MSO Runbook
Code being used for Credentials:
$Username = "domainname\userid"
$Password = "P#s4w0rd1!" | ConvertTo-SecureString -AsPlainText -Force
$mycreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $Password
Code for the PSSession:
$Session1 = New-PSSession -ComputerName WorkstationNAme #Connects to the computer
Invoke-Command -Session $Session1 -ScriptBlock {
$FreeDrive = (68..90 | %{$L=[char]$_; if ((gdr).Name -notContains $L) {$L}})[0] #Grabs the first available Drive Letter
$execDriveLocation = New-PSDrive -Name $FreeDrive -PSProvider FileSystem -Root $Using:Variable1 -Credential $using:mycreds -Persist #Creates temporary mapped drive
}
Error Returned on the affected machines:
The specified network password is not correct
+ CategoryInfo : InvalidOperation: (D:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand
+ PSComputerName : computername
Any thoughts or suggestions?

Access Windows.Security.Credentials.PasswordVault over PS-Session on fresh Azure VM

This is essentially a re-post of this question: "Cannot open Vault" when accessing PasswordVault on a fresh machine via WinRM
It is quite old, and we don't don't know how to "bump" it, so we are restating here...
After entering a PS-Session on a fresh Azure Windows machine, server 2012r2, like so:
$username = 'print-dev'
$uri = 'somevm.eastus.cloudapp.azure.com'
$port = '5986'
$remote_address = "https://" + $uri + ":" + $port
$password = 'somepassword'
$pass = ConvertTo-SecureString -string $password -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
Enter-PSSession -ConnectionUri $remote_address -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
... we run the following command and fail:
[somevm.eastus.cloudapp.azure.com]: PS C:\Users\print-dev\Documents> [Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$vault = New-Object Windows.Security.Credentials.PasswordVault
$vault.RetrieveAll()
...with the following result:
Exception calling "RetrieveAll" with "0" argument(s): "Access is denied.
Cannot open Vault"
At line:1 char:1
+ $vault.RetrieveAll()
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : UnauthorizedAccessException
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
If we RDP to the machine with the same user, print-dev, bring up a console and run the command that way, we succeed. Also subsequent calls over remote access will succeed after being run from RDP the first time.
How can we get around this access denied error?
What is the difference between a PowerShell command executed in an RDP session and powershell command executed in Remote PS-Session by the same user?
Any help would be appreciated!

Copy-Item for copy files from local to remove server using credentials

I am trying to copy some files and folder from my local machine to a remote server:
Copy-Item .\copy_test.txt -destination "\\serverip\c$\backups\"
but I'm getting an error:
Copy-Item : Logon failure: unknown user name or bad password.
At line:1 char:10
+ Copy-Item <<<< .\copy_test.txt -destination "\\serverip\c$\backups\" -verbose
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
I was trying using credentials but this command does not allow -Credential argument. I was searching a lot and in every example the command is pretty easy just executing the Copy-Item $source -destination $destination and I wonder why is so hard in my workstation.
Creating New PSDrive
I tried to create a New-PSDrive but it didn't work.
$creds = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username, $password
New-PSDrive -Name X -PSProvider FileSystem -Root '\\$serverip\c$' -Credential $creds -Persist
Copy-Item '.\copy_test.txt' -Destination 'X:\backups'
Remove-PSDrive -Name X
It is the error message:
PS C:\Users\Administrator\Desktop> .\copyfiles.ps1
New-PSDrive : The network path was not found
At C:\Users\Administrator\Desktop\copyfiles.ps1:11 char:1
+ New-PSDrive -Name X -PSProvider FileSystem -Root '\\$serverip\c$' -Credential $c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (X:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveC
Copy-Item : Cannot find drive. A drive with the name 'X' does not exist.
At C:\Users\Administrator\Desktop\copyfiles.ps1:12 char:1
+ Copy-Item '.\copy_test.txt' -Destination 'X:\backups'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (X:String) [Copy-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
Remove-PSDrive : Cannot find drive. A drive with the name 'X' does not exist.
At C:\Users\Administrator\Desktop\copyfiles.ps1:13 char:1
+ Remove-PSDrive -Name X
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (X:String) [Remove-PSDrive], DriveNotFoundExcepti
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.RemovePSDriveCommand
My servers
My server are windows instances in AWS. I have the right permission because I am able to run other command like Invoke-Command in order to inspect some services into the remote server.
PS> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
If credentials are required for access to a remote share you need to map it to a (PS)drive before you can use it with other cmdlets.
$cred = Get-Credential
New-PSDrive -Name X -PSProvider FileSystem -Root "\\$serverip\c$" -Credential $cred -Persist
Copy-Item '.\copy_test.txt' -Destination 'X:\backups'
Remove-PSDrive -Name X
I found the solution. I was using PowerShell version 4.0 and then upgrade my version to 5.0
In previous version the Copy-Item doesn't allow credentials. Now is possible to copy files through the sessions between servers:
$deploy_dest = "C:\backup"
$username = "$server\Administrator"
$password = Get-Content C:\mypassword.txt | ConvertTo-SecureString -AsPlainText -Force
$creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$session = New-PSSession -ComputerName $server -Credential $creds
Copy-Item -Path .\copy_test.txt -Destination -ToSession $session
Check this alternative using copy command and net use
net use \\10.164.60.77\c$\Users\ana\Desktop password /user:username
copy "C:\Users\alex\Desktop\test.txt" "\\10.164.60.77\c$\Users\ana\Desktop\test.txt"

Using PSCredential Object to authenticate commands non-interactively

I am using the PSCredential Object to authenticate a command, which I need to be run as a different user.
I get the following on the powershell cli.
> whoami
dmn1\srveikafka
> $secpasswd = ConvertTo-SecureString "mypassword" -AsPlainText -Force
> $mycreds = New-Object System.Management.Automation.PSCredential ("srveizookeeper", $secpasswd)
>
> $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
> invoke-command -session $sess -scriptblock {whoami}
dmn1\srveizookeeper
But when I run these same commands as a powershell script I get this error.
new-pssession : [remotecomputer.xyz.com] Connecting to remote server remotecomputer.xyz.com failed with the following
error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
At C:\workstation\add_zookeeper_spn.ps1:13 char:9
+ $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At C:\workstation\add_zookeeper_spn.ps1:14 char:25
+ invoke-command -session $sess -scriptblock {whoami}
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
What am I getting wrong or missing?
You might need to include the domain as part of the username in the credential constructor:
$mycreds = New-Object System.Management.Automation.PSCredential ("dmn1\srveizookeeper", $secpasswd)

Moving client to a workgroup when the domain machine account doesn't exist

I'm working on some automation in our test environment where we have powershell scripts to join a windows client to either a domain or a workgroup.
I'm having trouble trying to move a windows 7 client from a domain to a workgroup, in the case where the client's machine account doesn't exist in the domain.
Here is the code:
$User = administrator
$Password = ConvertTo-SecureString "<password>" -AsPlainText -Force
$DomainCred = New-Object System.Management.Automation.PSCredential $User, $Password
remove-computer -credential $DomainCred -force -passthru -verbose
This is the error that is returned:
VERBOSE: Performing operation "Remove-Computer" on Target "localhost".
Remove-Computer: This command cannot be executed on target computer ('xxx')
due to following error: No mapping between account names and security IDs was done.
At line :1 char:16
+ remove-computer <<<< -credential $DomainCred -force -passthru -verbose
+ CategoryInfo : InvalidOperation: (xxx:String) [Remove-Computer],
InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.Powershell.
Commands.RemoveComputerCommand
However, if I try this using the GUI (Computer Properties, Advanced system settings, Computer Name , Change...), it prompts for credentials and succeeds.
How would I replicate this operation into the powershell command so that it can be done pragmatically?
Try Add-Computer, like this (untested):
Add-Computer -WorkgroupName "WORKGROUP" -Force
AFAIK the only difference between Add-Computer and Remove-Computer is that Remove-Computer also disables the computer account, which would probably give you this error since the computer account doesn't exist.
I have two options.
Option 01
$Workgroup = "CL-01" #IF you want to add computer to domain edit here(Domain name)
$Password = "Password" | ConvertTo-SecureString -asPlainText -Force
$Username = "$Workgroup\Username"
$Credential = New-Object System.Management.Automation.PSCredential($Username,$Password)
Add-Computer -WorkGroup $Workgroup -Credential $credential
Restart-Computer -Force
Option 2 and why Option 2 Storing a password in a script is not such a favorable option so I suggest taking up option 2
$Workgroup = "CL-01"#IF you want to add computer to domain edit here(Domain name)
$Password = Read-Host -Prompt "Enter password for $user" -AsSecureString
$Username = "$Workgroup\Username"
$credential = New-Object System.Management.Automation.PSCredential($Username,$Password)
Add-Computer -WorkGroup $Workgroup -Credential $credential
Restart-Computer -Force
Note: Run the all the Scripts as Administrator!!
Hope this will help!! Cheers!!

Resources