Copy files with elevated credentials in PowerShell - powershell

Searched and searched, but cannot find an answer that works specifically for what I am looking for.
I want to call a PowerShell script from a logon vbscript that runs on logon. The PowerShell script will copy a file from a server network share to C:\Windows, but I need to embed credentials securely in the PowerShell script because the script will be hosted on a common share. I have already generated the AES key file and the password file I am decrypting with the AES key.
This is what I have so far
$User = "itadmin"
$source = "\\server\cip$\misc-programs\new_inb_install\inb.exe"
$destination = "C:\Windows\"
$PasswordFile = "\\server\cip$\misc-programs\new_inb_install\psw.txt"
$KeyFile = "\\server\cip$\misc-programs\new_inb_install\AES.key"
$key = Get-Content $KeyFile
$MyCredential = New-Object -TypeName System.Management.Automation.PSCredential `
-ArgumentList $User, (Get-Content $PasswordFile | ConvertTo-SecureString -key $key)
Copy-Item $source -Destination $destination -Recurse -Credential $MyCredential
The error I get when I run the code is
> Copy-Item : Cannot retrieve the dynamic parameters for the cmdlet. The FileSystem provider supports credentials only on the New-PSDrive
> cmdlet. Perform the operation again without
> specifying credentials.
> At line:12 char:1
> + Copy-Item $source -Destination $destination -Recurse -Credential $MyC ...
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidArgument: (:) [Copy-Item], ParentContainsErrorRecordException
> + FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.CopyItemCommand
I should also mention, the credentials I am specifying I don't need for access to the server. I need to use those credentials to deal with UAC and make sure the end user isn't prompted for the service account creds.
Any help would be greatly appreciated!

Related

WriteErrorException - invoke-command

I'm working on a script to execute a .ps1 file remotely on multiple server for testing reasons im only executing it on one server. Here is the code:
#Citrix Optimizer Automation
$computer= Get-ADComputer -LDAPFilter "(name=*XXXXXXXXXXX*)" -SearchBase "OU=Test-Server,OU=CVAD1912,OU=Server,DC=domain,DC=tld"
$computername=$computer.name
foreach ($server in $computername){
$dir = "\\$server\c$\Temp\CitrixOptimizer"
#Remove Citrix Optimizer if exists
Remove-Item $dir -Recurse
#Copy the item from the filesystem to the server
Copy-Item -Path \\fs01\install$\Citrix\CitrixOptimizer -Destination $dir -Recurse
Invoke-Command -ComputerName $server -ScriptBlock{
#Execute the CitrixOptimizer
Set-Location "c:\temp\CitrixOptimizer"
.\CtxOptimizerEngine.ps1 -OutputLogFolder "\\fs01\install$\Citrix\01_OptimizerLogs\$([DateTime]::Now.ToString('yyyy-MM-dd'))_$server" -Mode Analyze
}
#Remove Citrix Optimizer
Remove-Item $dir -Recurse
}
Anyways I always get this Error:
Access Denied
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,CtxOptimizerEngine.ps1
+ PSComputerName : XXXXXXXXXXXXX
The Problem is that it can't write the Logs to my Networkpath. This is the only problem. It is working if i give the -OutputLogFolder a local path.
I tried to send the invoke-command with credentials but this was also not working same with the Parameter -RunAsAdministrator. I know that this is a double-hop problem but i don't know how to solve it. PS: Every User in the Group Domain-Admins must be able to execute this file so just giving creds for one users is not enough.
I would be grateful for help!
Best, cosmo_

how to delete a folder using invoke command in powershell

First time asking a question here after using it for a long time.
I'm currently making a powershell script to delete userdata when they left the company for a month.
I already tried deleting the folder using the normal remove-item and this works however this is a very slow process when going over the network.
I then found out about the invoke-command function which can run on a remote computer.
Now i can't seem to get this working.
I keep getting the error that the path is not found.
However it seems like powershell is changing my path.
How can i prevent this from happening?
Cannot find path 'C:\Users\admcia\Documents\P$\PERSONAL\JOBA' because it does not exist.
+ CategoryInfo : ObjectNotFound: (C:\Users\admcia...$\PERSONAL\JOBA:String) [Remove-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
+ PSComputerName : ODNDATA
my code is the following:
Note that P$ is the local drive letter on the server.
Also note That $item.SamAccountName is used for creating foldername. (we use Samaccountname as the name of the users folder.
$localPath1 = "P$" + "\PERSONAL\" + $item.SamAccountName
$serverName = "Remotecompter"
Invoke-Command -ComputerName $serverName -ScriptBlock { Remove-Item $using:localPath1 -Force -Recurse -Confirm:$false }
If as seen from your local machine, the drive is \\Remotecomputer\P$\, then for the remote computer (where the code is executed) the path is just P:\.
To combine strings into a path, I would suggest you better use the Join-Path cmdlet rather than concatenating the strings with '+'
Try
$localPath1 = Join-Path -Path 'P:\PERSONAL' -ChildPath $item.SamAccountName
$serverName = "Remotecompter"
Invoke-Command -ComputerName $serverName -ScriptBlock { Remove-Item $using:localPath1 -Force -Recurse -Confirm:$false }
You can use -ArgumentList in Invoke command,
Invoke-Command -ComputerName $serverName -ScriptBlock {
param($localPath1)
Remove-Item $localPath1 -Force -Recurse -Confirm:$false
} -ArgumentList($localPath1)
make sure your path is correct, and if it does not work try to hardcode the path in your code.

Replicating file to remote server, Issue while joining path of local and remote server copying files in powershell

enter code hereI am facing issue while replicating files to remote server, joining the path failing somehow.
Below is code:
Invoke-Command -ComputerName $RemoteServer -ScriptBlock {param($DestinationDir,$LocalCertResultObj,$RemoteCertResultObj,$SourceDir) Compare-Object $LocalCertResultObj $RemoteCertResultObj -Property Name, Length, FullName | Where-Object {$_.SideIndicator -eq "<="} | ForEach-Object {
{$DestinationDir = Join-Path $DestinationDir $_.FullName.Substring($SourceDir.length)}
Write-Output $DestinationDir
Write-Output $SourceDir
Copy-Item -Path "$SourceDir\$($_.name)" -Destination "$DestinationDir" -Recurse -Force
} } -ArgumentList $DestinationDir,$LocalCertResultObj,$RemoteCertResultObj,$SourceDir -Credential $RemoteMachine_cred
Getting error like below:
$DestinationDir = Join-Path $DestinationDir $_.FullName.Substring($SourceDir.length)
C:\TestFolderR
C:\TestFolder
Cannot find path 'C:\TestFolder\file1.txt' because it does not exist.
+ CategoryInfo : ObjectNotFound: (C:\TestFolder\file1.txt:String) [Copy-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
Joining the path looks to be working fine. Copy-Item's error is pretty clear that it can't find C:\TestFolder\file1.txt. Since you're presumably trying to copy this file to the remote server, your ScriptBlock used with Invoke-Command is going to run that entire ScriptBlock on the remote system. It's not going to be able to copy that file over the PowerShell session because it's not aware of your local filesystem - at least, not by using Invoke-Command.
You can establish a New-PSSession to the remote system, and use this with Copy-Item directly from your local session to the remote filesystem:
$Session = New-PSSession -ComputerName server.domain.tld -Credential $RemoteMachine_Cred
Copy-Item -ToSession $Session -Path $localPath-Destination $remotePath
You can even copy an item from the remote filesystem back to your local system, too. Using the same $Session we established above:
Copy-Item -FromSession $Session -Path $remotePath -Destination $localPath

Powershell copy from linux samba to local windows server folder

I need to copy a file from a Linux samba server to various Windows Server 2008.
The shared folder has a specific login and is read-only.
I can access and copy the shared file using Windows Explorer without a problem.
But, when using PowerShell to copy the file, it always give an error as shown below.
I have tried using Copy-item, robocopy and bitstransfer but they all give an error.
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
echo $downloadSource
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix"
this method gives me the following error
Copy-Item : Access denied
CategoryInfo : PermissionDenied: (\domain.or.ip\sharedfolder\file.zip:String) [Copy-Item], UnauthorizedAc
cessException
FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
...
Copy-Item: path not found...
So, I tried adding a credential parameter
$credencial = New-PSSession -ComputerName "serverhostname" -Credential "serverhostname\sharedfolder"
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix" -ToSession $credencial
But received this error after typing my password:
"New-PSSession : [pxl0mon00013] Fail to connect to remote server >serverhostname ...
WinRM cannot process the request... error 0x80090311 ...
CategoryInfo : OpenError (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
FullyQualifiedErrorId : AuthenticationFailed,PSSessionOpenFailed
Then, I decided to give BitsTransfer a shot.
Import-Module bitstransfer
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
Start-BitsTransfer -DisplayName DownloadName `
-TransferType Download `
-Source $downloadSource `
-Destination .\$arq
And it also gave me an error:
Start-BitsTransfer : path not found
'\domain.or.ip\sharedfolder\file.zip' does not exist.
CategoryInfo : ObjectNotFound: (\domain.or.ip\sharedfolder\file.zip:String) [Start-BitsTransfer], ParentC
ontainsErrorRecordException
FullyQualifiedErrorId : PathNotFound,Microsoft.BackgroundIntelligentTransfer.Management.NewBitsTransferCommand
How can I make this file copy, please?
EDIT - 20190403
I tried the following:
get-childitem \\domain.or.ip\sharedfolder\
which resulted in:
Get-ChildItem : Cannot find path '\\domain.or.ip\sharedfolder\' because it does not exist.
At line:1 char:3
+ ls <<<< \\domain.or.ip\sharedfolder\
+ CategoryInfo : ObjectNotFound: (\domain.or.ip\sharedfolder\:String) [Get-ChildItem], ItemNotFo
undException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
So, I opened Explorer and pasted \domain.or.ip\sharedfolder\ at the address bar. It asked me for username and password, then, the file was available.
After that, I returned to PowerShell and tried once again the same Get-ChildItem cmdlet. Then, I was able to list the shared folder contents as expected.
Directory: \\domain.or.ip\sharedfolder
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 01/04/2019 10:06 3896455 file.zip
Finally, I tried:
Copy-Item -Path \\domain.or.ip\sharedfolder\file.zip -Destination ".\file.zip"
And it was copied successfully.
Well, only after I entered my login information in Explorer that PowerShell was able to find the shared folder.
But I need it to copy without having to open explorer.
You can provide alternate credentials with Invoke-Command:
Invoke-Command -ScriptBlock {
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder\$arq"
echo $downloadSource
Copy-Item -Path "$downloadSource" -Destination ".\$arqAgenteZabbix"
} -Credential $Cred
I finally managed to successfully copy the shared file in a relative simple way. I used "NET USE" command to open a session and copy the file, like shown below.
$arq = "file.zip"
$downloadSource = "\\domain.or.ip\sharedfolder"
net use $downloadSource /persistent:no /user:[user] [pass]
Copy-Item -Path "$downloadSource\$arq" -Destination ".\$arq"
net use $downloadSource /delete
Now, a new challenge... encrypt the clear-text password.

Access is denied - confusion over COPY-ITEM

I am trying to copy some files from my server to a workstation. If I change $Foldername to C:\the process works fine. However if I leave the code the way it is, i.e. If I decide to copy files to C:\Program Files\Interrogator.
I get this error:
Copy-Item : Access to the path 'C:\Program Files\Interrogator\Setup Instructions.txt' is denied.
At C:\Users\coduy\Desktop\Copy2Test.ps1:20 char:10
+ Copy-Item <<<< -Path \\10.10.0.10\DeploymentShare\Applications\JDE-Interrogator\* -Destination $Foldername
+ CategoryInfo : PermissionDenied: (\\10.10.0.10\De...nstructions.txt:FileInfo) [Copy-Item], Unauthorized
AccessException
+ FullyQualifiedErrorId : CopyFileInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
I can see that the access is denied but why? I have not shared any of the folders and that should not make any difference if I decide to copy to C:\ or C:\Program Files
$net = New-Object -comobject Wscript.Network
$net.MapNetworkDrive("Z:","\\10.13.0.10\DeploymentShare\Applications\JDE Interrogator",0,"mydomain\coduy","P0kroy$")
$uncServer = "\\10.10.0.10\"
$uncFullPath = "\\10.13.0.10\DeploymentShare\Applications\JDE Interrogator"
$username = "coduy"
$password = "password"
$Foldername="C:\Program Files\Interrogator"
net use $uncServer $password /USER:$username
try
{
mkdir C:\'Program Files'\Interrogator
Copy-Item -Path \\10.10.0.10\DeploymentShare\Applications\JDE-Interrogator\* -Destination $Foldername
}
finally {
net use $uncServer /delete
}
Found out that other user has similar issue and this seems to be a reasonable answer:
Windows Vista and above default to not allowing non-administrative
users to write to the `%PROGRAMFILES% folder. This means that you're
not going to be allowed to copy the files there; you're also not going
to be able to save them after doing your find/replace operation.
You can write them to your user documents folder
(%USERPROFILE%\Documents) folder instead, if that will work for you.
share|edit answered Dec 23 '12 at 6:32
Ken White
74.5k770140