Access is denied - confusion over COPY-ITEM - powershell

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

Related

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.

add-pnpfile between powershell

I got this inconvenience, im trying to copy a file between sharepoint, I already have the file in a variable but when I tried, it said:
Add-PnPFile : Access denied. You do not have permission to perform this
action or access this resource.
At line:1 char:1
+ Add-PnPFile -Path "http://domain/$cow" -Folder Documents
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (:) [Add-PnPFile],
ServerUnauthorizedAccessException
+ FullyQualifiedErrorId :
EXCEPTION,SharePointPnP.PowerShell.Commands.Files.AddFile
I would like to know how i can open two connection, one to grab the file in that sharepoint and then send to the other one.
this is the code I'm using
Add-PnPFile -Path "http://domain/$cow" -Folder Documents
$cow is variable that contiain my file and Document is where i wanna add the file.
Thank you
you have to connect to the first SharePoint first with:
Connect-PnPOnline –Url https://yoursite.sharepoint.com –Credentials (Get-Credential)
next get the file you want with:
Get-PnPFile -Url Documents/sample.doc -Path c:\temp -FileName sample.doc -AsFile
and finally, after connecting to the second SharePoint, add the file with:
Add-PnPFile -Path c:\temp\sample.doc -Folder "Documents"

Test-Path returns True but ExtractToDirectory Could not find path

I have a simple powershell script which is supposed to ease some deployment tasks.
In an earlier portion of the script, I create a virtual drive mapped to Z: which is on a remote server. The part that is tripping up is when it tries to unzip the files on the remote server mapped to Z:
function UnzipBuild($destinationFolder)
{
Add-Type -assembly "System.IO.Compression.Filesystem"
$zipFiles = Get-ChildItem -Path $destinationFolder -Filter *.zip
foreach($zip in $zipFiles)
{
$folderName = $zip.ToString().TrimEnd(".zip")
$extractPath = Join-Path $destinationFolder $folderName
New-Item -ItemType Directory $extractPath
Write-Host "Extracting $zip to $extractPath `r`n"
[io.compression.zipfile]::ExtractToDirectory([string]$zip.FullName, "$extractPath")
}
}
When it reaches the ::ExtractToDirectory line it throws an exception
Hit Line breakpoint on 'D:\MyDeploymentScript.ps1:85'
[DBG]: PS C:\WINDOWS\system32>>
Exception calling "ExtractToDirectory" with "2" argument(s): "Could not find a part of the path
'Z:\Build_11_17_13_28\Web'."
At D:\MyDeploymentScript.ps1:85 char:9
+ [io.compression.zipfile]::ExtractToDirectory([string]$zip.FullName, "$ex ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DirectoryNotFoundException
But the crazy thing is if I breakpoint that same spot and check the path with Test-Path it returns True. I am at a loss for what can be wrong right now.
[DBG]: PS C:\WINDOWS\system32>> Test-Path Z:\Build_11_17_13_28\Web
True
It seems like you might be mapping your drive in the earlier portion of the script with New-PSDrive. The drive created with that cmdlet is only visible within PowerShell, unless you use the -Persist switch. That switch creates it as an actual mapped drive (as though you had used net use or group policy or mapped it through explorer).
The .ExtractToDirectory method you're calling can't see any of the powershell provider namespaces, so it needs a real mapped drive or UNC path that's visible to the whole operating system.
Remember that if you're using -Persist you may also want to unmap the drive manually now.

Powershell Remove-Item Cmdlet error

I'm using powershell to remove a directory with the command:
Remove-Item $pathAsString -Recurse -Force
However, it gives me the following error:
Remove-Item : Cannot remove the item at 'C:\Path' because it is in use.
At line:1 char:1
+ Remove-Item "C:\Path" -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Remove-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RemoveItemCommand
I thought that was odd, because the directory shouldn't be in use. I can go into file explorer and delete the directory manually. I'm not really sure why this behavior is occurring. I'm fairly new to powershell, so don't understand exactly how it behaves.
My scripts interaction with the program includes:
Creating the folder
Downloading an MSI to the folder
Setting a variable to represent the MSI stored in the folder. Like so:
$MSIVariable = Get-ChildItem $Path | Where {&_.Name -eq "MSIName.msi"}
I'm assuming that something to do with the folder is within a stream of some sort, but don't know how I'd fix this issue.
EDIT:
Here is the code I use involving the folder:
Creating the Folder:
if(!(Test-Path $MSILocation))
{
New-Item $MSILocation -ItemType directory
}
Downloading the MSI:
$webClient = (New-Object System.Net.WebClient)
$downloadLocation = Join-Path $MSILocation $MSIName
$webClient.DownloadFile($downloadURL, $downloadLocation)

Delete broken link

I need to delete all the content of a folder which may include broken links among others. The folder path is provided by a variable. Problem is that PowerShell fails to remove the broken links.
$folderPath = "C:\folder\"
Attempt 1:
Remove-Item -Force -Recurse -Path $folderPath
Fails with error:
Remove-Item : Could not find a part of the path 'C:\folder\brokenLink'.
At line:1 char:1
+ Remove-Item -Force -Recurse -Path $folderPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (C:\folder\brokenLink:String) [Remove-Item], DirectoryNot
FoundException
+ FullyQualifiedErrorId : RemoveItemIOError,Microsoft.PowerShell.Commands.RemoveItemCommand
Attempt 2:
Start-Job { cmd /c rmdir $folderPath }
Fails because $folderPath gets passed as is instead of its value:
Start-Job { cmd /c rmdir $folderPath } | select command
Command
-------
cmd /c rmdir $folderPath
Any suggestion besides using the .NET framework?
EDIT
By broken link I'm referring to a folder which points to a previously mounted partition, that doesn't exist anymore. The folder is still available but when attempting to navigate into it this error occurs because the destination doesn't exist anymore:
Error:
C:\folder\brokenLink refers to a location that is unavailable. It
could be on a hard drive on this computer, or on a network. Check to
make sure that the disk is properly inserted, or that you are
connected to the Internet or your network, and then try again. If it
still cannot be located, the information might have been moved to a
different location.
This will work:
$folderPath = "C:\folderContaingBrokenSymlinks\";
$items = ls $folderPath -Recurse -ea 0;
foreach($item in $items){
if($item.Attributes.ToString().contains("ReparsePoint")){
cmd /c rmdir $item.PSPath.replace("Microsoft.PowerShell.Core\FileSystem::","");
}
else{
rm -Force -Recurse $item;
}
}