How to output objects to various coordinates of a powershell console window at the same time? - powershell-4.0

I have been using powershell on a win 10 environment for a few months now, so still new to powershell and am trying use the powershell console as a technical point of display, whereby it cycles/loops through various components of data and displays the information at various coordinates of the console window. The problem I have is it can only display the data from any one particular loop at any one time. I suspect a type of multithreading is going to be needed like runspaces or psjobs, but I believe they are both background functions and cant display data in real-time, so not sure if the console even supports this kind of request.
Perhaps there is another way of going about this
I have tried putting all my scripts and get- command under one loop but it doesnt provide the "look" and feel we are trying to achieve. I want to be able to use the entire window as realestate for outputing objects. I have looked at psjobs and runspaces but they seem to work in the background.
So the code presented should output the get-service ojbects and the get-process objects to the coordinates specified at the same time.
function OBJ1{
[console]::setcursorposition(60,120)
Get-Process
]}
function OBJ2{
[console]::setcursorposition(10,70)
Get-Service
]}
Workflow obj3
{
Parallel
{
obj1
obj2
}
}
obj3
Instead the errors I get are:
<!-- language: lang-none -->
Microsoft.PowerShell.Utility\Write-Error : Exception calling "SetCursorPosition" with "2" argument(s): "The handle is invalid.
"
At obj3:20 char:20
+
+ CategoryInfo : NotSpecified: (:) [Write-Error], RemoteException
+ FullyQualifiedErrorId : System.Management.Automation.RemoteException,Microsoft.PowerShell.Commands.WriteErrorCommand
+ PSComputerName : [localhost]
Microsoft.PowerShell.Utility\Write-Error : Exception calling "SetCursorPosition" with "2" argument(s): "The handle is invalid.
"
At obj3:20 char:20
+
+ CategoryInfo : NotSpecified: (:) [Write-Error], RemoteException
+ FullyQualifiedErrorId : System.Management.Automation.RemoteException,Microsoft.PowerShell.Commands.WriteErrorCommand
+ PSComputerName : [localhost]

Related

How to obatin a different interface from a COM object in PowerShell

Using COM methods like [System.Runtime.InteropServices.Marshal]::GetActiveObject("VisualStudio.DTE") I can navigate the Visual Studio DTE object model fine. For instance from DTE object I can get Debugger, and then LocalProcesses, and the the Process object. But I need the derived Process2 interface on it, to call Attach2("<my debug engine>").
I could not find a way to obtain the interface I want, a simple cast results in runtime error: Cannot convert the "System.__ComObject" value of type "System.__ComObject#{5c5a0070-f396-4e37-a82a-1b767e272df9}" to type "EnvDTE80.Process2".
PS> $dte = [System.Runtime.InteropServices.Marshal]::GetActiveObject("VisualStudio.DTE")
PS> $p = $dte.Debugger.LocalProcesses | where {$_.ProcessID -eq 11212}
PS> $p
Name : C:\Program Files\IIS Express\iisexpress.exe
ProcessID : 11212
Programs : System.__ComObject
DTE : System.__ComObject
Parent : System.__ComObject
Collection : System.__ComObject
PS> [EnvDTE80.Process2]$p2 = $p
Cannot convert the "System.__ComObject" value of type "System.__ComObject#{5c5a0070-f396-4e37-a82a-1b767e272df9}" to type "EnvDTE80.Process2".
At line:1 char:1
+ [EnvDTE80.Process2]$p2 = $p
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
+ FullyQualifiedErrorId : RuntimeException
You can't really, at least not in a way that PowerShell will be able to remember when it comes to member binding.
PowerShell only ever operates based on runtime information. Even if you cast it in C# first, if QueryInterface returns the same pointer for that interface then all PowerShell is going to see is the IDispatch it currently detects. Even if the object you obtained was a strongly typed version from the primary interop assembly, PowerShell only sees concrete types (which there doesn't seem to be one for Process2).
As a workaround, you can use reflection:
[EnvDTE80.Process2].InvokeMember(
'Attach2',
[Reflection.BindingFlags]::InvokeMethod,
<# binder: #> $null,
<# target: #> $process,
<# args: #> #($myEngine))

Couldn't register WMI __EventConsumer in Powershell

My PC environment is Windows 10 Enterprise Evaluation, Build 17763.rs5_release.180914-1434
When I entered this command $consumer = ([wmiclass]"\.\root\subscription:CommandLineEventConsumer").CreateInstance() in Powershell (Run as Administrator), I got an exception like below.
Cannot convert value "\\.\root\subscription:CommandLineEventConsumer" to type "System.Management.ManagementClass". Error: "Not found
"
At line:1 char:1
+ $consumer = ([wmiclass]"\\.\root\subscription:CommandLineEventConsume ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastToWMIClass
I tried to digger more deeper information, then I got some messages like below
System.Management.Automation.RuntimeException: Cannot convert value "\\.\root\subscription:CommandLineEventConsumer" to type "System.Management.ManagementClass". Error: "Not found " ---> System.Management.Automation.PSInvalidCastException: Cannot convert value "\\.\root\subscription:CommandLineEventConsumer" to type "System.Management.ManagementClass". Error: "Not found " ---> System.Management.ManagementException: Not found
at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus errorCode)
at System.Management.ManagementObject.Initialize(Boolean getObject)
at System.Management.ManagementBaseObject.get_wbemObject()
at System.Management.PropertyData.RefreshPropertyInfo()
at System.Management.PropertyDataCollection.get_Item(String propertyName)
at System.Management.Automation.LanguagePrimitives.ConvertToWMIClass(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
--- End of inner exception stack trace ---
at System.Management.Automation.LanguagePrimitives.ConvertToWMIClass(Object valueToConvert, Type resultType, Boolean recursion, PSObject originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
Actually, I could register __EventFilter, __EventConsumer and __FilterToConsumerBinding at first.
However, after trying some commands related to register and unregister WMI (Sorry I didn't remember what commands I tried...), I couldn't register __EventConsumer anymore, even though I tried to reboot PC and unregister all of them, I still get the exception like above.
you can try something like this instead to create a new instance in the CommandLineEventConsumer Class. The same will go for Filters and Consumer Binding.
$Properties = #{
"Name"="Test"
"CommandLineTemplate"="C:\Windows\Notepad.exe"
}
New-CimInstance -Namespace 'ROOT\subscription' -ClassName 'CommandLineEventConsumer' -Arguments $Properties

Cannot create com object - Powershell

Below is the msg while creating a New-Object (Powershell)
I tried opening Powershell
as Admin
32bit ISE
64bit ISE
Nothing helped
> New-Object : Retrieving the COM class factory for component with CLSID
> {00000000-0000-0000-0000-000000000000} failed due to the following
> error: 80040154 Class not registered (Exception from HRESULT:
> 0x80040154 (REGDB_E_CLASSNOTREG)). At line:1 char:8
> + $obj = New-Object -ComObject Microsoft.SMS.Client -Strict
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : ResourceUnavailable: (:) [New-Object], COMException
> + FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand
I was able find alternative way to set the site code which I was trying to earlier with the com-object and fix the issue. but still not sure what is wrong with the above method

How can I resume suspended jobs using powershell using BITS command?

For BITS Transfer on Windows, There are some JOBIDS whose TransferType is "upload" and JobState is "Suspended". I am executing below command from PowerShell :-
Get-BitsTransfer | Resume-BitsTransfer
I am getting below error :-
Resume-BitsTransfer : Exception from HRESULT: 0x80200003 At line:1
char:20
+ Get-BitsTransfer | Resume-BitsTransfer
+ ~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Microsoft.Backg...agement.BitsJob:BitsJob) [Resume-BitsTransfer], COM
Exception
+ FullyQualifiedErrorId : ResumeBitsTransferCOMException,Microsoft.BackgroundIntelligentTransfer.Management.Resume
BitsTransferCommand
How can I can resume these jobs.
Any Suggestions...
Thanks..... !!

VisualStudio.DTE.Solution is null using Activator::CreateInstance

I am running the following code in PowerShell ISE:
$scriptDirectory = "C:\Test"
$dteObj = [System.Activator]::CreateInstance([System.Type]::GetTypeFromProgId("VisualStudio.DTE.10.0"))
$slnName = "All"
$dteObj.Solution.Create($scriptDirectory, $slnName)
I get the error:
You cannot call a method on a null-valued expression.
At C:\DevHome\TFS\CreateMasterSolution.ps1:8 char:1
+ $dteObj.Solution.Create($scriptDirectory, $slnName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Why is the Solution Property on this COM Object always "null"? Is there something I am forgetting to do?
In Addition to that do also:
$solution = $dteObj.Solution
$solution.Open("<path to your solution>")
Seems that if you replace the above with the following it works:
$dteObj = New-Object -ComObject "VisualStudio.DTE.10.0"

Resources