Get-ChildItem -path "\\Servername.net\FolderName\SubFolderName\" error with UNC path - powershell

I am using Get-ChildItem with a path to navigate to a common file share.
I was able to navigate to common file share from my local machine without any issues but when I deploy this code into the PROD server, there I am running into Cannot find path issue.
Power Shell Command:
Get-ChildItem "\\servername.net\abcd\"
Error:
Get-ChildItem : Cannot find path '\\servername.net\abcd\' because it does not exist.
At line:2 char:1
+ Get-ChildItem '\\servername.net\abcd\'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\servername.net\abcd\:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Not sure if anyone experienced this issue and how to resolve these environmental issues.
Any help is greatly appreciated.
Power shell error

Based on your screenshot, I believe this to be a limitation of Get-ChildItem accessing UNC Paths while the current location is a SqlServer provider. I see a few options:
Map a PSDrive to the UNC path so that Get-ChildItem has a FileSystem provider to work with directly.
New-PSDrive -Name Z -Root "\\servername.net\abcd" -PSProvider FileSystem
Get-ChildItem Z:
Use a different method to retrieve files and directories.
[System.IO.Directory]::EnumerateFileSystemEntries("\\servername.net\abcd")
Use the location stack to go into a FileSystem. Then return to your previous PSDrive.
Push-Location C:
Get-ChildItem "\\servername.net\abcd"
Pop-Location

After evaluating the environments found that these UNC path issues are happening because of Domain differences.
My laptop and archive file share are residing in the same domain, and that's how archiving script was working without any issues.
Whereas the PROD server where I have deployed the script is residing in a different domain.
Resolved the issue by identifying another PROD server with the same domain name as the archive file share and deployed the script using task schedular.

Related

Edit/Add GPO on DC via Powershell

I'm given the task to migrate all the printers installed on workstations via GPO to another server.
As for now all printers are installed in a local decentralized Distribution Point, we want to move on a centralized Distribution Point/Print Server.
On mine DC, via Group Policy Management Editor, I've a lot of printers in
Computer Configuration\Preferences\Control Panel Settings\Printers
All printers are mapped from \DP00x\Printer and given a local name.
What i want to change is the \DP00x to \CentralDP01\Printer in the GPO.
I've managed via powershell to create all printer ports, install all printers and publish/list in the directory all of them.
Given that they are more than 100, I wish to automate the process to edit the GPO editing, so that i don't need to open each policy and each printer to modify the destination.
I've tried the cmdlet Get-GPRegistryValue because I know (at least) that printers are installed on HKLM\SYSTEM\CurrentControlSet\Control\Print\Printers
but i get this error every time:
Get-GPRegistryValue : The following Group Policy registry setting was not found: "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Printers".
Parameter name: keyPath
At line:1 char:1
+ Get-GPRegistryValue -Guid 6b464ed9-66c8-47fa-8327-1fe9b074a0d7 -Key H...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Microsoft.Group...tryValueCommand:GetGPRegistryValueCommand) [Get-GPRegistryValue], ArgumentException
+ FullyQualifiedErrorId : UnableToRetrievePolicyRegistryItem,Microsoft.GroupPolicy.Commands.GetGPRegistryValueCommand
I tried as well Get-GPPrefRegistryValue
Get-GPPrefRegistryValue -Context Computer -Guid 6b464ed9-66c8-47fa-8327-1fe9b074a0d7 -Key HKLM\SYSTEM\CurrentControlSet\Control\Print\Printers
But error looks the same:
Get-GPPrefRegistryValue : The Preference registry setting "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Printers" was not found in the
"x-x-x-x-x-x" GPO in the x-x-x-x-x-x-x.com domain.
Parameter name: keyPath
At line:1 char:1
+ Get-GPPrefRegistryValue -Context Computer -Guid 6b464ed9-66c8-47fa-83 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Microsoft.Group...tryValueCommand:GetGPPrefRegistryValueCommand) [Get-GPPrefRegistryValue], ArgumentException
+ FullyQualifiedErrorId : UnableToRetrievePreferenceRegistryItem,Microsoft.GroupPolicy.Commands.GetGPPrefRegistryValueCommand
I found a workaround. Backup the GPO, manually edit the XML with the new value and import back the GPO.
I don't fancy the idea of manually editing because it can lead to errors and with over 100+ GPOs I can have alot of errors.
Can anyone help me?
Maybe i'm using the wrong commands, but so far documentations state to use GPO Module.
Unfortunately the GroupPolicy commands are limited to registry key settings only, and printer-preferences fall outside that. You can safely edit the live GPO xml files themselves though (or use Backup-GPO/Restore-GPO).
If you're only replacing the server name, this should work fine. Try it on a test GPO, updating the path as needed:
$guid = (Get-GPO -Name 'Test GPO')
# Check the GPO version before changes:
Get-GPO -guid $guid
$domain = 'domain.com'
$path = "\\$domain\SYSVOL\$domain\Policies\{$guid}\User\Preferences\Printers\Printers.xml"
# Update the path in the GPO xml:
(Get-Content $path -Raw) -replace 'DP00x','CentralDP01' | Set-Content $path
# Validate the GPO version/change date have updated - might take a while if xml is on a different DC:
Get-GPO -guid $guid

How to mount a SMB share to local folder - not only a drive letter - using powershell

Is it possible to mount a SMB share (or any other network share) to a local folder with powershell - apart from using "net use"?
I tried New-SmbMapping and New-PSDrive. But I get errors for both.
This is what I tried with New-SmbMapping
New-SmbMapping -LocalPath E:\MOUNT\pro\ -RemotePath \\host.example\projects
I get the specified device name is invalid and:
+ CategoryInfo : NotSpecified: (MSFT_SmbMapping:ROOT/Microsoft/...MSFT_SmbMapping) [New-SmbMapping], CimException
+ FullyQualifiedErrorId : Windows System Error 1200,New-SmbMapping
And for New-PSDrive, it seems not possible at all.
Thanks for any help!
You cannot use New-SMBMapping to create a mapping to a local folder - only to a drive letter. The "device name is invalid" error refers to the fact that E:\MOUNT\pro is not a valid device letter (it expects a single English letter).
To mount an SMB path into a local folder, you need to create a "junction point" - what Powershell calls SymbolicLink. For example:
New-Item -ItemType SymbolicLink -Path mytest -Target '\\computer\share'
The local path (./mytest in the above example) must not exist as New-Item needs to create it (this is unlike file system mapping in other operating systems).
Your current user must have access to the remote share, otherwise you'd get a non-helpful error message such as New-Item : Cannot find path '\\computer\share' because it does not exist. You can access shares for which you need to provide a user name and password by first loading the credential with net use before running New-Item (I don't know of Powershell way to do net use).

Permission Denied when moving files using PowerShell script

Getting the below error while executing PowerShell script
+ CategoryInfo : PermissionDenied: (\\domain\tm1server.log:FileInfo) [Move-Item], UnauthorizedAccessException
+ FullyQualifiedErrorId : MoveFileInfoItemUnauthorizedAccessError,Microsoft.PowerShell.Commands.MoveItemCommand
You might have to use Copy-Item to move your file to the destination.
The documentation for Move-Item states:
The locations must be supported by the same provider. For example, it can
move a file or subdirectory from one directory to another or move a
registry subkey from one key to another. When you move an item, it is
added to the new location and deleted from its original location.
I had to add the sourcce directory as a PSDrive as well. Because the log in I used to the server didn't have WRITE acccess to the server.
So, I declared the sourcce directory as another PSDrive and used my ADMIN credential for creating it.
After that I was able to use move-item.
The folder specified in -path needs modify in addition to Read permission. Modify and write permission is needed on the -destination folder.

Out-file export to a network location powershell

I am having an issue trying to output a file with PowerShell, I can export the file to the computer's local drives however when I want to export it to a network location it will not let me.
I receive the following error:
Access to the path '\\fmadt-prod-web5\e$\ftproot\customer\temp\SiteLists\Classic\Hosted1.txt' is denied.
+ CategoryInfo : OpenError: (:) [Out-File], UnauthorizedAccessException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutFileCommand
This is the code that I am using:
$list2 | Format-Table -a -Property "WebAppName", "Version", "State"| Out-File '\\fmadt-prod-web5\e$\ftproot\customer\temp\SiteLists\Classic\Hosted1.txt' -force
Is it possible to export to a network location? The user I am using has admin access to that location as well.
You can't use a UNC path, but you can map a PSDrive to that location and use that:
New-PSDrive -Name dest -Root \\fmadt-prod-web5\e$\ftproot\customer\temp\SiteLists\Classic -PSProvider FileSystem
Then:
| out-file dest:\Hosted1.txt
Use the -Credential parameter of New-PSDrive if you need to access the drive using alternate credentials.
you most certainly can output to unc paths, I regularly use those at work. This almost looks like you don't, or the account you are running the script as doesn't, have access to the directory.
E$ refers to the admin share on a server, try actually sharing that directory via windows shares or run the script using an account that is in the administrators group on the relevant server. Also, I always use double quotes for paths because then you can include variables -- force of habit :)

Getting an error code 1 on Set-Acl on a network drive

I have a folder structure with damaged permissions restored on a new NAS (synology). All folders (+1000) contain the same structure with 13 subfolders, each with their specific permissions.
I have an 'example' structure on the same drive and I'm now trying to get/set the acl on the different folders. But every time I try to 'Set-Acl' I'm receiving this kind of error:
Set-Acl : Method failed with unexpected error code 1.
At line:1 char:1
+ Set-Acl -Path ".\1019 Stekene Molenbergstraat" -AclObject $MainAcl
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (N:\WERVEN\WERVE...Molenbergstraat:String) [Set-Acl], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.SetAclCommand
I've tried many different things..
Directly on UNC, mapped as a drive, used combinations of Get-Acl, Set-Acl, GetAccessControl('Access'), SetAccessControl($acl), absolute paths, relative paths,..
$TemplateAcl = Get-Acl ".\{TEMPLATE}"
Set-Acl -Path ".\OTHER" -AclObject $TemplateAcl
# Error..
$TemplateItem = Get-Item ".\{TEMPLATE}";
$TemplateAcl = $TemplateItem.GetAccessControl('Access');
Set-Acl -Path ".\OTHER" -AclObject $TemplateAcl
# Error...
$OtherItem = Get-Item ".\OTHER";
$OtherItem.SetAccessControl($TemplateAcl);
# No error.. but nothing has changed
I have full access to this drive. I can set permissions in windows just fine. Using robocopy, I can copy a structure maintaining it's permissions. In PowerShell... I keep getting this error code 1.
I'm all out of ideas...
Edit 22 nov - part 1
As requested in the comments:
PS N:\WERVEN> $error[0].exception|select *;
Message : Method failed with unexpected error code 1.
Data : {}
InnerException :
TargetSite : Void Persist(System.String, System.Runtime.InteropServices.SafeHandle, System.Security.AccessControl.AccessControlSections, System.Object)
StackTrace : at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object
exceptionContext)
at System.Security.AccessControl.FileSystemSecurity.Persist(String fullPath)
at Microsoft.PowerShell.Commands.FileSystemProvider.SetSecurityDescriptor(String path, ObjectSecurity sd, AccessControlSections sections)
at Microsoft.PowerShell.Commands.FileSystemProvider.SetSecurityDescriptor(String path, ObjectSecurity securityDescriptor)
at System.Management.Automation.SessionStateInternal.SetSecurityDescriptor(CmdletProvider providerInstance, String path, ObjectSecurity
securityDescriptor, CmdletProviderContext context)
HelpLink :
Source : mscorlib
HResult : -2146233079
PS N:\WERVEN> $error[0].exception.innerexception| select *
PS N:\WERVEN>
Edit 22 nov - part 2
There seems to be some 'known' problem with assigning permissions on synology nas's: http://mikebeach.org/2014/12/06/acl-fix-for-synology-diskstations/
Since I was loosing way too much time on this I have fixed my problem by expanding my script using ROBOCOPY to MOVE the folder per folder to a local disc. On this local disc I fix the permissions and /MOVE /SEC /E the folder back to the NAS.
Takes up some more time.. but it works. And I can get some sleep.
I'd say remove the -AclObject parameter name, it does not exist (on PowerShell 5 at least). This works on my computer (I specified absolute paths to test) :
$TemplateAcl = Get-Acl ".\{TEMPLATE}"
Set-Acl ".\OTHER" $TemplateAcl
There doesn't seem to be any quick answer for this. For some reason it's not possible to use Set-Acl on a synology nas.
Anywhere you look you're referred to the tool 'synoacltool'. Absurd!