Unable to remove a directory on network drive with PowerShell - powershell

I have built a script that removes a user from AD, Exchange, Lync etc. At the end of the script it deletes the users profile-folder and home-directory. The thing is, only the user who is being deleted has the Full Control for the profile-folder, so I need to delete the folder with his/hers credentials.
First I tried this:
Remove-Item -Path \\networkdrive\share$\profilefolder -Recurse -Force -Credential $UsersCredentials
but I got the following error:
Remove-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.
Then I tried to do it with the New-PSDrive cmdlet:
New-PSDrive -Name F -PSProvider FileSystem -Root \\networkdrive\share$\profilefolder -Credential $UsersCredentials
I get the following error:
New-PSDrive : Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again
I read somewhere that connecting to the network drive with IP-address might solve the error above, but when I tried that, I got a new error:
New-PSDrive : The specified network password is not correct
Do you have any suggestion as to what I could do? My goal is to use the credentials of the person being deleted to remove the folders. My next step is to download the NetApp PowerShell cmdlets and see if I could get the directories removed with those.
Edit: I decided that I would not to try to remove the folder with other credentials, but instead take the ownership, and delete the folder after that. I tried:
takeown /F \\server\share\folder /A /R /D y
But I got the following error:
SUCCESS: The file (or folder): "\\server\share\folder" now owned by the administrators group.
takeown :
At line:1 char:1
+ takeown /F \server\share\folder /A /R /D y
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
ERROR: The data area passed to a system call is too small.
So it seems I am not able to take the ownership, for some reason. Any suggestions how I could proceed from here?

Remove-Item -Path \networkdrive\share`$\profilefolder -Recurse -Force-Credential $UsersCredentials
Escape the $ in path with a backtick ( ` ).

Related

How to remove outlook profile remotely using invoke-command?

I am trying to create the script which will delete all outlook profiles from a remote machine.
I run the script as an admin. Now, I'm getting the following error:
Cannot find path 'HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\Profiles' because it does not exist.
even though the user can access those profiles in the registry.
Cannot find path 'HKEY_CURRENT_USER\Software\Microsoft\Office\16.0\Outlook\Profiles' because it does not exist.
+ CategoryInfo : ObjectNotFound: (HKEY_CURRENT_US...utlook\Profiles:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
The code is:
Invoke-Command -ComputerName $currentPC -ScriptBlock {remove-item -Path "HKCU:\Software\Microsoft\Office\16.0\Outlook\Profiles"}
I run the script with admin rights, so I have a feeling that the script block cannot identify HKEY_USERS for the current user who is logged on to the remote machine
and somehow points to my registry entries. Perhaps there is a way to access profile registry entries using the user's SID? How can I make this script work?

getting error while copying file to remote location using powershell scripts in gitlab runner

I am setting up a GitLab CI/CD pipeline to copy the war file using PowerShell copy-item function. I am getting below error in the pipeline. the user is already an administrator on the gitlab runner computer.
[servername] Connecting to remote server name failed with the
following error message: Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (servername:String) [], PSRemotingT ransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken ERROR: Job failed: exit status 1
Here is my script in .yml file.
GitLab Runner registered in windows server.
Here is my script in .yml file.
envvariable_username - Environment variable configured in gitlab CI/CD settings page
$envvariable_password - Environment variable configured in gitlab CI/CD settings page
- powershell Invoke-Command -ComputerName computer_name -argumentlist $envvariable_username,$envvariable_password -ScriptBlock {
$password = convertto-securestring -String $envvariable_password -AsPlainText -Force
$mycred = new-object -typename System.Management.Automation.PSCredential $envvariable_username, $password
New-PSDrive -Name "s" -PSProvider FileSystem -root "\\\\computer_name\\share" -Credential $mycred
New-PSDrive -Name "z" -PSProvider FileSystem -root "\\\\computer_name\\backup" -Credential $mycred
Copy-Item -Path "s:\\sample.war" -Destination "z:\\sample.war"
}
expected to copy .war file from one server location to another server location
Looking at your script, you try to execute a script block on a remote server without specifying credentials. That means that either the server has no restrictions or you assume that both servers belong to the same domain, so kerberos will be utilized.
In my experience, when the second is the case, most people forget to evaluate on who's behalf is the script executing. Keep in mind that a process inherits the user context of the parent process unless otherwise specified.
That would mean that the user running your script doesn't have the necessary access to the remote server. You can always evaluate this by first doing this $env:USERDOMAIN + "\" + $env:USERNAME
For example a line in your yaml
- powershell $env:USERDOMAIN + "\" + $env:USERNAME
So when you debug something from a console that you launched with your user, then you don't have 100% replication of the conditions as you are forgetting the most important aspect of any process, that is the logon user.
Then, if this works, I've noticed that from the remote server you are trying to access another remote location. I notice that you are specifying credentials for this part if please do note that if from within a remote session, you try to access any remote resource, then you need to be aware of some caveats. Please read more about them hereand especially the one specific to the double hop.
As a word of advice, best way to troubleshoot scripts that utilize remote execution, is to logon on the server with the same user as with the services that runs your scripts, thus replication the conditions 100%. It is also possible to launch only the console with the credentials of another user.

How to use Powershell to grant Windows application or executable to use your network profile?

Powershell newbie here. I am learning Powershell (yes, I have been ignoring it all these years) as I have never needed this one particular need of mine. I have looked at PS tutorial sites and, of course, StackOverflow for any tips. Seems like my need is unique.
Short story, how do you execute an application (for example, notepad.exe) on a local machine to open a network shared file but the local machine has a generic logged-on user but the network share requires a privileged user (like mine) to open the file. I want the app/executable to inherit my credentials but not set the local machine itself. I want to run a local app/executable as if I logged on to the local machine with my credentials.
I have read PS can do this exact thing so I have been experimenting with Powershell command line:
start-process "[SOME APP].exe" -FilePath "\DIRECTORY\PATH\WHERE\APP\IS\LOCATED]" -Credential (Get-Credential -Credential "DOMAIN\USERID")
I get an error prompt from the Powershell command line:
start-process : This command cannot be run due to the error: The
system cannot find the file specified. At line:1 char:1
+ start-process "[SOME APP].exe" -FilePath "[\DIRECTORY\PATH\WHERE\APP\IS\LOCATED] ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
I plan on using this Powershell script in my LabVIEW executable to assign the VI (virtual instrument) executable my own network login privilege to transfer files to/fro or modify a text file that resides in the network share.
Thanks for your help guys!
You could do something like the following. All you need to do is change the $app variable to the executable you want and save the script as a PS1 file. Someone can run it by right-clicking and selecting Run with PowerShell or opening a PowerShell console and typing in path\scriptname.ps1.
$App = "c:\windows\system32\notepad.exe"
$Credentials = Get-Credential
$WorkingDir = Split-Path $app
$Exe = Split-Path $app -Leaf
Start-Process -FilePath $Exe -WorkingDirectory $WorkingDir -credential $Credentials

Can't create Remote App via Powershell that points to an Excel workbook

I am using Windows Server 2008 R2.
I'm trying to use Powershell to create a new Remote App that points to an Excel workbook. The following script fails on the New-Item call:
PS C:> Import-Module RemoteDesktopServices
PS C:> cd RDS:
PS RDS:\RemoteApp> New-Item -Path RDS:\RemoteApp\RemoteAppPrograms -Name "ATM999" -Appli
9\ATM999_Cube.xlsx"
New-Item : An unknown error has occurred.
At line:1 char:9
+ New-Item <<<< -Path RDS:\RemoteApp\RemoteAppPrograms -Name "ATM999" -ApplicationPath
ube.xlsx"
+ CategoryInfo : NotSpecified: (RDS:\RemoteApp\RemoteAppPrograms\ATM999:Stri
+ FullyQualifiedErrorId : UnknownError,Microsoft.PowerShell.Commands.NewItemCommand
As a test, I attempted to create a new item that points to an executable rather than an Excel workbook. That works. Is there a parameter or something that I'm missing that would let me create a Remote App against an Excel workbook?
Figured it out. Here's what I did:
Import-Module RemoteDesktopServices
cd RDS:
New-Item –Path RDS:\RemoteApp\RemoteAppPrograms –Name Workbook.xlsx –ApplicationPath "C:\Program Files\Microsoft Office\Office14\Excel.exe" –CommandLineSetting 2 -RequiredCommandLine "E:\ProcessingFolder\ClientName_Cube.xlsx"
This creates an entry that points to Excel but specifies the path to the workbook in the RequiredCommandLine parameter. The "2" setting for CommandLineSetting forces the Remote App to always use the supplied RequiredCommandLine parameter.

Cannot Copy a file from a network share in powershell until I open the share in windows explorer

I have a very simple powershell script which to copy files from a networked server.
here's the script
Write-Output "Copying Backups"
copy \\sqlbox\SqlBackups\Client.bak c:\sqlbackups
It throws this exception
Invalid Path: '\\sqlbox\SqlBackups\Client.bak'.
At C:\Work\db\restore.ps1:5 char:1
+ copy \\sqlbox\SqlBackups\Client.bak c:\sqlbackups
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], ArgumentException
+ FullyQualifiedErrorId : CopyItemDynamicParametersProviderException
If I open a windows explorer up and goto \sqlbox\SqlBackups it opens fine and if I then run the powershel script it also starts working and will work until the next time I reboot the PC.
How can I address this in the script?
Try mapping the drive first, then carry out the copy operation.
New-PSDrive -Name S -Root \\sqlbox\SqlBackups\ -PSProvider FileSystem
Write-Output "Copying Backups"
copy S:\Client.bak c:\sqlbackups
I have a similar problem when copying files over servers with this error:
Cannot find path '\\computer1\d$\path' because it does not exist.
It works after adding Microsoft.PowerShell.Core\FileSystem:: in front of file name:
copy-item "Microsoft.PowerShell.Core\FileSystem::\\computer1\d$\path\installer.msi" "Microsoft.PowerShell.Core\FileSystem::\\computer2\d$\path\installer.msi"