Powershell script works but also gives an error message - windows

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'

Related

Powershell Force Maximize / Reopen if close

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.

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()

cannot call a method on a null-valued expression - how to solve it

I have written a script that gets the zip file from a specific folder and unzip the file to a specific folder.
please check the below codes
$shell_app=new-object -com shell.application
$zip_file = $shell_app.namespace("C:\Users\jhnayak\Views_Seagate\jhnayak_DDTools_Phase14_Dev\apps\ddcli\build\win\\..\\..\\..\\..\sas2_rel\mptlib2_rel\mptlib2_rel.zip")
$destination = $shell_app.namespace("C:\Users\jhnayak\Views_Seagate\jhnayak_DDTools_Phase14_Dev\apps\ddcli\build\win\\..\\..\\..\\..\sas2_rel\mptlib2_rel")
$destination.Copyhere($zip_file.items())
$shell_app=new-object -com shell.application
$zip_file = $shell_app.namespace((Get-Location).Path + "\\..\\..\\..\\..\\sas2_rel\mptlib2_rel" + "\$filename")
$destination = $shell_app.namespace((Get-Location).Path + "\\..\\..\\..\\..\\sas2_rel\mptlib2_rel")
$destination.Copyhere($zip_file.items())
for both the codes i got the same error, please check below
You cannot call a method on a null-valued expression.
At line:1 char:38
+ $destination.Copyhere($zip_file.items <<<< ())
+ CategoryInfo : InvalidOperation: (items:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
when i hardcoded the path without using \..\ in between it worked perfectly.
please check the below code
$shell_app=new-object -com shell.application
$zip_file = $shell_app.namespace("C:\Users\jhnayak\Views_Seagate\jhnayak_DDTools_Phase14_Dev\sas2_rel\mptlib2_rel\mptlib2_rel.zip")
$destination = $shell_app.namespace("C:\Users\jhnayak\Views_Seagate\jhnayak_DDTools_Phase14_Dev\sas2_rel\mptlib2_rel")
$destination.Copyhere($zip_file.items())
but i would like to use the earlier one, so that the path should not be hard coded, it should work for all paths.
What is causing this error?
What exactly is my null valued expression?
Try parsing the path before passing it to $shell_app.namespace(). There is a handy method in .Net that does just that: System.IO.Path.GetFullPath(). Like so,
$relativeLoc = "...build\win\\..\\..\\..\\..\sas2..." # Complex dynamic path
$parsedLoc = [IO.Path]::GetFullPath($relativeLoc) # Get absolute path
$zip_file = $shell_app.namespace($parsedLoc)
As a bonus, you can use Test-Path to check that the target $parsedLoc exists.

PowerShell, doesn't contain method 'items'

When executing this code, I received the error below:
$filesExist = Test-Path($file)
if ($filesExist) {
$shell_app=new-object -com shell.application
$zip_file = Get-Item "$mindCrackFolder\files.zip"
$destination = Get-Item $mindCrackFolder
$destination.Copyhere($zip_file.items(), 0x14)
#Remove-Item "$zip_file"
#Remove-Item "install.ps1"
}
Error:
Method invocation failed because [System.IO.FileInfo] doesn't contain a method named 'items'.
At C:\Users\User1\Desktop\ps install\install.ps1:33 char:5
+ $destination.Copyhere($zip_file.items(), 0x14)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
But I already convertered $destination into a IO object to be manipulated? Can I get any help, this my first time experimenting with PS.
This has nothing do with $destination. $zip_file.items() is evaluated first and the error message is telling you that the .NET System.IO.FileInfo object returned by Get-Item has no Items() method. Get-Item only returns an object that provides information about a file - size, last write time, readonly or not, etc. You can't use Get-Item to access the contents of a ZIP file.
If you need to extract the contents of the ZIP file, consider using the PowerShell Community Exensions' Expand-Archive cmdlet.
The errors is talking about the object you use the items() method on = $zip_file. Powershell doesn't have built-in zip support, you gotta create it(using shell.application com-object, google it) or add a .net library. $zip_file is just a simple FileInfo object just as the ones you get from dir(Get-ChildItem). It does not contain an items() method.
Solution: as previously said, google powershell zip files to read about how you can use zip files in powershell. My suggestion is DotNetZip
I don't know what and where you learned these, but you seem to have copied some code wrongly and made changes ad-hoc. Try the below script which does what you want:
$shell_app=new-object -com shell.application
$filename = "test.zip"
$zip_file = $shell_app.namespace((Get-Location).Path + "\$filename")
$destination = $shell_app.namespace((Get-Location).Path)
$destination.Copyhere($zip_file.items(), 0x14)
The items and copyHere method are not available on FileInfo objects, which is what you get from Get-Item. Use them as shown above.

How do I get an error reason from InstallProductKey (SoftwareLicensingService) in PowerShell?

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)"

Resources