How to remove outlook profile remotely using invoke-command? - powershell

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?

Related

Powershell VSCode invoke-command from localhost different user for SCCM

Because VSCode is not able to run a powershell console and debug it as a different user i am trying to get arround it with invoked credentials like this:
Start-Service -Name "WinRM"
$cred = Get-Credential -Credential domain\myuser
Invoke-command -Credential $cred -Computer "localhost" -scriptblock {
Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
Set-Location 'XXX:' # my sccm site code
Import-CMComputerInformation -CollectionName "All Systems" -ComputerName "TestComputer" -MacAddress "00:00:00:00:00:69"
}
If i start it in the debugger of VSCode (F5) it starts but cant connect then to the SCCM Server infrastructure. Could someone help me to solve this issue?
Error:
Cannot find drive. A drive with the name 'XXX' does not exist.
+ CategoryInfo : ObjectNotFound: (XXX:String) [Set-Location], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
+ PSComputerName : localhost
This command cannot be run from the current drive. To run this command you must first connect to a Configuration Manager drive.
+ CategoryInfo : DeviceError: (Microsoft.Confi...ormationCommand:ImportComputerInformationCommand) [Import-CMComputerInformation], InvalidOperationException
+ FullyQualifiedErrorId : CommandCannotExecuteFromCurrentDrive,Microsoft.ConfigurationManagement.Cmdlets.Oob.Commands.ImportComputerInformationCommand
+ PSComputerName : localhost
If i logoff from my machine and login with my admin credentials and execute everything in the invoke-command scriptblock it works.
As i am not allowed to work like this by our company policy's is there maybe a alternative way or something i can do to use the visual studio code debugger?
Have you logged onto the SCCM site server interactively with the credentials you are using and opened the console at least once? I believe this initial first opening is required before the drive is accessible remotely...

Unable to remove a directory on network drive with 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 ( ` ).

Powershell remoting does not have the correct permissions

On the non-domain server SERVER I have a local administrator account USER.
On the domain client machine I am running as a domain user.
Using the following code I attempt to view all services on SERVER
$cred = Get-Credential "SERVER\USER"
Invoke-Command -ComputerName SERVER -ScriptBlock {Get-Service} -Credential $cred
However, I receive the following error
Cannot open Service Control Manager on computer '.'. This operation might require other privileges.
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
Yet, if I RDP to SERVER as USER, I can manually open a Powershell window and run Get-Service without any issues. What's going on?
When remoting cross-domain, the remote command/session will not run with administrative rights. Even though you're connecting as a local admin, the resulting PSSession will not be elevated.
To fix this, you need to set the registry key LocalAccountTokenFilterPolicy located in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System to 1. See Microsoft for more details

PowerShell Double Hop Issue

I’m trying to run a PowerShell script on SYSTEM1, which executes robocopy on SYSTEM2, copying files to SYSTEM3,4,5,etc.
SYSTEM1 and SYSTEM2 are on the same domain, but SYSTEM2 is not behind a firewall (hence the need to run robocopy from SYSTEM2 and not SYSTEM1).
SYSTEM3,4,5 are on different domains than SYSTEM2, as well as different domains than each other.
I set the script up like this (it uses the net use command to prompt the user for credentials for the different domains):
Foreach($server in $servers) {
$command = {
param($cred, $server);
$error.clear();
# Stored credentials in local variables
$user = $cred.GetNetworkCredential().username
$pass = $cred.GetNetworkCredential().password
#establish connection from SYSTEM2-> $server
net use \\$server\c$\Deployments /delete
net use \\$server\c$\Deployments /USER:$user $pass
# Check to see if C:\Deployments exists on server, and if not create it.
if ((Test-Path \\$server\c$\Deployments) -eq $FALSE) {
$c = {
New-Item \\$server\c$\Deployments -type directory
}
$ws = Invoke-Command -ComputerName $server -Credential $cred -ScriptBlock $c
}
# Copy over the deployment packages
$dest = "\\$server\Deployments\$DeploymentDate\$CurrentDirectoryName"
robocopy $CurrentDirectoryPath $dest /W:20 /R:15 /e /XF CopyPackage.ps1
# Delete connection from SYSTEM2 -> $server
net use \\$server\c$\Deployments /delete
However, the net use command returns an error after the credentials are entered:
The network connection could not be found.
+ CategoryInfo : NotSpecified: (The network con...d not be found.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : SYSTEM2
More help is available by typing NET HELPMSG 2250.
System error 55 has occurred.
+ CategoryInfo : NotSpecified: (System error 55 has occurred.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : SYSTEM2
The specified network resource or device is no longer available.
[SYSTEM3] Connecting to remote server failed with the following error message : WinRM cannot process the request. The
following error occured while using Kerberos authentication: There are currently no logon servers available to service
the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or
use HTTPS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more
information, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
+ PSComputerName : SYSTEM2
The network connection could not be found.
+ CategoryInfo : NotSpecified: (The network con...d not be found.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ PSComputerName : SYSTEM2
More help is available by typing NET HELPMSG 2250.
I’ve read this could be a “double-hop” issue (as detailed here), but I’m not sure how to edit the script to use CredSSP instead of Kerberos (or if this is even the problem).
Any ideas?
Posting this solution in case someone is still having an issue with a simple resolution to DoubleHop without using CredSSP.
Try this out:
https://www.powershellgallery.com/packages/Invoke-PSSession
It Invokes a PSSession, then Registers a PSSessionConfiguration with the Credentials that you provided. Basically providing the credentials for that DoubleHop
Then use Invoke-Command with that new PSSession. It should have the required privileges to do what you need.

Access Denied when calling SharePoint Import-SPWeb cmdlet remotely

I am currently trying to import a SharePoint 2013 site into a single server farm via the Import-SPWeb PowerShell cmdlet. It is a pretty straightforward process, except the twist is that I need to do it remotely from another machine by using Invoke-Command. This remote machine calls Invoke-Command and invokes the following script on the SharePoint server, which I called SPOINT13SSS.
Below you will find the content of both the call and the script.
CALL (from remote machine to SPOINT13SSS):
Invoke-Command -ComputerName SPOINT13SSS.sandbox.local -Authentication CredSSP -Credential $spusercreds[0] -ArgumentList "SPOINT13SSS" -FilePath C:\Users\rsmith\Desktop\SPScripts\Framework\Create\Create_SPSite.ps1
SCRIPT:
$spserver = $args[0]
Add-PSSnapin Microsoft.SharePoint.Powershell
Write-Host "[INFO] SP Server is $spserver"
Write-Host "[INFO] Beginning Import of the Site Collection into SharePoint for testing..."
try{Import-SPWeb http://$spserver -Path C:\SP13Install\siteexport.cmp -UpdateVersions Overwrite}
catch{Write-Error "[ERROR] Importing the Site Collection failed. Please make sure that the siteexport.cmp file exists and that you have proper access permissions to both the file and the SharePoint database."}
The issue I'm having - When I run
Import-SPWeb http://$spserver -Path C:\SP13Install\siteexport.cmp -UpdateVersions Overwrite
on SPOINT13SSS, the import works just fine, no flaws.
When I run it remotely, however, I get the following error:
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
+ CategoryInfo : InvalidData: (Microsoft.Share...CmdletImportWeb:SPCmdletImportWeb) [Import-SPWeb], UnauthorizedAccessException
+ FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletImportWeb
+ PSComputerName : SPOINT13SSS.sandbox.local
I have made sure that the user I am authenticating with via CredSSP has the following privileges:
Farm Administrator
Site Collection Administrator
Local Administrator on SPOINT13SSS
I am also 100% sure that the credentials are correct because I have other scripts called via Invoke-Command with this PSCredential and they work fine.
In addition, I have also tried fiddling with the NTFS Permissions on C:\SP13Install\siteexport.cmp (Everyone - Access Full control) and can't seem to get this to work. I also attempted to share the folder. I can access it from the remote machine, read and write to it, but I just can't Invoke this command from the remote machine to SPOINT13SSS.
I solved the issue by assigning the account as the service account for the web application pool where the site collection resides and resetting IIS via iisreset /noforce