Copy-Item command in powershell: problem with credentials - windows

I am writing a powershell script that copies a .jar file from a server to a remote VM. When it gets to the Copy-Item command, it fails with this error:
Copy-Item : The user name or password is incorrect.
+ Copy-Item -Path $source -Destination '\\consolidate\c$ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Comma
nds.CopyItemCommand
I have tried adding a -Credentials argument to the Copy-Item command. That gives me this error:
The FileSystem provider supports credentials only on the New-PSDrive cmdlet.
Perform the operation again without specifying credentials.
At [file path]
+ Copy-Item -Path $source -Destination '\\consolidate\c$ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported
Here is the code around the line in question:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
Invoke-Command -ComputerName "consolidate" -Credential $credentials -ScriptBlock {
New-PSDrive -Name "X" -PSProvider FileSystem -Root "C:\" -Credential $Using:credentials
}
Copy-Item -Path $calcEngineJarPath -Destination '\\consolidate\c$'
...
Remove-PSDrive X

You'd want to create a new PSDrive on your local machine that maps the network path to a drive letter:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
# Create mapped network drive
New-PSDrive -Name "X" -PSProvider FileSystem -Root "\\consolidate\c$\" -Credential $credentials
# Copy to mapped network drive
Copy-Item -Path $calcEngineJarPath -Destination X:\
Alternatively, use Copy-Item's -ToSession parameter:
$password = ConvertTo-SecureString -AsPlainText -Force -String $vmPwd
$user = "consolidate\$vmUser"
$credentials = New-Object System.Management.Automation.PSCredential $user,$password
# Create a new PSRemoting session on the target machine using the credentials
$session = New-PSSession -ComputerName consolidate -Credentials $credentials
# Copy file to remote session drive
Copy-Item -Path $calcEngineJarPath -Destination C:\ -ToSession $session

Related

Automate user homedirectory creation Powershell

I'm automating the process of creating LocalUsers on Windows systems. So far I used the Microsoft docs on New-LocalUser which has worked fine to create the account, this is my code so far:
function New-AdminUser {
param(
[Parameter(Position=0)]
[string] $UNameLocal,
[Parameter(Position=1)]
[string] $UDescription,
[Parameter(Position=2)]
[System.Security.SecureString] $Password
)
New-LocalUser -Name $UNameLocal -Description $UDescription -Password $Password -AccountNeverExpires -Confirm
Add-LocalGroupMember -Group "Administrators" -Member $UNameLocal
}
But this command does not actually generate the homedirectory in C:\Users\username.
I can create this by manually logging into the created user, but I want to automate this in Powershell. I couldn't find anything in the LocalAccounts module.
Is there any way to automate local account setup in Windows 10 using Powershell, without having to manually log in to a new account?
If you start a process (cmd /c) as the created user, it will create his profile. Add this to your function:
$Cred = New-Object System.Management.Automation.PSCredential ("$UNameLocal", $Password)
Start-Process "cmd.exe" -Credential $Cred -ArgumentList "/C" -LoadUserProfile
Here is the code:
param([Parameter(Mandatory=$true)][String]$samAccountName)
$fullPath = "\\srv2012r2\Users\{0}" -f $samAccountName
$driveLetter = "Z:"
$User = Get-ADUser -Identity $samAccountName
if($User -ne $Null) {
Set-ADUser $User -HomeDrive $driveLetter -HomeDirectory $fullPath -ea Stop
$homeShare = New-Item -path $fullPath -ItemType Directory -force -ea Stop
$acl = Get-Acl $homeShare
$FileSystemRights = [System.Security.AccessControl.FileSystemRights]"Modify"
$AccessControlType = [System.Security.AccessControl.AccessControlType]::Allow
$InheritanceFlags = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
$PropagationFlags = [System.Security.AccessControl.PropagationFlags]"InheritOnly"
$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule ($User.SID, $FileSystemRights, $InheritanceFlags, $PropagationFlags, $AccessControlType)
$acl.AddAccessRule($AccessRule)
Set-Acl -Path $homeShare -AclObject $acl -ea Stop
Write-Host ("HomeDirectory created at {0}" -f $fullPath)
}
and here is the reference:
https://activedirectoryfaq.com/2017/09/powershell-create-home-directory-grant-permissions/

How to copy file to Ubuntu from Windows via PowerShell script

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.

Map network drive permanently

How to change this script so netrwork drive is still aviable after machine reboot?
$User = "user"
$PWord = ConvertTo-SecureString -String "password" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
$net = $(New-Object -ComObject WScript.Network)
$net.MapNetworkDrive("r:", "\\name\othername")
Powershells way:
New-PSDrive -Name "R" -PSProvider FileSystem -Root "\\name\othername" -persist:$true -Scope Global
Use:
net use r: \\name\othername

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"

PowerShell_copy-item_ToSession/FromSession

I want to copy a file from the remote server to local, and my code is
Make sure the xxx.xxx.x.xxx's connection
>
Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString | Out-File"C:\Users\chrishchang\Desktop\powershell/remote-password.txt"
$user = get-content C:\Users\chrishchang\Desktop\powershell/remote-user.txt
$pass = get-content C:\Users\chrishchang\Desktop\powershell/remote-password.txt |
ConvertTo-securestring
&myCred = new-object -typename System.Management.Automation.PSCredential -argumentlist $user,$pass
$session = new-pssession -computername name -credential $myCred
Invoke-Command -ComputerName xxx.xxx.x.xxx -ScriptBlock { ipconfig /all } -credential $myCred
create the new file
>
$command={New-Item c:\scripts\new_file.txt -type file -force -value "This is text added to the file"}
Invoke-Command -session $session -scriptblock $command
copy the file from xxx.xxx.x.xxx to local
>
$command={Copy-Item -FromSession $session -Path "c:\scripts\new_file.txt" -Destination "C:\Users\chrishchang\desktop\"}
Invoke-Command -session $session -scriptblock $command
The error result..
enter image description here
Please give me some suggestion, I have suffered from it for a long time.
The last step (3) should be:
Copy-Item -FromSession $session -Path "c:\scripts\new_file.txt" -Destination "C:\Users\chrishchang\desktop"
Don't use Invoke-Command as the Copy-Item already uses the session.

Resources