Powershell Call cancelled - powershell

I was running Get-CimInstance -Namespace root/CIMV2 -ClassName CIM_Component | Out-File -Encoding utf8 .\CIM_Component.txt and received
Get-CimInstance : Call cancelled
At line:1 char:2
+ (Get-CimInstance -Namespace root/CIMV2 -ClassName CIM_DirectoryContai ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80041032,Microsoft.Management.Infrastructure.CimCmdlets.GetCimInstanceCommand
This was not cancelled from a keyboard interrupt. It simply... timed out?
I really don't know why it cancelled at all.
I was hoping someone else might know what happened that it threw the Call cancelled error.
It may simply be that the amount of information is just too much going threw the pipe that it... but, its not a out of memory error...
I have no idea!

***strong text***Hummm… See the below for potential edification...
CIM_Component class
I saw a question about the CIM_Component class and wondered what it
was. So I tried it
Get-CimInstance -Namespace root\CIMV2 -ClassName CIM_Component | select -f 1 | fl *
# Results
GroupComponent : Win32_Directory (Name = "<directory path>")
PartComponent : CIM_DataFile (Name = "<file path>”)
PSComputerName :
CimClass : root/CIMV2:CIM_DirectoryContainsFile
CimInstanceProperties : {GroupComponent, PartComponent}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties
What you’ll get is a list of every file on your system – showing
folder in the GroupComponent (parent) and File in the PartComponent
(child).
The documentation is totally accurate and totally useless as it
explains that you get a parent-child relationship but not what’s in
it!
I’d strongly recommend against using this class – there are easier
ways to get the information.

Related

Powershell Exception issue

Thank you in advance to taking in consideration such stupid query.
I am trying to get Process list with some extended properties from powershell with following query:
**Get-Process -FileVersionInfo | select -Unique | Select-Object * | Format-Table -Property OriginalFilename, FileName, InternalName, ProductName, CompanyName, FileVersion -Wrap > C:\Users\user\OneDrive\Desktop\final.txt**
It works but for some processes I am unable to get FileVersion which is ok and I don't care about that. Problem is that Even trying to catch the exception, It simple does nothing.
Get-Process: Cannot enumerate the file version information of the
"csrss" process. At line:1 char:7
try { Get-Process -FileVersionInfo | select -Unique | Select-Object * ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : PermissionDenied: (System.Diagnostics.Process (csrss):Process) [Get-Process],
ProcessCommandException
FullyQualifiedErrorId : CouldnotEnumerateFileVer,Microsoft.PowerShell.Commands.GetProcessCommand
Tried to get exception details with
**$Error[0] | Select-Property ***
and
**$Error[0].exception.GetType().fullname**
Which gives following result:
WriteErrorStream : True PSMessageDetails : Exception
: Microsoft.PowerShell.Commands.ProcessCommandException: Cannot
enumerate the file version information of the "Idle"
process. ---> System.ComponentModel.Win32Exception: Unable to enumerate the process
modules.
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId,
Boolean firstModuleOnly)
at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32
processId)
at System.Diagnostics.Process.get_MainModule()
at System.Management.Automation.PsUtils.GetMainModule(Process
targetProcess)
at Microsoft.PowerShell.Commands.GetProcessCommand.ProcessRecord()
--- End of inner exception stack trace --- TargetObject : System.Diagnostics.Process (Idle) CategoryInfo
: PermissionDenied: (System.Diagnostics.Process (Idle):Process)
[Get-Process], ProcessCommandException FullyQualifiedErrorId :
CouldnotEnumerateFileVer,Microsoft.PowerShell.Commands.GetProcessCommand
ErrorDetails : InvocationInfo :
System.Management.Automation.InvocationInfo ScriptStackTrace : at
, : line 1 PipelineIterationInfo : {0, 1, 64,
0...}
While trying to catch the exception with [Microsoft.PowerShell.Commands.ProcessCommandException] it simply does nothing and still throws bunch on red lines.
try { Get-Process -FileVersionInfo | select -Unique | Select-Object * | Format-Table -Property OriginalFilename, FileName, InternalName, ProductName, CompanyName, FileVersion -Wrap > C:\Users\user\OneDrive\Desktop\final.txt
} catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
Write-Verbose "Catch all" -Verbose
}
Could you help please?
Thanks in advance.
You can ignore the processes you don't have the required access to by adding an ErrorAction to Get-Process
Get-Process -FileVersionInfo -ErrorAction Ignore
If you somehow do need to know what processes gave you errors, you can use
Get-Process -FileVersionInfo -ErrorAction SilentlyContinue
and look at $error afterwards or cudo's to #zett42
Get-Process -FileVersionInfo -ErrorAction SilentlyContinue -ErrorVariable ProcError
and look at $ProcError afterwards

Cannot convert System Object to String Powershell

Hi I am trying to use the below powershell script
$get_AD_Server = (Get-WmiObject -Class Win32_NetworkAdapterConfiguration).DnsDomain | Out-String
$get_Nearest_DC = (Get-ADDomainController -DomainName $get_AD_Server -Discover -NextClosestSite).Name
The output of $get_AD_Server contains contoso.com, however when i pass the variable $get_AD_Server in the next variable it always errors out, any idea on what am i doing wrong?
Get-ADDomainController : The format of the specified domain name is invalid
At line:2 char:20
+ ... arest_DC = (Get-ADDomainController -DomainName $get_AD_Server.ToStrin ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-ADDomainController], ADException
+ FullyQualifiedErrorId : GetADDomainController:BeginProcessingOverride:DiscoverDC:1212,Microsoft.ActiveDirectory.Management.Commands.GetADDomainController
Automatic variable unrolling will return a collection.
DNSDomain property may not be populated. In my case it isn't. Assuming you've got that covered I think you might have better luck if you isolate the NIC configuration you care about. If you narrow the return to 1 object .DNSDomain will be a string.
In my case this looks like:
(Get-WmiObject win32_NetworkAdapterCOnfiguration -Filter "IPEnabled = 'True'").DnsDomain
If needed just work on the filter until you find something that reliably only returns the NIC you care about.
Note: I may have misread something, but I worry you'll have an issue with the next step. You may have trouble querying the AD domain when you aren't authenticated. If you do hit something like that you may consider using the -Credential parameter on Get-ADDomainController. Of course it'd be interactive at that point.
Instead of fetching the DNS domain associated with the NIC, pull the computers domain from the Win32_ComputerSystem class:
$domain = (Get-WmiObject -Class Win32_ComputerSystem).Domain
$nearestDC = (Get-ADDomainController -DomainName $domain -Discover -NextClosestSite).Name

Using Powershell called from a bat file, Need to get owner/user of a windows process, but owner isn't showing up

I need to get the path and owner of certain processes on a remote computer and use a batch file to get it. So far, I've come up with something that gives me the path, but not the owner:
powershell -command "Get-WmiObject -Class win32_process -ComputerName myserver.mydomain.local -Filter 'name like """"%%myprocess%%""""' | select path,GetOwner"
For that, GetOwner is blank.
How can I get this to work or accomplish the same objective with another PS query or batch command?
GetOwner() is a method. User is a property returned by getowner() that is probably what you want.
set myprocess=powershell
powershell "Get-WmiObject win32_process -computername myserver.mydomain.local | where name -match %myprocess% | select path,#{n='Owner';e={$_.getowner().user}}"
Path Owner
---- -----
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe admin
Or you can use get-process. EDIT: Hmm looks like -computername and -includeusername can't go together. I can test it with "%computername%" but not "localhost".
powershell "get-process -computername %computername% -includeusername *%myprocess%* | select path,username"
Get-Process : Parameter set cannot be resolved using the specified named parameters.
At line:1 char:1
+ get-process -computername DESKTOP-JQ7B7TZ -includeusername *powershel ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Process], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Commands.GetProcessCommand
If remote powershell were working:
powershell "invoke-command myserver.mydomain.local { get-process -includeusername *%myprocess%* | select path,username }"
Path : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
UserName : DESKTOP-JQ7B7TZ\admin
PSComputerName : myserver.mydomain.local
RunspaceId : b1bc87a7-1c21-4f91-a238-bbb68978ea6c

How to check particular VMware VM is not currently running in the task using PowerShell?

I need to check particular VMware VM is currently in the recent task like CLone_task, Migrate_VMTask,.etc and also skip that VM before VM migration starts..
I have tried the below code:
PS> Get-Task (Get-VM -Name VM1) | Select State
Get-Task : Cannot bind parameter 'Status'. Cannot convert the "nalb00cava3"
value of type "VMware.VimAutomation.ViCore.Impl.V1.Inventory.VirtualMachineImpl"
to type "VMware.VimAutomation.Sdk.Types.V1.TaskState".
At line:1 char:10
+ Get-Task (Get-VM -Name nalb00cava3) | Select State
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-Task], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetTask
This should do what you're looking for, the final pipe is where you would define the specific VM.
Get-Task | ?{$_.ObjectId -match 'VirtualMachine'} | Select #{N='VM';E={(Get-View -Id $_.ObjectId).Name }},State,Description | where {$_.VM -eq "VM1"}
It filters on ObjectId from Get-Task, then referencing the Id, determines the VM names, and finally filters on the VM you define.

PowerShell remote event log parsing

I wrote a small script to grab event log entries from a remote machine and write it to a .csv file. The script works when targeting a single machine, but when I try to implement a for loop and loop it over all machines in Active Directory, I get this error:
Method invocation failed because [Microsoft.ActiveDirectory.Management.ADComputer]
does not contain a method named 'op_Addition'.
At Y:\srp.ps1:7 char:143
+ ... | Export-Csv $($computer + ".csv")
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Export-Csv : Cannot validate argument on parameter 'Path'. The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
At Y:\srp.ps1:7 char:141
+ ... 0 | Export-Csv $($computer + ".csv")
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Export-Csv],
ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,
Microsoft.PowerShell.Commands.ExportCsvCommand
The error indicates there's a problem with the Export-Csv command, but running the command by itself creates the log files needed. Here is the full script, for reference:
# Gets SRP event log entries from remote machine and writes them to a .csv file
# of the same name.
Write-Output "Running..."
$computers = Get-ADComputer -filter {(Name -like "PC*") -or (Name -like "LT*")}
foreach ($computer in $computers) {
Get-EventLog -LogName Application -Source Microsoft-Windows-SoftwareRestrictionPolicies
-ComputerName $computer -Newest 10 | Export-Csv $($computer + ".csv")
} #end foreach
Write-Host "Done."
Any ideas as to why this error appears when I try to loop over computers in AD?
It looks like Get-ADComputer returns ADComputer objects, but you're passing it to Get-EventLog's ComputerName parameter, which takes a string, as-is. I'm assuming you'll need to grab the name property from the Microsoft.ActiveDirectory.Management.ADComputer object.