Using -Credential with Copy-Item failure - powershell

I am trying to copy a file to a UNC filename where my user has permission, but no traditional drive letter mapping. PSVersion 5.0.10586.11
# Get and store the password in an encrypted file. Do this once only.
# (Get-Credential).Password | ConvertFrom-SecureString | Out-File .\my_secret.txt"
$user = "me"
$file = ".\my_secret.txt"
$cred = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $user, (Get-Content $file | ConvertTo-SecureString)
Copy-Item -Credential $cred .\list.txt "\\zeplin.nowhere.org\data\docs\log"
Running the script seems to suggest that Copy-Item does not support -Credential. I would rather not create a new drive letter mapping with New-PSDrive unless I must. Using Get-Help Copy-Item shows that it supports the -Credentials parameter. The following error message is returned.
The FileSystem provider supports credentials only on the New-PSDrive cmdlet. Perform the operation again without specifying
credentials.
PS C:\Users\me> .\t.ps1
At C:\Users\me\t.ps1:8 char:1
+ Copy-Item -Credential $cred .\list.txt "\\zeplin.nowhere.org\data\docs ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported

Copy-Item has a Credential parameter for PS providers that support it. The FileSystem provider, as indicated, does not. You'll have to use New-psdrive.

Related

I want to store encrypted credentials and use them to open a powershell instance and run a script that makes a change to a field in AD

Below is my code, I've used the same process for connecting to sftp securely. I'm getting the error at the bottom of my post. Not sure if I'm missing a step in the creation of the key and password. Thanks.
#Set the credentials
$Password = Get-Content "c:\password.txt" |
ConvertTo-SecureString -Key (Get-Content "c:\aes.key")
$Credential = New-Object System.Management.Automation.PSCredential ('serviceaccount', $Password)
# Start a new instance of Windows PowerShell using the credentials
# stored in $Credential and run the script in $scriptblock
$powershellPath = "$env:windir\system32\windowspowershell\v1.0\powershell.exe"
$process = Start-Process $powershellPath -Credential $Credential -NoNewWindow `
-ArgumentList ("-ExecutionPolicy Bypass -noninteractive -noprofile " + $scriptBlock) -PassThru
# Script to execute in the new PowerShell instance
$scriptBlock = {
Import-Module ActiveDirectory
Get-ADUser ecarlsson | Set-ADUser -Manager bbob
Read-Host
}
I tried the code above and go the password error below.
Start-Process : This command cannot be run due to the error: The user name or password is incorrect.
At\filepath \\fV3.ps1:7 char:12
+ $process = Start-Process $powershellPath -Credential $Credential -NoN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

How do I use Powershell on my computer to use another computer to copy files from a third computer to a fourth computer?

Working remotely works fine -- mostly. Occasionally, I need to copy large files, or large numbers of files, from one server to another or from a vendor's web site to a server (like install sets). With limited upload speeds through the ISP I use at home, anything that involves large uploads will take a very long time.
It seems PowerShell's ability to run commands remotely should be able to help with this. I'm trying to create a simple app that will enable me to use another computer to copy from anywhere to anywhere (assuming I have appropriate permissions in all 3 places).
I like Start-BitsTransfer because it seems to be much faster and because I can use it to download software from a vendor's web site.
I have created a very simple example that I haven't been able to get to work.
If I log onto "server1" using Remote Desktop and do...
$src = "\\server2\c$\myfolder\*"
$dest = "c:\myfolder\"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Start-BitsTransfer -Source $src -Destination $dest
...it works fine. All of the files from c:\myfolder on server2 are copied to c:\myfolder on server1.
Trying to remove Remote Desktop from the equation, here's what I have so far:
#RemoteCopy.ps1
param(
[string]$computer,
[string]$source,
[string]$destination
)
Invoke-Command -ComputerName $computer -ScriptBlock {
$src = $args[0]
$dest = $args[1]
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Start-BitsTransfer -Source $src -Destination $dest
#Copy-Item -Path $src -Destination $dest
} -ArgumentList $source,$destination
From my workstation:
.\RemoteCopy.ps1 -computer server1 -source "\\server2\c$\myfolder\*" -destination "c:\myfolder\"
But nothing happens.
Since I'm logged onto the network on my workstation, there shouldn't be a credential problem. If there was, I would expect to receive an error message.
For this specific example, my workstation, server1, and server2 are on the same domain and my user account is an admin on all three machines.
I'm currently using PowerShell 5.1.
Responding to comments
$Credential = Get-Credential
Invoke-Command -ComputerName $computer -ScriptBlock {
$src = $args[0]
$dest = $args[1]
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Start-BitsTransfer -Source $src -Destination $dest
#Copy-Item -Path $src -Destination $dest
} -ArgumentList $source,$destination -Credential $Credential
...behaves the same.
$Credential = Get-Credential
Invoke-Command -ComputerName $computer -ScriptBlock {
$src = $args[0]
$dest = $args[1]
$cred = $args[2]
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Start-BitsTransfer -Source $src -Destination $dest -Credential $cred
#Copy-Item -Path $src -Destination $dest
} -ArgumentList $source,$destination,$Credential -Credential $Credential
...produces an error:
The operation being requested was not performed because the user has not logged on to the network. The specified service does not
exist. (Exception from HRESULT: 0x800704DD)
+ CategoryInfo : NotSpecified: (:) [Start-BitsTransfer], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.BackgroundIntelligentTransfer.Management.NewBits
TransferCommand
+ PSComputerName : server1
Invoke-Command -ComputerName $computer -ScriptBlock {
$src = $args[0]
$dest = $args[1]
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Start-BitsTransfer -Source $src -Destination $dest -Credential domain\username
#Copy-Item -Path $src -Destination $dest
} -ArgumentList $source,$destination -Credential domain\username
...produces the same error
And if I try to follow https://www.ipswitch.com/blog/the-infamous-double-hop-problem-in-powershell (the first link on https://duckduckgo.com/?q=%27powershell+doublehop%27&t=h_&ia=web) ...
Invoke-Command -ComputerName $computer -ScriptBlock {
Register-PSSessionConfiguration -Name RemoteCopy -RunAsCredential 'domain\username' -Force
}
Invoke-Command -ComputerName $computer -ScriptBlock {
$src = $args[0]
$dest = $args[1]
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Start-BitsTransfer -Source $src -Destination $dest -Credential domain\username
} -ArgumentList $source,$destination -ConfigurationName RemoteCopy.
...I get different errors:
Processing data for a remote command failed with the following error message: The I/O operation has been aborted because of either a thread exit or an application request. For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OperationStopped: (server1:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : JobFailure
+ PSComputerName : server1
[server1] Connecting to remote server server1 failed with the following error message : The WS-Management service
cannot process the request. Cannot find the RemoteCopy. session configuration in the WSMan: drive on the server1 computer.
For more information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (server1:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : InvalidResourceUri,PSSessionStateBroken
And if I remove the . from the end of the ConfigurationName argument in the Invoke-Command call, I get the same error I saw at the start of this rework:
The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist. (Exception from HRESULT: 0x800704DD)
+ CategoryInfo : NotSpecified: (:) [Start-BitsTransfer], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.BackgroundIntelligentTransfer.Management.NewBits
TransferCommand
+ PSComputerName : server1
I also read https://www.codeproject.com/Tips/847119/Resolve-Double-Hop-Issue-in-PowerShell-Remoting. But other reading indicates the CredSSP is not secure. Credentials can be stolen. So I'd need to run this one by my security and infrastructure experts.
If this is a problem with credentials (that for some reason doesn't generate any error messages), how would I get through that?

Remove-ItemProperty does not support credentials

I tried to remove registry object using admin credentials by powershell
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User,$pass
Invoke-Command -ScriptBlock {Remove-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\office\16.0\outlook\security" -Name "clearsign" -Credential $Credential}
But i got en error below:
The provider does not support the use of credentials. Perform the operation again without specifying credentials.
At line:1 char:1
+ Remove-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\office\1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported
Based on what microsoft documentation says i have to do use -credentials with Invoke command since it is not supprted , but its still not working
any suggestion how i suppose to do it ?

Copy-Item throws AccessDenied exception

I am trying to copy files from a remote server to my base machine using powershell. This throws an 'Access Denied' exception even though the drives get mapped:
New-PSDrive -Name source -PSProvider FileSystem -Root "\\SERVERNAME1\D$\Temp\Folder" ;
New-PSDrive -Name target -PSProvider FileSystem -Root $destinationRemotePath ;
Copy-Item -Path source:\$($file).zip -Destination target: -Verbose -ErrorAction Stop -Force ;
Approach 2
I am mapping the source drive and using PsSession for target drive but I get
Cannot find drive. A drive with the name 'source' does not exist.
+ CategoryInfo : ObjectNotFound: (source:String) [Copy-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
Following is the code being used:
$Username = "UserName";
$Password = ConvertTo-SecureString "Password" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($Username, $Password)
$session = new-pssession -computername 'TargetServerName' -credential $cred
New-PSDrive -Name source -PSProvider FileSystem -Root "\\SERVERNAME1\D$\Temp\Folder" ;
Invoke-Command -Session $session -ScriptBlock { Copy-Item -Path $($args[0]) -Destination $($args[1]) -Verbose -ErrorAction Stop } -ArgumentList source:\$($file).zip,'D:\Folder' ;
There are some issues on that second example:
The PSSession has a different scode, it does not know about your PSDrive.
PSSessions do not support authentication to network location like you might be used to from RDP-Sessions. See CredSSP or ' PSSession double hop'
Approach 1 looks like you have no access to that share you want to use. You can specify credentials via -Credential parameter at New-PSDrive. Can you Get-Childitem on Source: and Target:?

using PsFtp to upload a file to FTP Powershell

I've been wracking my brain on this issue and can't seem to fix it. I'm trying to upload a file to FTP using PSFTP.
The script I'm using:
#------------------------------------------------------
#local variables
$ftp_server = "SERVERNAME"
$ftp_path = "/FTPPATH/PATH"
$local = "C:\ftp\"
$local_in = Join-Path $local "In"
$local_out = Join-Path $local "Out"
$session = "my_ftp_session"
# set up credentials object
$username = "FFandP"
$password = Get-Content "$local_out\Credentials.txt" | ConvertTo-SecureString -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
Set-FTPConnection -Server $ftp_server -Credentials $cred -Session $session -KeepAlive -confirm -UseBinary
Get-ChildItem -Path $local_out |
% {
$ftp_file = "$ftp_path/$($_.Name)" # determine item fullname
Add-FTPItem -Path $ftp_file -LocalPath $_.FullName -Session $session -
}
# -------------------------------------------------
And the error I receive:
Add-FTPItem : Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (550) File
unavailable (e.g., file not found, no access)."
At line:22 char:1
+ Add-FTPItem -Path $ftp_file -LocalPath $_.FullName -Session $session
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Add-FTPItem
I've tried running the Add-FTPitem command by itself, but I get the same error.
I can upload to the FTP using FileZilla. I have also tried removing the variables and using hard-coded paths; I get the same error.
Any ideas?
The answer in #Josh's comment solved it for me. Run Add-FTPItem with the -Overwrite parameter.
Add-FTPItem -Path $remotePath -LocaPath $myPath -Overwrite
It took me a moment to figure out this problem, but here is my solution (I had the same problem).
When using Add-FTPItem the -Path parameter must not include the filename itself.
Add-FTPItem
-Path "ftp://SomeServer/SomeDir/"
-LocalPath "C:\SomeFilename.ext"
-Session $session
So in your example it should be:
Add-FTPItem -Path $ftp_path -LocalPath $_.FullName -Session $session
The filename will be added to the remote FTP path. In case you don't want to have the same name you must either rename the file locally first or remotely after.
Change block
Get-ChildItem -Path $local_out | %{ .... }
to one line
Get-ChildItem -Path $local_out | Add-FTPItem -Path $ftp_path