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.
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 retrieve a list of updates in the scope. My code is as follows:
#Loads Microsoft.UpdateServices.Administration assembly in order to connect to the WSUS server
[reflection.assembly]::LoadWithPartialName(“Microsoft.UpdateServices.Administration”) | Out-Null
#Make the initial WSUS connection by using the .NET accelerator [Microsoft.UpdateServices.Administration.AdminProxy] and the static method getUpdateServer(), which requires two values: the WSUS server name and a Boolean value for a secure connection.
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer()
#Creating the Computer Target Scope object
$computerscope = New-Object Microsoft.UpdateServices.Administration.ComputerTargetScope
#Find all clients using the computer target scope
$wsus.GetComputerTargets($computerscope)
#Gets computer status
$Wsus.GetComputerStatus($computerscope,[Microsoft.UpdateServices.Administration.UpdateSources]::All)
When I try to run the following:
#Provides a summary of whether the clients that are specified in the scope require the update
ForEach($update in $computerscope)
{
$update = $wsus.SearchUpdates($computerscope)
}
$update[0].GetSummary($computerscope)
I receive the following error:
You cannot call a method on a null-valued expression.
At line:6 char:1
+ $update[0].GetSummary($computerscope)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
even though I am passing $computerscope in the GetSummary method.
Any guidance would be appreciated.
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 am editing a Powershell script that a colleague created before they left which I assume was created on an older version of Powershell/Activedirectoy. It is to create an AD account but I'm having an issue checking if a username already exists then carrying out an action if it does.
$UsernameInteger = 1
$sAMAccountName = $sn+$givenName.substring(0,$UsernameInteger)
# Check to see if the username is available in Active Directory
do
{
if (dsquery user -samid $sAMAccountName)
{
$CreateUser = $False
$UsernameInteger++
$Username = $sn+$givenName.substring(0,$UsernameInteger)
}
Else
{
$CreateUser = $True
}
}
Until ($CreateUser -eq $True)
When I run this code with an account with the same name I get the following error:
Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string.
Parameter name: length"
At C:\AD Account Creation.ps1:43 char:5
+ $Username = $sn+$givenName.substring(0,$UsernameInteger)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentOutOfRangeException
What I want is when the $createuser = $false then it will add the next letter of their $givenName to the $username and keep doing this until an account with the same $sAMAccountName is not found and the account can be created.
How would I go about doing this?
You've incremented the counter to a value bigger than the length of the $givenName string. You need to change the increment logic to something like:
if ($UsernameInteger -le $givenName.length) {
$UsernameInteger++
}
This won't help if the username you pass in already exists in its entirety though, so you'll also need to handle that scenario
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)"