Rename folder in active directory with powershell - powershell

I am writing a powershell script to change the User home folder name to some "NewName" but it is not working for me. Here is my code:
$NewHomeDirectory = "\\SRV10177\users001$\newusername"
Get-ADuser -Identity $OldUserName | Set-ADUser -HomeDirectory $NewHomeDirectory
Later I also tried this code:
Rename-Item -path \\SRV10177\users001$\Oldusername -newName \\SRV10177\users001$\Newusername
But the folder name still not changed.
Would be great if someone can tell me what am I doing wrong in this case?
EDIT
After outputting the rename-item command I got this:
Rename-Item : Access to the path '\\SRV10177\Users000$\newusername' is denied.
At C:\folder_rename\folder_rename_action.ps1:202 char:9
+ Rename-Item -path $OldHomeDirectory -newName $NewHomeDirector ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (\\SRV10177\Users000$\newusername:Str
ing) [Rename-Item], IOException
+ FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.
RenameItemCommand
EDIT.2
Ok, so it was related to the permissions that require to make changes. After having it everything worked as it suppose to.

Couple of observations:
1) Your error is showing for \SRV10177 while you have mentioned the path as \srv1011
2) It is stating clearly that you do not have the permission to access the path or the path is invalid so it is not able to access that.
Lets consider you have a valid path which you can always check using Test-Path, then you should try running the powershell as administrator.
Second, try giving a different share path and see if at all its a permission issue. may be you do not have the right to access/modify that.
Hope it helps.

Related

Rename-Item is not working

I have a share on a folder at path \\Srv1011\User0$ (Active Directory) and I want to rename it with another name \\Srv1011\User1$ but it is not working for me.
Code is:
Rename-Item -Path \\Srv1011\User0$ -NewName \\Srv1011\User1$
Right now the share is enable on the folder and if I execute the above command I get this error:
Rename-Item : Object reference not set to an instance of an object.
At line:1 char:1
+ Rename-Item -Path \\srv13577\User0$ -NewName \\srv13577\User1$
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Rename-Item], NullReferenceException
+ FullyQualifiedErrorId : System.NullReferenceException,Microsoft.PowerShell.Commands.RenameItemCommand
But If I remove the share from folder I get the following error:
Rename-Item : Cannot rename because item at '\\srv13577\User0$' does not exist.
At line:1 char:1
+ Rename-Item -Path \\srv13577\User0$ -NewName \\srv13577\User1$
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Right now I am not sure how to rename such folder. My original work is to drop the share, rename the folder and create the share back.
But for now I am stuck with renaming.
To explain your misconception:
What you are trying to achieve is renaming an smb share, (Look at your path, which starts with \\). Rename-Item is not able to rename shares this way.
You probably want to rename the folder, which is shared under User0$ on the server, or you want to chamge the share's name. These are two different actions.
When you unshare your folder and try to rename it again, it can't be found, because - yeah - the share under \\srv13577\User0$ is not there anymore. That's why your 2nd error came up.
There is no way to rename a share folder using rename-item cmdlet.
Rather I would suggest you to take the content of the share folder,
then create a new share folder with your new name
then move the content from the old one to new one
and finally delete the source share folder.
That will ease out your work.

Copy-Item PowerShell silently continues when source is a network share that does not exist

I'm seeing a strange behavior with the "Copy-Item" cmdlet. It looks like the cmdlet errors out if the source location is a local location that does not exist, but completely ignores that if the source is a network location that does not exist.
For e.g.
Copy-Item \\server\share\thisdoesnotexist\* -Destination c:\temp -ErrorAction Stop
This command doesn't show any errors even if the source share is invalid. However,
Copy-Item c:\thisdoesnotexist\* -Destination c:\temp -ErrorAction Stop
throws an error that looks like:
Copy-Item : Cannot find path 'C:\thisdoesnotexist' because it does not exist.
At line:1 char:1
+ Copy-Item c:\thisdoesnotexist\* -Destination c:\temp -ErrorAction Stop;
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\thisdoesnotexist:String) [Copy-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
What's going on here? I checked TechNet but couldn't see anything there that talked about this. My question is:
Is this expected?
Is there a way to make the cmdlet fail when source network share is invalid as well?
Thanks for any pointers!

Misbehaving Get-ChildItem Operation in PowerShell

There is a back-end SQL DB contains "managed folders" in the form of UNC paths. Using SQL queries in PowerShell I have a loop that will work it's way through these folders and run a GCI operation against them to work out how much disk space they are using.
$managedFolder = "\\server\share\folder\subfolder"
For the sake of the question, $managedFolder is declared as above. The failing command below:
$diskTrendsInitialUsage = "{0:N2}" -f ((Get-ChildItem $managedFolder -Recurse -Force | Measure-Object -Property Length -Sum).Sum / 1GB)
Now if I were to run this command manually in PS console it's fine, it pulls back data. But as soon as it's packaged in a script, it fails with the below error. The folder is accessible from the server, as it works fine from a local PS console session.
ERROR: Get-ChildItem : Invalid Path: '\\server\share\folder\subfolder'.
AddManagedFolder.psf (17): ERROR: At Line: 17 char: 42
ERROR: + $diskTrendsInitialUsage = "{0:N2}" -f ((Get-ChildItem $managedFolder -Recurse ...
ERROR: + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ERROR: + CategoryInfo : NotSpecified: (:) [Get-ChildItem], ArgumentException
ERROR: + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.GetChildItemCommand
ERROR:
I'm stumped.
The problem with your path is that it does not have any indication about which provider to use, so PowerShell just use current one. And if current provider is not a file system provider, then it will fail. So you need to specify provider in path, to allow PowerShell to choose right one regardless of current provider:
$managedFolder = "filesystem::\\server\share\folder\subfolder"
My guess is your are using the SQL PS cmdlets prior to running GCI, this is changing your provider path to SQL: which is what is causing GCI to be unhappy.
Prior to running GCI do cd c:\ to change the path back to the file system and GCI will work.

How to pipe a directory name into Remove-Item?

I'm not very savvy with powershell, so any help is appreciated.
I have a drive that holds users profiles. I need to remove a specific file from each user's profile. It's structured something like this. (Names changed to protect the innocent.)
E:\Profiles
UserID
Documents
OtherFolders
DirectoryToDeleteFrom
FileToDelete.txt
UserID2
...
...
I could use the following command to delete all of the files I need to get to, but it's unbearably slow as it's recursing through all of the other folders under UserID.
#this one would work perfectly, but is terribly slow
Get-ChildItem -Path E:\Profiles -Include FileToDelete.txt -Recurse
I know exactly where each file resides, so I thought that I could do this.
(Get-ChildItem -Path 'E:\Profiles' -Exclude *.lnk)|ForEach-Object{Remove-item -path 'E:\Profiles\' + $_.Name + '\Path\To\File\FileToDelete.txt'}
But I get the following error message:
Remove-Item : A positional parameter cannot be found that accepts
argument '+'. At line:1 char:70
+ (Get-ChildItem -Path 'E:\Profiles' -Exclude *.lnk)|ForEach-Object{Remove-item ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Remove-Item], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
I thought it was because I was passing Remove-Item a bad file path, but the following command generates the correct paths.
(Get-ChildItem -Path 'E:\Profiles' -Exclude *.lnk)|ForEach-Object{'E:\Profiles\' + $_.Name + '\Path\To\File\FileToDelete.txt'}
So what am I doing wrong here?
If you construct a string on the fly to be used inline, by another command, then put brackets around the path:
..{Remove-item -path ('E:\Profiles\' + $_.Name + '\Path\To\File\FileToDelete.txt')}

I need help understanding PowerShell security and file access issues

I'm working with PowerShell, running a script (from my console) that includes this line:
$inpath = "C:\users\xxxxx\path\foo\bar"
and I keep getting this error:
Get-Content : Access to the path 'C:\users\xxxxx\path\foo\bar' is denied.
At C:\users\xxxxx\path\foo\testscript.ps1:53 char:12
+ Get-Content <<<< $txtfile | Get-WordCount -Exclude (Get-Content c:\temp\exclude.txt) | select -First 15
+ CategoryInfo : PermissionDenied: (C:\users\xxxxx\path\foo\bar:String) [Get-Content], UnauthorizedAcc
essException
+ FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand
The scripts and target files are all located on my local drive. I can access the files in Explorer, view/edit/save them using NotePad, and do not have any permissions restrictions set. When I'm on the command line, I can run the get-content cmdlet successfully on files in my path. I can change directories PS C:> cd C:\users\xxxxx\path\foo\bar and successfully list what's there. Even more interesting, I can duplicate the line that's erroring in the script, and NOT receive an error on the command line.
PS C:\users\xxxxx\path\foo> $inpath = "C:\users\xxxxx\path\foo\bar"
PS C:\users\xxxxx\path\foo>
This makes me suspect that the 'Permission Denied' error is actually something else, or something vague enough that I've got no clue how to proceed with troubleshooting. Is it possible for PS to have different permissions than the user under which it's running? Has anyone seen this behavior before, and how did you solve the problem? I'm sure there's a simple solution that I don't know.
Get-Content : Access to the path 'C:\users\xxxxx\path\foo\bar' is denied.
At C:\users\xxxxx\path\foo\testscript.ps1:53 char:12
That path doesn't look like it is a file but a folder.
Are you sure you are appending the file name to the folder and passing that to Get-Content?
Windows gives Access Denied when you try and open a directory as if it were a file without passing extra flags; and .NET does not pass those flags (there are a few specific circumstances for opening a folder, but they do not apply here).
Get-Content read contents of file not folder. Please add . after your your folder path like below.
Get-Content "D:\Logs\*.*" | ?{($_|Select-String "test")}
If you want to go through all folders way under it then add -recurse like below:
Get-Content "D:\Logs\*.*" -Recurse | ?{($_|Select-String "test")}
Instead of this: (as per your comment)
foreach ($doc in $inpath) { do-function }
try this:
foreach ($doc in (gci $inpath)) { do-function }
You are doing a foreach on a string object instead of your folder items.