Set folder permissions with PowerShell in different cultures - windows

I am trying to create a PowerShell script that grants folder permissions to NETWORK SERVICE on different cultures. The main problem is that the NETWORK SERVICE, while present in all installations of Windows, has different names in different cultures, and I don't know how to handle this.
Here is the script I'm using:
$appPath = "C:\SomeFolder"
$Acl = (Get-Item $appPath).GetAccessControl('Access')
$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("NETWORK SERVICE", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")
$Acl.SetAccessRule($Ar)
Set-Acl $appPath $Acl
Now this script works just fine on English versions of Windows. However, when trying to run it on a German version of Windows, I get the following error message (translated from German):
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity
references could not be translated."
At C:\Experimental Files\GrantFolderPermissions.ps1:7 char:1
+ $Acl.SetAccessRule($Ar)
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
How can I best handle this so this script will work culture independently?

Use the well-known SID to determine the account name:
$sid = [Security.Principal.SecurityIdentifier]'S-1-5-20'
$acct = $sid.Translate([Security.Principal.NTAccount]).Value
$ace = New-Object Security.AccessControl.FileSystemAccessRule($acct, 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow')

Related

Set-Acl : Attempted to perform an unauthorized operation while using Addaudit Rule

I am trying to run Powershell script to set Audit Rule on C:\Windows\security folder on my Windows 2008 box.
Below is the script:
$FileDirList = ("C:\Windows\security")
$AccountName = New-Object System.Security.Principal.NTAccount("Everyone")
$FileSystemRight = [System.Security.AccessControl.FileSystemRights]::FullControl
$AuditFlag = [System.Security.AccessControl.AuditFlags]::Failure
$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]::None
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None
#
#write-OSPBOSbuildLog "Applying Audit Setting"
#
foreach ($FileDirName in $FileDirList) {
#write-OSPBOSbuildLog ">>>>> Appying audit setting to $FileDirName"
$AuditRule = New-Object System.Security.AccessControl.FileSystemAuditRule $AccountName, $FileSystemRight, $InheritanceFlag, $PropagationFlag, $AuditFlag
$objACL = Get-ACL $FileDirname
$objACL.AddAuditRule($AuditRule)
Set-ACL $FileDirname $objACL
}
But I am getting error as shown below:
Set-Acl : Attempted to perform an unauthorized operation.
At C:\IBM\File-Perm.ps1:22 char:12
+ Set-ACL <<<< $FileDirname $objACL
+ CategoryInfo : PermissionDenied: (C:\Windows:String) [Set-Acl], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetAclCommand
Please help me understand what changes I need to do?
Thanks in Advance!!

Pulling OEM Key and activating

I work as a Microsoft partner for their loaning and seeding process for Surface Pro 3's and 4's. We re-image hundreds of devices a day and are having a problem with digital entitlement. I need a way to pull the OEM key from the device and force activation with that key. I am trying to accomplish this through a powershell script:
$computer = gc env:computername
$key = (Get-WmiObject -query ‘select * from SoftwareLicensingService’).OA3xOriginalProductKey | Out-String
$service = get-wmiObject -query “select * from SoftwareLicensingService” -computername $computer
$service.InstallProductKey($key)
$service.RefreshLicenseStatus()
I am getting the error :
Exception calling "InstallProductKey" : ""
At line:7 char:1
+ $service.InstallProductKey((Get-WmiObject -query ‘select * from Softw ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
any help would be appreciated, either with fixing this error or if there is an easier way to accomplish what I am doing. Thanks!
EDIT: Added exception trap, new error
Cannot convert the "System.Runtime.InteropServices.COMException (0xC004F025)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementObject.InvokeMethod(String methodName, ManagementBaseObject inParameters,
InvokeMethodOptions options)
at System.Management.Automation.ManagementObjectAdapter.InvokeManagementMethod(ManagementObject obj, String
methodName, ManagementBaseObject inParams)" value of type "System.Management.Automation.ErrorRecord" to type
"System.Management.ManagementException".
At line:3 char:1
+ [System.Management.ManagementException] $_
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ConvertToFinalInvalidCastException
Try Adding .Trim() to the end of $key
I had a similar issue with my code below, which threw the same error
Exception calling "InstallProductKey" : ""
It turned out the $key was returning the key string + a few blank spaces after it. Credits to #elexis for picking it up. Couldn't find a solution anywhere for this.
$computer = gc env:computername
$key = (wmic path softwarelicensingservice get oa3xoriginalproductkey)[2].Trim() #<--The Trim is to remove the white space aftewards which causes an error
Write-Output $key
$service = get-wmiObject -query "select * from SoftwareLicensingService" -computername $computer
$service.InstallProductKey($key)
$service.RefreshLicenseStatus()

Powershell script works but also gives an error message

The error is as follows:
You cannot call a method on a null-valued expression.
At C:\Across.ps1:6 char:21
+ $result.Handle.Close <<<< ()
+ CategoryInfo : InvalidOperation: (Close:String) [],
RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The script is as follows:
# Load ntuser.dat
reg load HKU\Across C:\users\Default\NTUSER.DAT
# Create a new key, close the handle, and trigger garbage collection
$result = New-Item -Path
'Registry::HKEY_USERS\Across\Software\AcrossStuff'
$result.Handle.Close()
[gc]::Collect()
#Unload ntuser.dat
reg unload HKU\Across
Can you please help me fix this.
Thanks!
Your $result seems to be null, check the place where it is assigned and ensure that this is not null
It is either your script is not properly lined up or path does not exist. You have to check this.
$result = New-Item -Path 'Registry::HKEY_USERS\Across\Software\AcrossStuff'

How to enter text into an input field through Power Shell?

Here is a PowerShell script to trigger Internet Explorer, open LinkedIn login page and enter some text in the username text field.
$ie = New-Object -Com "InternetExplorer.Application"
$ie.Navigate("www.linkedIn.com")
$ie.Visible = $true
$doc = $ie.document
$usernameElement = $doc.getElementByTagName("input") | Where-Object {$_.id = "session_key-login""}
$usernameElement.Click()
Get-Process iexplore | Foreach-Object {$_.CloseMainWindow()}
Unfortunately, I keep getting the following error:
You cannot call a method on a null-valued expression.
At C:\Users\Pinku\Desktop\Untitled1.ps1:7 char:23
+ $usernameElement.Click <<<< ()
+ CategoryInfo : InvalidOperation: (Click:String) [], RuntimeExcepti
on
+ FullyQualifiedErrorId : InvokeMethodOnNull
I have tried but have not been able to alleviate myself from this issue.Please suggest!
Instead of using $doc.getElementsByTagName("input") and then trying to filter through the results, try retrieving the ID directly using getElementById:
$usernameElement = $doc.getElementById("session_key-login")
$usernameElement.Click()
---Edit---
Response to still getting the null-valued expression after using the above:
The error message is that it can't find any elements called "session_key-login", and so it returns $null, and hence, when you try to invoke the Click() method, it throws the error. Some things to try:
-Check to see if the id exists. Run the following code after creating your $ie object, and see if there is an ID that matches "session_key-login":
$ie = New-Object -Com "InternetExplorer.Application"
$ie.Navigate("www.linkedIn.com")
$ie.Visible = $true
$doc = $ie.document
$doc.getElementsByTagName("Input") | Select Id, Name
-Try running your PowerShell session as Administrator. I know I wasn't able to launch IE properly until I ran PowerShell as Administrator. For ex. even though the iexplore process was created, the physical Internet Explorer window didn't open for me.

PowerShell folder permission error - Some or all identity references could not be translated

I am running this script as Admin and It does create the folders requred, just does not set the appropriate permissions.
$Users = Get-Content "D:\New_Users.txt"
ForEach ($user in $users)
{
$newPath = Join-Path "F:\Users" -childpath $user
New-Item $newPath -type directory
$UserObj = New-Object System.Security.Principal.NTAccount("DOMAIN",$user)
$acl = Get-Acl $newpath
$acl.SetAccessRuleProtection($True, $False)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("O1OAK\$user","AppendData,CreateDirectories,CreateFiles,DeleteSubdirectoriesAndFiles,ExecuteFile,ListDirectory,Modify,Read,ReadAndExecute,ReadAttributes,ReadData,ReadExtendedAttributes,ReadPermissions,Synchronize,Traverse,Write,WriteAttributes,WriteData,WriteExtendedAttributes","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("NT AUTHORITY\SYSTEM","FullControl","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators","FullControl","ContainerInherit, ObjectInherit","None","Allow")
$acl.SetAccessRule($accessRule)
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule("1OAK\$user","Delete","ContainerInherit, ObjectInherit","None","Allow")
$acl.removeAccessRule($accessRule)
$acl.SetOwner($UserObj)
$acl | Set-Acl $newpath
}
The first error in a string of 3 that I get is below. I think it is the most important and will fix the other 2.
Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At D:\DOMAIN\IT\IT Private\User Drives\user_folders.ps1:12 char:20
+ $acl.SetAccessRule <<<< ($accessRule)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
The error is pretty self explanatory: Some or all identity references could not be translated.
This means the account couldn't be found. So what you have to do is verify your accounts. Since you're adding 4 ACE's, you'll need to identify which is invalid.
The easiest way to do this is to debug through, line by line using the ISE or PowerGUI.
I tried your code with "NT AUTHORITY\SYSTEM" and "BUILTIN\Administrators" and it works so the issue is with "O1OAK\$user" or "1OAK\$user". You likely have an invalid account in your text file.
a gotch with the user ID is that AD truncates the username, so a user with a long name "j_reallylongname" will have a samid (Security Account Manager (SAM) account name) which is truncated. (j_reallylong)
so when fetching usernames, make sure you verify against the AD before using it.
When i've got the upns, so i run a dsget query to get the samid then use that to build the identity reference.
Adding this in case any C#/ASP.NET developers get this (which is my scenario, and I found this post).
I am using .NET Core in a corporate environment, and I need to check UserGroups as part of security. The code is like (where "user" is a ClaimsPrincipal):
var windowsIdentity = user.Identity as WindowsIdentity;
if( windowsIdentity is null )
throw new Exception( $"Invalid Windows Identity {user.Identity.Name}" );
return windowsIdentity.Groups
.Select( g => g.Translate( typeof( NTAccount ) ).Value );
Anyway, someone in charge of groups deleted a group I was part of, and the AD replication lag caused me to get the error in the title. A logoff and/or reboot worked just fine.
For me it was a case of where i verified whether the script execution knew the password by using $user = Get-Credential "username". i had to turn my $user into $user.UserName To give the script parameters the value they were expecting

Resources