Permissions for using gwmi win32_ntlogevent instead of get-eventog? - powershell

The problem I have: get-eventlog works (I tested by doing "run as" on the PoSH ISE). Get-WMIObject win32_ntlogevent does not. It's a perm issue of some sort. Help please.
Background:
I've built a script that uses gwmi win32_ntlogevent to pull event logs. (I chose it because it was an order of magnitude faster than either get-winevent or get-eventlog, even with filters).
However, I cannot reach some other servers in my environment. So I had the Servers group add a credential to connect under, that has some sort of Log Reader right. (not sure what they added)
Get-Eventlog:
$server = "myserver"
get-eventlog -ComputerName $server -logname "application"
(above returns results)
Get-WMIObject win32_ntlogevent does not. Neither with
Get-WmiObject win32_ntlogevent -ComputerName $server
or
$time = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime('2015/05/01 5:00:00am')
$EventQuery = #"
select
Logfile, RecordNumber, Timegenerated, TimeWritten, EventCode, EventType, Type, Category, CategoryString, SourceName, InsertionStrings, ComputerName, User, Message
from Win32_NTlogEvent
where timewritten >='$time'
and LogFile = 'system'
"# #this line must be un-recessed
gwmi -computername $server -Query $EventQuery
Instead, I get:
gwmi : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:10 char:1
+ gwmi -computername "myserver" -Query $EventQuery
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Thanks!

Related

Get-WmiObject Win32_Product critical error

I have created a remote uninstaller, it has been working perfectly until I got to a pc which has too many MSI packages. Until the Get-WmiObject Win32_Product can finish searching and listing all the packages it gets a critical error with no explanation.
My guess is that it has a timeout timer but I have no idea how to modify it or if it is even possible.
the code I use :
$ComputerName = Read-Host -Prompt 'Input the computer name' # the name of the computer to remove the app from
Get-WmiObject Win32_Product -ComputerName $ComputerName | Select-Object -Property Name | Out-GridView -Title "All apps on destination Computer"
$Name = Read-Host -Prompt 'Input name of the application (has to be exact name)' #name of the application
$Application = Get-WmiObject Win32_Product -ComputerName $ComputerName | Where-Object {$_.Name -eq $Name} #choose the object, this will be the app that we will delete
if ($Application) {
$Application.Uninstall()
"The removal was successful"
}
else {
$Name + ' is not installed on ' + $ComputerName
}
Start-Sleep -Seconds 10
the error:
Get-WmiObject : Critical error
At line:5 char:1
+ Get-WmiObject Win32_Product -ComputerName $ComputerName | Select-Obje ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
the application asks the name of the computer that I want to uninstall an app form, lists all the packages in that computer, and I choose the one I want to delete, copy the name and paste it in the next field.
this error happens after I enter a name of the computer, also it takes a really long time to load, the error happens at 55 second mark from the moment it starts listing.
My idea is that the command has a timeout or a number of max
If anyone has any idea why I get this error or how to avoid it please help

Powershell printer installation script

I'm trying to create a login script that performs a few actions. I need it to complete the following.
Check and record the current default printer.
Delete all printers.
Install a specific list of printers.
Set the default printer back to what the default printer was previously.
I need to do this because we've made some printer name changes on the network and we want to re-map all of the printers with the new names and also install some additional printers. I currently have a batch file calling a .ps1 file. Here's the code from both files.
Login.bat
#echo off
powershell -command Set-ExecutionPolicy Unrestricted -force
Powershell -command " & '\\server\share\MyPSScript.ps1'"
Login.ps1
# Save current default printer.
Get-WmiObject -Query " SELECT * FROM Win32_Printer WHERE Default=$true" | foreach {$_.portname} -OutVariable CurDefPrinter
# Deletes all network printers.
Get-WmiObject Win32_Printer | where{$_.Network -eq ‘true‘} | foreach{$_.delete()}
# Maps all network printers.
add-printer -connectionname "\\server\ricoh"
add-printer -connectionname "\\server\hp"
# Set default printer
(Get-WmiObject -Class Win32_Printer -Filter "portame='$CurDefPrinter'").SetDefaultPrinter()
When I run this, I get this error.
C:\Temp\Scripts>Login.bat
C:\Temp\Scripts>REM #echo off
10.0.0.155
Get-WmiObject : Invalid query "select * from Win32_Printer where portame='10.0.0.155'"
At \\server\share\login.ps1:12 char:2
+ (Get-WmiObject -Class Win32_Printer -Filter "portame='$CurDefPrinter' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
You cannot call a method on a null-valued expression.
At \\server\share\Login.ps1:12 char:1
+ (Get-WmiObject -Class Win32_Printer -Filter "portame='$CurDefPrinter' ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Any help would be greatly appreciated!
You spelled PortName wrong so nothing was being returned and you were calling a method on ($null)
(Get-WmiObject -Class Win32_Printer -Filter "portname='$CurDefPrinter'").SetDefaultPrinter()
If you dont need to use the Query and Filter option you can do it like this:
#to get the current default printer
$default = Get-WmiObject -Class Win32_Printer | Where-Object {$_.Default -eq "true"}
#to reset the default printer
$default.SetDefaultPrinter()
Atleast it works at my enviroment.

Win32_LogicalFileSecuritySetting returns an error for some paths, but not others

I got a script from Microsoft that uses the following method to get NTFS security settings from a remote machine.
$SharedFolderPath=[regex]::Escape("D:\UserSetup");
$SharedNTFSSecs = Get-WmiObject -Class Win32_LogicalFileSecuritySetting -Filter "Path='$SharedFolderPath'" -ComputerName $Computer
$SharedFolderPath=[regex]::Escape("C:\Program Files\AdventNet\ME\OpManager\Reports");
$SharedNTFSSecs = Get-WmiObject -Class Win32_LogicalFileSecuritySetting -Filter "Path='$SharedFolderPath'" -ComputerName $Computer
I got the paths from a previous call to Win32_Share. The first one works fine, the second gives an error:
> Get-WmiObject : Invalid query At line:1 char:118
> + $SharedFolderPath=[regex]::Escape("C:\Program Files\AdventNet\ME\OpManager\Reports"); $SharedNTFSSecs =
> Get-WmiObject <<<< -Class Win32_LogicalFileSecuritySetting -Filter
> "Path='$SharedFolderPath'" -ComputerName $Computer
> + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
> + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
The only thing different is the path:
D:\UserSetup
C:\Program Files\AdventNet\ME\OpManager\Reports
I can connect to the share and view the security permissions. I am effectively in the local administrators group and that group has full control over the problem share.
Does anyone have any clue why I'm getting an error (and consequently no resulting object)?
I beleive that this is because :
[regex]::Escape("C:\Program Files\AdventNet\ME\OpManager\Reports")
gives
C:\\Program\ Files\\AdventNet\\ME\\OpManager\\Reports
The white space is escaped also, try :
Get-WmiObject -Class Win32_LogicalFileSecuritySetting -Filter "Path='C:\\Program Files\\AdventNet\\ME\\OpManager\\Reports'" -ComputerName $Computer

Suppressing fatal error (access denied)

Going round in a circle here...
I'm trying to handle and continue from 'fatal errors' in scripts. I know the -EA silentlycontinue doesn't work but keep coming back to using foreach to get around it but solutions I find don't work for me for example and this is an example not what I'm trying to do...
The code:
get-content serverLists.txt |
foreach {get-wmiobject -computer $_ -query "Select * from win32_logicaldisk where drivetype=3"} |
Format-Table SystemName,DeviceID,Size,FreeSpace,VolumeName
Dies with:
get-wmiobject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At line:1 char:40
+ get-content serverLists.txt | foreach {get-wmiobject -computer $_ -query "Select ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
I want it to just continue, I've tried and investigated try/catch this just gives me the error in a readable format and stops, I've looked at ping/port check solutions but some servers are behind firewalls but certain ports are open etc I just want it to handle the fatal error and just carry on...
BTW this isn't a rights issue, it'll pass through a whole bunch of servers fine then the script will die on one and stop
try..catch should do what you want:
Get-Content serverLists.txt | % {
try {
gwmi -Computer $_ -Query "SELECT * FROM Win32_LogicalDisk WHERE DriveType=3"
} catch {}
} | Format-Table SystemName,DeviceID,Size,FreeSpace,VolumeName
or you could change $ErrorActionPreference:
$ErrorActionPreference = "SilentlyContinue"
Get-Content serverLists.txt | % {
gwmi -Computer $_ -Query "SELECT * FROM Win32_LogicalDisk WHERE DriveType=3"
} | Format-Table SystemName,DeviceID,Size,FreeSpace,VolumeName

Invalid Namespace when automating Get-WMIObject

I am trying to automate the retrieval of OS architecture and when I do I get an Invalid Namespace error.
foreach($i in $hosts){
$ip = $i.name
Get-WmiObject -ComputerName $ip Win32_OperatingSystem
}
If I take Get-WmiObject -ComputerName $ip Win32_OperatingSystem and replace $ip with a legit IP it works perfectly. I even added Write-Host to the front of Get-WMIObject so it would display the entire command that would run. I ran the output from Write-Host and the command completes successfully.
Error:
Get-WmiObject : Invalid namespace
At line:4 char:18
+ Get-WmiObject <<<< -ComputerName $ip Win32_OperatingSystem
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
The $hosts variable is a PSCustomObject with two noteProperty fields. The first is name and the second is user. The name field holds an IP address of the system.
It turns out there were trailing whitespaces after the IPs. I used .trim() and now everything works just fine.