Null-Valued Expression Error in Powershell - powershell

I am trying to uninstall a Program via Power Shell but I am getting an error "You cannot call a method on a null valued expression.
PS C:\Users\user> $App = Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq "CVF_x64"}
PS C:\Users\user> $App.Uninstall()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $App.Uninstall()
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The program is in Programs and Features on control panel, see attached picture below.
List of Apps on Control Panel
Powershell List of Apps
CVF Doesn't show up in Powershell for some reason

looks like your query does not find anything -> empty variable?
$x = $null
$x.uninstall()
result: You cannot call a method on a null-valued expression.
btw. wmi is a thing of the past, use the cim cmdlets, and do the filtering one step earlier:
$name = "MyApp"
get-ciminstance -query "select * from win32_product where name = '$name'"
To identify what the value of the variable name must be simply output this beforehand and identify the exact string:
(get-ciminstance -query "select * from win32_product").name
You could also check the registry:
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" -Name DisplayName,DisplayVersion,InstallSource,Publisher,UninstallString
Execute the command in the attribute UninStallString...

Related

Using Invoke-CimMethod 'Activate' in order to activate a windows powerplan, instead I get Invalid Class what am I doing wrong?

I followed the Scripting Guy instructions from Microsoft but even with this I still get the same error Scripting Guy article
here is my script:
$p2=Get-CimInstance -N root\cimv2\power -Class win32_PowerPlan -Filter "ElementName = 'Balanced'"
Invoke-CimMethod -InputObject $p2-MethodName Activate
which results in:
Invoke-CimMethod : This method is not implemented in any class
At line:1 char:1
+ Invoke-CimMethod -InputObject $p2 -MethodName Activate
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (Win32_PowerPlan...2-f694-41f0...):CimInstance) [Invoke-CimMethod], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041055,Microsoft.Management.Infrastructure.CimCmdlets.InvokeCimMethodCommand
I cant seem to find answers I have looked in a few locations, I have seen people start to run into this a few months ago but I could not find an answer any advice would be appreciated
my end goal is to write a script where I import a powerplan and then activate it I have the import part working fine it just this last bit. $p contains my imported plan I used $p2 on a default plan for testing purposes.
cheers and thank you in advance for any advice you can offer
I found this code for changing the Power Schema.
Get-CimInstance -N root\cimv2\power -Class win32_PowerPlan | select ElementName, IsActive | ft -a
$p = gwmi -NS root\cimv2\power -Class win32_PowerPlan -Filter "ElementName ='Ultimate Performance'"
$p.Activate()
Get-CimInstance -N root\cimv2\power -Class win32_PowerPlan | select ElementName, IsActive | ft -a
pause
It works on most flavors of Windows O/S. I get this error sometimes.
"Exception calling "Activate" : "This method is not implemented in any class " At line:1 char:1 + $p2.Activate() + ~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WMIMethodException –"

Powershell Error for Get-Service

Back when I had Windows 7 an a lower version of Powershell the following code use to work without any issues.
It checks each server in a text file for some services and dumps the results to a CSV.
Now that I'm on Windows 10 and with Powershell v5 I get this error message:
Get-Service : Cannot open Service Control Manager on computer 'tfsserver1'. This operation might require other privileges. At
C:\Users\Razon\Desktop\Patching\ServerServices_Checker_v2.ps1:48
char:4
+ (Get-Service -Name TFSJobAgent*,IIS*,World* -ComputerName $_) | Select Machine ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
####System Varialbe to User's Deskotp
$filePath = [Environment]::GetFolderPath("Desktop")
Here is the code:
function tfsCheck
{
$Path = "$filePath\Patching\Servers\tfs_servers.txt"
Get-Content $Path | foreach {
(Get-Service -Name TFSJobAgent*,IIS*,World* -ComputerName $_) | Select MachineName, Status, DisplayName
}
}
#TFS Function Call and Write to CSV
tfsCheck|Select MachineName, Status, DisplayName |Export-Csv $filePath\Patching\Results\TFS_ServicesResults.csv -NoTypeInformation
To resolve this issue, elevate the user's network privileges to be able to access the Service Control Manager on the Server.
https://support.microsoft.com/en-in/help/964206/cannot-open-service-control-manager-on-computer-servername-.-this-operation-might-require-other-privileges

PowerShell script inside SQL Agent job error

I'm trying to run the code below via a script in a SQL agent job on a drive which is failing. When I logon as the service account user and run it in an ISE shell it works fine which leads me to believe it's not access related.
I tried running it as a PowerShell job step but it wouldn't work so decided to run it as a cmdexec job type and call it like this:
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file "F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1"
Script
$ComputerName = "servername"
$KeyFolder = "\\servername\sharename\SSRSKEYS\"
$KeyPassword = "Password1"
$TimeStamp = Get-Date -Format "-yyyyMMdd-HHmmss"
Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer" -Class "__Namespace" -ComputerName $ComputerName |
Select-Object -ExpandProperty Name |
% {
$NameSpaceRS = $_
$InstanceName = $NameSpaceRS.SubString(3)
$KeyFileName = Join-Path -Path $KeyFolder -ChildPath ($InstanceName + $Timestamp + ".snk")
$SQLVersion = (Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer\$($NameSpaceRS)" -Class "__Namespace" - ComputerName $ComputerName).Name
$SSRSClass = Get-WmiObject -Namespace "Root\Microsoft\SqlServer\ReportServer\$($NameSpaceRS)\$($SQLVersion)\Admin" - Query "SELECT * FROM MSReportServer_ConfigurationSetting WHERE InstanceName='$($InstanceName)'" -ComputerName $ComputerName
$Key = $SSRSClass.BackupEncryptionKey($KeyPassword)
If ($Key.HRESULT -ne 0) {
$Key.ExtendedErrors -join "`r`n" | Write-Error
} Else {
$Stream = [System.IO.File]::Create($KeyFileName, $Key.KeyFile.Length)
$Stream.Write($Key.KeyFile, 0, $Key.KeyFile.Length)
$Stream.Close()
}
}
Error
Executed as user: domain\svc_account. Exception calling "Create" with "2"
argument(s): "Access to the path '\\servername\sharename\SSRSKEYS\MSSQLSERVER-20150824-125254.snk' is denied." At
F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1:24 char:13 + $Stream = [System.IO.File]::Create($KeyFileName, $Key.KeyFile.Length ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +
CategoryInfo : NotSpecified: (:) [], MethodInvocationException +
FullyQualifiedErrorId : UnauthorizedAccessException You cannot call a
method on a null-valued expression. At
F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1:25 char:13 +
$Stream.Write($Key.KeyFile, 0, $Key.KeyFile.Length) +
Try passing the script path to the PowerShell.exe as a parameter using the & operator, e.g.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "& 'F:\Powershell\ScriptOutSSRSEncryptionKeys.ps1'"
The call operator (&) allows you to execute a command, script or function.
Syntax
& "[path] command" [arguments]

Property is empty when run through Invoke-Command

I am trying to individually monitor memory usage of a process (w3wp.exe) that has multiple instances of itself by filtering out a string found in the process' CommandLine property.
It works when I run this script locally:
$proc = (WmiObject Win32_Process -Filter "Name = 'w3wp.exe'" | Where-Object {$_.CommandLine -like "*SomeTextFromCl*"})
$id = $proc.ProcessId
$ws = [math]::round((Get-Process -Id $id).WS/1MB)
Write-Host $ws
However, when I try to run it remotely through Invoke-Command, I get an error telling that the Id property's value is null:
Cannot bind argument to parameter 'Id' because it is null.
+ CategoryInfo : InvalidData: (:) [Get-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetProcessCommand
+ PSComputerName : RemoteServerName
My Invoke-Command syntax is:
Invoke-Command -ComputerName RemoteServerName -FilePath script.ps1 -Credential $mycredential
I'm sure it's simple but I'm back to PS after a long absence and I had a look around but couldn't find anything really helpful.
You are writing the answer to the console. You use the ps1 as a function, so you should use:
return $ws
instead of
write-host $ws

Powershell, how to update several dns records

I have the following script, but am getting an error -
Script -
$CNAMES = Get-Content "C:\Temp\alias.txt"
$Query = "Select * from MicrosoftDNS_CNAMEType"
$Record = Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName 10.10.10.1 | Where-Object{$_.Ownername -match $CNAME}
Foreach($CNAME in $CNAMES)
{
$Record.RecordData = "some.server.net"
$Record.put()
}
Error -
Property 'RecordData' cannot be found on this object; make sure it exists and is settable.
At C:\temp\DNSUpdateCNAMETarget_02.ps1:7 char:9
+ $Record. <<<< RecordData = "some.server.net"
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
Method invocation failed because [System.Object[]] doesn't contain a method named 'put'.
At C:\temp\DNSUpdateCNAMETarget_02.ps1:8 char:12
+ $Record.put <<<< ()
+ CategoryInfo : InvalidOperation: (put:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
TIA
I didn't try (cause i don't have a MS-DNS at hand right now) but i'd suspect that you need
$Record.PSBase.Put()
to make it work.
EDIT:
As it looks $Record holds an array of System.Object so will have to cast it a suitable type to access .RecordData and .Put()
Your script queries for records of type MicrossoftDNS_CNAMEType which only support CreateInstanceFromPropertyData.
I would try sending you $Record to Get-Member
Get-WmiObject -Namespace "root\microsoftdns" -Query $Query -ComputerName 10.10.10.1 | Get-Member
to find out, what you are dealing with.