"InvalidOperation: (op_Addition:String) [], RuntimeException" in Powershell - powershell

I have a script that works on other PCs. It only on one PC I have following error message.
Error:
Fehler beim Aufrufen der Methode, da [System.Object[]] keine Methode mit dem Namen "op_Addition" enthält.
In C:\Users\stream1\Desktop\watchdog.ps1:8 Zeichen:5
$wmi += (Get-WMIObject -Class Win32_PerfFormattedData_Tcpip_Netwo ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
FullyQualifiedErrorId : MethodNotFound
Thats the script:
#$ErrorActionPreference = 'SilentlyContinue'
$threshold = 6000
$timer = new-timespan -Seconds 10
$wmi = 0
$count = 0
$clock = [diagnostics.stopwatch]::StartNew()
while ($clock.elapsed -lt $timer){
$wmi += (Get-WMIObject -Class Win32_PerfFormattedData_Tcpip_NetworkInterface | Select-Object BytesSentPerSec).BytesSentPerSec
$count++
}
$kbytes = ($wmi/$count) / 1kb * 8 #to kbit/s
if($kbytes -le $threshold)
{
Write-Output $kbytes
Write-Host "Neustart"
taskkill /f /im obs64.exe
timeout /t 5
Start-Process -FilePath "obs64.exe" -WorkingDirectory "C:\Program Files\obs-studio\bin\64bit\" --startstreaming --minimize-to-tray
}
else
{
Write-Output $kbytes
Write-Host "Alles OK"
}
Does somebody has any idea?
Thanks so much :-)
I thought it was due to the permission to run scripts in Powershell. But I allowed the execution of scripts (Unrestricted)

Related

How do I suppress PowerShell script block errors?

Below is a simple script block, the script block works. However, I would like to suppress any errors that the script block would generate.
$Name = 'TEST'
$SB = { param ($DSNName) ;
$conn = new-object system.data.odbc.odbcconnection
$conn.ConnectionString = ('DSN='+ $DSNName)
$conn.open()
$ConState = $conn.State
$conn.Close()
$ConState
}
$test = Start-job -scriptblock $SB -args $Name -RunAs32 -ErrorAction Stop | wait-job | receive-job
What I am trying to get out of this is a simple test for a 32bit ODBC connection. If the connection fails the connection state will remain closed but I also get an exception error I would like to suppress
Exception calling "Open" with "0" argument(s): "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : OdbcException
+ PSComputerName : localhost
If I pipe to out-null my $test variable is empty. When I use a valid DSN Name everything works as desired.
You could use try..catch:
try {
$test = Start-job -scriptblock $SB -args $Name -RunAs32 -ErrorAction Stop | wait-job | receive-job
catch [System.Management.Automation.MethodInvocationException] {
# Do nothing here if you want to suppress the exception completely.
# Although redirecting it to a log file may be a better idea, e.g.
# $Error[0] | Out-File -FilePath "script.log"
}

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]

Run remote PowerShell Office uninstallation script

KB2956128 is causing headache for users in my network. I do not run WSUS in this environment so I was going to employ PS script to take care of uninstallation.
By all means the script below should work
$comp = 'PC03'
$scrblock =
{
$TitlePattern = 'KB2956128'
$Session = New-Object -ComObject Microsoft.Update.Session
$Collection = New-Object -ComObject Microsoft.Update.UpdateColl
$Installer = $Session.CreateUpdateInstaller()
$Searcher = $Session.CreateUpdateSearcher()
$Searcher.QueryHistory(0, $Searcher.GetTotalHistoryCount()) |
Where-Object { $_.Title -match $TitlePattern } |
ForEach-Object {
Write-Verbose "Found update history entry $($_.Title)"
$SearchResult = $Searcher.Search("UpdateID='$($_.UpdateIdentity.UpdateID)' and RevisionNumber=$($_.UpdateIdentity.RevisionNumber)")
Write-Verbose "Found $($SearchResult.Updates.Count) update entries"
if ($SearchResult.Updates.Count -gt 0) {
$Installer.Updates = $SearchResult.Updates
$Installer.Uninstall()
$Installer | Select-Object -Property ResultCode, RebootRequired, Exception
# result codes: http://technet.microsoft.com/en-us/library/cc720442(WS.10).aspx
}
}
}
Invoke-Command -ComputerName $comp -ScriptBlock $scrblock -Credential 'myDomain\administrator'
Instead I get this error
Exception calling "CreateUpdateInstaller" with "0" argument(s): "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : PC03
Exception calling "QueryHistory" with "2" argument(s): "Exception from HRESULT: 0x80240007"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
+ PSComputerName : PC03
I don't quite understand why the access is denied. Any ideas?
Short answer is that the ComObject does not allow the CreateUpdateInstaller to be called remotely. You can only do this locally, not over sessions or any other remoting. You can however use psexec to remotely execute your script as system.

Restart-Computer to Email Body = Null, PowerShell

Attempting to run the follow script for a reboot I get the following error,
"Send-MailMessage : Cannot validate argument on parameter 'Body'. The argument is null or empty. Supply an arg
that is not null or empty and then try the command again.
At line:8 char:30
+ Send-MailMessage #messageParameters -BodyAsHtml
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage"
Any help would be great!
Thanks
Cody
Restart-Computer -ComputerName nocconverter1 -Wait -For Wmi
$server = 'XXX'
ping -n 2 $server >$null
Function Server_Status_Check {
if($lastexitcode -eq 0) {
write-host "$server is ONLINE"
} else {
write-host "$server is OFFLINE/UNREACHABLE"
}
}
$messageParameters = #{
Subject = "Result: Reboot report for WebPeriop - $((Get-Date).ToShortDateString())"
Body = Server_Status_Check | out-string
From = "XXXX"
To = "XXXXX"
SmtpServer = "exmbx6"
}
Send-MailMessage #messageParameters -BodyAsHtml
Write-Host writes directly to the display. It doesn't write to stdout out therefore your Server_Status_Check function outputs nothing. Change it to:
Function Server_Status_Check {
if($lastexitcode -eq 0) {
"$server is ONLINE"
}
else {
"$server is OFFLINE/UNREACHABLE"
}
}

PowerShell: Starting process with variable parsed from Get-Process

I am currently writing a PowerShell script to stop a few processes, start a program, and then restart those processes. The problem arises when I feed the processes into an array variable to restart them later.
My code:
$direc = "C:\Program Files (x86)\PathTo\Program.exe";
$arguments = "/theseArguments1", "/theseArguments2";
$processesDefined = #();
$processes = "notepad", "explorer";
ForEach ($i in $processes)
{
$processesDefined += get-process -name $i | select-object path;
get-process -name $i | stop-process -force;
}
start-process -filepath $direc -ArgumentList $arguments -NoNewWindow -wait;
ForEach ($i in $processesDefined)
{
start-process -filepath $i;
}
When debugging the $processesDefined.Count displays 2 and the $processesDefined displays as expected yet when it gets to tjhe time to start the processes I get:
Start-Process : This command cannot be executed due to the error: The system ca
nnot find the file specified.
At D:\Desktop\Aion.ps1:17 char:18
+ start-process <<<< -FilePath $i;
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp
erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
I've done a lot of searching but can't find anything of real help. Any help with this would be greatly appreciated. Thank you.
Output of $processesDefined:
[DBG]: PS D:\Desktop>>> $processesDefined
Path
----
C:\Program Files\Windows Media Player\wmpnetwk.exe
C:\Windows\explorer.exe
_____________________________________________________________
Try doing it this way. The way you are doing it leaves the variable $processesDefined with a table heading (PATH) and this will screw things up.
$processesDefined += (get-process -name $i).Path
This way will just give you the path with no table heading