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()
Related
Working on a Kiosk Windows tablet, was working before I started to optimize. I had used a Windows Debloating tool to remove all the unnecessary items on the tablets. But I believe it removed something I was calling on in the script. Just looking to see if anyone has any idea what I would need to reinstall. Or if I should start over on the Image
Here is the Powershell script
Add-Type -AssemblyName UIAutomationClient
$MyProcess = Get-Process | where { $_.MainWindowTitle -like "Kiosk*" }
while (1 -eq 1) {
if ($null -ne $MyProcess) {
# if Minimized make it Normal
$ae = [System.Windows.Automation.AutomationElement]::FromHandle($MyProcess.MainWindowHandle)
$wp = $ae.GetCurrentPattern([System.Windows.Automation.WindowPatternIdentifiers]::Pattern)
if ($wp.Current.WindowVisualState -eq 'Minimized') {
$wp.SetWindowVisualState('Normal')
}
# execute needed function
}
else {
start-process "C:\Users\Public\Desktop\Welcome.lnk" -WindowStyle Normal
# execute needed function
}
start-sleep -Milliseconds 500
}
And here is the error attempted a copy and paste
Cannot convert argument "hwnd", with value: "System.Object[]", for "FromHandle' to type "System.IntPtr": "Cannot convert the "System.Object[]" value of type "System.Object[]"' to type "System. IntPtr At C:\Scripts\KioskMinimizedcheckscript.ps1:9 char:5 + Sae = [system.windows. Automation.AutomationElement]:: FromHandle($
+
+CategoryInfo
: NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgument Conversion InvalidcastArgument
You cannot call a method on a null-valued expression. At C:\scripts\KioskMinimizedcheckscript.ps1:10 char:5
Swp = Sae.GetCurrentPattern([system.windows. Automation.windowPatt ...
+ CategoryInfo
Invalidoperation; (:) [], RuntimeException
+ FullyQualifiedErrorId: InvokeMethodonNull
Image of Actual Error
Tried running script on default install of windows and works fine. Just need to know what to add back into the stripped down version.
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')
Before deleting an EventSubscriber with SourceIdentifier "abc", I want to test if it exists and only then delete it. Otherwise there is no need to.
But every time I access it to test if it exists with:
Get-EventSubscriber -SourceIdentifier "abc"
Powershell responds with an error:
get-eventsubscriber : Event subscription with source identifier 'abc' does not exist.
At line:1 char:8
+ $chk = get-eventsubscriber -SourceIdentifier "abc"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-EventSubscriber], Argu
mentException
+ FullyQualifiedErrorId : INVALID_SOURCE_IDENTIFIER,Microsoft.PowerShell.C
ommands.GetEventSubscriberCommand
stating that it does not exist. Is there a way to avoid the error messages and instead set a variable to null or false that can be tested to see if it does not exist?
Something like:
$eventSubscriberExists = Get-EventSubscriber -SourceIdentifier "abc"
if ($eventSubscriberExists) {
Unregeister-Event -SourceIdentifier "abc"
}
In other words instead of sending error messages to the console, set a variable to true or false.
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'
I'm using some PowerShell functions to configure Windows product keys and activation. I get an instance of the SoftwareLicensingService and call InstallProductKey, like this. The trap block with super formatting is extra to help debugging.
trap [Exception]
{
"=================================================="
"Trapped: $($Error[0])"
"=================================================="
"Exception: $($_.Exception)"
"--------------------------------------------------"
""
break
}
$service = Get-WmiObject -Query "SELECT * FROM SoftwareLicensingService"
$service.InstallProductKey("12345-12345-12345-12345-12345")
$service.RefreshLicenseStatus() | Out-Null
The error condition is an invalid product key. I know this because I entered it manually into the Activate Windows dialog from the System panel. But, the script only ever shows me the WMIMethodException or the COMException.
==================================================
Trapped: Exception calling "InstallProductKey" : ""
==================================================
Exception: 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)
--------------------------------------------------
Exception calling "InstallProductKey" : ""
At line:14 char:31
+ $service.InstallProductKey <<<< ("12345-12345-12345-12345-12345")
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : WMIMethodException
I don't get a return code from the method (despite the documentation stating I do, can't find a list of error codes anyway). Do you know how to get the activation (or product key install) error reason?
As far as I can see there's no message there. Adding these to your trap:
$_ | fl * -Force
$_.Exception | fl * -Force
Returns everything that is there in the exception and there is nothing useful. So I googled a bit and found a piece of C# code here: http://www.dozty.com/?tag=change-windows-7-product-key-c-sharp They were cathcing ManagementException and in C# it seemed to work a bit better. I have rewritten that code into PowerShell and was trying to catch ManagementException, but without luck:
trap [Exception]
{
[System.Management.ManagementException] $_
break
}
$classInstance = new-object System.Management.ManagementObject("root\CIMV2","SoftwareLicensingService.Version=`"6.1.7600.16385`"", $null);
$inParams = $classInstance.GetMethodParameters("InstallProductKey")
$inParams["ProductKey"] = "12345-12345-12345-12345-12345"
$classInstance.InvokeMethod("InstallProductKey", $inParams, $null)
It throws: Cannot convert the "System.Runtime.InteropServices.COMException (0xC004F050)"