Powershell Exception issue - powershell

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

Related

Powershell Call cancelled

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.

The server is unwilling to process request

I am trying use powershell to add OU called Calder under an OU called Branches but I keep getting the error New-ADOrganizationalUnit : The server is unwilling to process the request., Also I am running powershell as a admin
Here is what I put in powershell
New-ADOrganizationalUnit "Calder" -Path "OU=Branches, DC=company.epl, DC=local
Here is the full error
New-ADOrganizationalUnit : The server is unwilling to process the
request At line:1 char:1
+ New-ADOrganizationalUnit "Calder" -Path "OU=Branches, DC=company.epl …
+ + CategoryInfo :NotSpecified: (OU=Calder, OU+Br...y.epl, DC=local:Strin g) [New-ADOrganizationalUnit] :
ActiveDirectoryServer:O,Microsoft.ActiveDirectory.Management.Commands.NewADOrganizationalUnit
I've generally seen this error when I've got my fully qualified DN mistyped. If that is the case, using a search to grab the intended OU object helps.
PS> $MYOU = Get-ADOrganizationalUnit -filter 'Name -like "Branches"'
PS> $MYOU.DistinguishedName
OU=Branches,dc=MyCompany,dc=ccTLD
PS> New-ADOrganizationalUnit "Calder" -Path $MYOU.DistinguishedName
PS> Get-ADOrganizationalUnit -filter 'Name -like "Calder"'
City :
Country :
DistinguishedName : OU=Calder,OU=Branches,dc=MyCompany,dc=ccTLD
LinkedGroupPolicyObjects : {}
ManagedBy :
Name : Calder
ObjectClass : organizationalUnit
ObjectGUID : 559c4242-505a-c165-15d5-562b5fb99103
PostalCode :
State :
StreetAddress :
If it's not just an incorrect OU path, try appending -Verbose to the command and see if there's a better indication of what exactly went awry.

Trying to Create a script that will get my filtered list of Get-Adcomputer then run a command on each

Firstly,
I am very new to powershell. Everytime I think i get the logic i go WTF.. If this was bash it would be so easy etc..
what am I trying to do exactly ...
Get all computers from AD that Meet the Xiopwb* criteria. Once i have the list I need to change the permissions on the \\Xiopwb20\Nsiwebroot Directory to ONLY INCLUDE Domain Administrators and A Security group "webadmins"
My Logic:
Get all computers from AD that meet Xio*PWB*
Take just the NAME of objects in that list
for ever "name" in that list do Get-ACL \\Name from list\Nsiwebroot
remove *
add user / group.
What I have:
PS C:\Windows\system32> Get-ADComputer -filter * | Where-Object {$_.Name -like "xiopwb*"} | Select Name | ForEach-Object { Get-Acl \\$_.Name\nsiwebroot}
all up to the "ForEach" works... I get just the names of the PC's that I need etc..
Simple as possible I don't need a 100 line script.
Thanks
** update **
it is double \ its just not showing it... no idea why
Looks like it is doing what I want to a degree. However its spitting out the format funky. #{Name=XIOPWB09}
PS C:\Windows\system32> Get-ADComputer -filter * | Where-Object {$_.Name -like "xiopwb*"} | Select Name | ForEach-Object {get-acl "\\$_\D$\nsiwebroot"}
get-acl : Cannot find path '\#{Name=XIOPWB09}\D$\nsiwebroot' because it does not exist.
At line:1 char:99
+ ... opwb*"} | Select Name | ForEach-Object {get-acl "\$_\D$\nsiwebroot"}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException
+ FullyQualifiedErrorId : GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand
get-acl : Cannot find path '\#{Name=XIOPWB06}\D$\nsiwebroot' because it does not exist.
At line:1 char:99
+ ... opwb*"} | Select Name | ForEach-Object {get-acl "\$_\D$\nsiwebroot"}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-Acl], ItemNotFoundException
+ FullyQualifiedErrorId : GetAcl_PathNotFound_Exception,Microsoft.PowerShell.Commands.GetAclCommand
"Select Name" returns an Object with Table Header Name. "Select -ExpandProperty Name" is What needed here, which will convert it o String.
Regards,
kvprasoon

ErrorVariable output not as expected

First, here is my code:
$InputPath = "\\Really\long\path\etc"
Get-ChildItem -Path $InputPath -Recurse -Force -ErrorVariable ErrorPath
$ErrorPath | select TargetObject
The problem I am facing is with the ErrorVariable parameter. Paths that are too long for Get-ChildItem to process are stored there (typically around 250+ characters). When I pipe $ErrorPath to select, the output looks like this:
TargetObject : \\Really\long\path\etc\1
TargetObject : \\Really\long\path\etc\2
TargetObject : \\Really\long\path\etc\3
However, if I run that last line again (either by running selection or by manually typing it in), the output changes to this:
TargetObject
------------
\\Really\long\path\etc\1
\\Really\long\path\etc\2
\\Really\long\path\etc\3
I am at a loss as to how to explain this. I prefer the second output, but I don't know why it is different from the first to the second time. Any ideas?
When there are multiple types of objects in a pipeline the first object type determines the formatting for the rest of the objects. If you ran your commands individually on the command prompt you wouldn't see this. Each line starts a new pipeline. However when you run these commands in a script, the whole script is executed as a pipeline. To work around this use Out-Default e.g.:
$InputPath = "\\Really\long\path\etc"
Get-ChildItem $InputPath -Recurse -Force -ErrorVariable ErrorPath
$ErrorPath | select TargetObject | Out-Default
The former output is in list format, the latter in table format. You can enforce one or the other by piping your data into the Format-List or Format-Table cmdlet respectively:
PS C:\> $ErrorPath | select TargetObject | Format-List
TargetObject : \\Really\long\path\etc\1
TargetObject : \\Really\long\path\etc\2
TargetObject : \\Really\long\path\etc\3
PS C:\> $ErrorPath | select TargetObject | Format-Table
TargetObject
------------
\\Really\long\path\etc\1
\\Really\long\path\etc\2
\\Really\long\path\etc\3

Why don't errors get returned when calling properties that don't exist?

Given the following snippet
$drives = Get-PSDrive
foreach($drive in $drives)
{
Write-Host $drive.Name "`t" $drive.Root
Write-Host " - " $drive.Free "`t" $drive.PropertyDoesntExist
}
The drive.PropertyDoesntExist property doesn't... erm... exist so I would expect an error to be thrown but instead it returns a null.
How can I get errors or exceptions?
EDIT - Me bad - I asked 2 questions in one so I moved one into a separate question.
The NextHop Blog provides a good solution to this problem. It doesn't give you an error, but instead a boolean. You can use Get-Member to get a collection of all of the real properties of the object's type and then match for your desired property.
Here's an example for strings:
PS C:\> $test = "I'm a string."
PS C:\> ($test | Get-Member | Select-Object -ExpandProperty Name) -contains "Trim"
True
PS C:\> ($test | Get-Member | Select-Object -ExpandProperty Name) -contains "Pigs"
False
If you explicitly want an error, you may want to look into Set-Strictmode as Set-StrictMode -version 2 to trap non-existent properties. You can easily turn it off when you're done with it, too:
PS C:\> Set-StrictMode -version 2
PS C:\> "test".Pigs
Property 'Pigs' cannot be found on this object. Make sure that it exists.
At line:1 char:8
+ "test". <<<< Pigs
+ CategoryInfo : InvalidOperation: (.:OperatorToken) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFoundStrict
PS C:\> Set-StrictMode -off