What I'm trying to do is look at some processes and get a list of the user of these processes. ANd the following code worked fine for me.
get-wmiobject win32_process |
where{$_.name -like "*notepad*"}|sort {$_.CommandLine}|
select #{n="User";e={$_.getowner().user}},#{n="ProcessID";e={$_.ProcessID}},{$_.CommandLine} |ft -AutoSize |Out-String -Width 300 >> C:\ListUsers.txt
Somehow I wanted to split the $_.CommandLine string in the middle of way, and output some of the split arrary(see the following code for a better idea, although the code is wrong). But the updated code just output nothing into the text file. I think I must be using the select-object or fommat-object wrong, but i don't know how i can fix it.
get-wmiobject win32_process |
where{$_.name -like "*notepad*"}|sort {$_.CommandLine}|
%{
$split = $_.CommandLine.split("\")
select #{n="User";e={$_.getowner().user}},#{n="ProcessID";e={$_.ProcessID}},#{n="Ihub";e=$split[3]},#{n="version";e=$split[3]},#{n="version";e=$split[3]} |
ft -AutoSize |Out-String -Width 300 >> C:\ListUsers.txt
}
Can anyone advise? Thanks!!
You don't need to use select and then format-table. Format-table can create calculated properties too. Also, you forgot to wrap the $split[3] in a scriptblock. I removed the two "version" properties because they were identical to "Ihub".
Try this(untested):
get-wmiobject win32_process |
where{$_.name -like "*notepad*"}|sort {$_.CommandLine} |
Format-Table -Property #{n="User";e={$_.getowner().user}},#{n="ProcessID";e={$_.ProcessID}},#{n="Ihub";e={($_.CommandLine.split("\"))[3]}} -AutoSize |
Out-String -Width 300 >> ListUsers.txt
Related
When I look at the Win32_ComputerSystem class, it shows loads of properties like Status, PowerManagementCapabilities, etc. However, when in PowerShell I do the below I only get back a couple:
PS C:\Windows\System32\drivers> Get-WmiObject -Class "Win32_computersystem"
Domain : YYY.com
Manufacturer : VMware, Inc.
Model : VMware Virtual Platform
Name : LONINEGFQEF58
PrimaryOwnerName : Authorised User
TotalPhysicalMemory : 2147016704
How can I see all properties?
Try this:
Get-WmiObject -Class "Win32_computersystem" | Format-List *
Get-WmiObject -Class "Win32_computersystem" | Format-List -Property *
For certain objects, PowerShell provides a set of formatting instructions that can affect either the table or list formats. These are usually meant to limit the display of reams of properties down to just the essential properties. However there are times when you really want to see everything. In those cases Format-List * will show all the properties. Note that in the case where you're trying to view a PowerShell error record, you need to use "Format-List * -Force" to truly see all the error information, for example,
$error[0] | Format-List * -force
Note that the wildcard can be used like a traditional wilcard this:
Get-WmiObject -Class "Win32_computersystem" | Format-List M*
If you want to know what properties (and methods) there are:
Get-WmiObject -Class "Win32_computersystem" | Get-Member
You can also use:
Get-WmiObject -Class "Win32_computersystem" | Select *
This will show the same result as Format-List * used in the other answers here.
I like
Get-WmiObject Win32_computersystem | format-custom *
That seems to expand everything.
There's also a show-object command in the PowerShellCookbook module that does it in a GUI. Jeffrey Snover, the PowerShell creator, uses it in his unplugged videos (recommended).
Although most often I use
Get-WmiObject Win32_computersystem | fl *
It avoids the .format.ps1xml file that defines a table or list view for the object type, if there are any. The format file may even define column headers that don't match any property names.
The most succinct way to do this is:
Get-WmiObject -Class win32_computersystem -Property *
You can list all properties of object using Four ways
Method-1: Format-Table
Get-Process | Format-Table -Property * -Wrap | Out-File abc.txt -Width 5000
OR
Get-Process | Format-Table * -Wrap | Out-File abc.txt -Width 5000
OR
Get-Process | FT * -Wrap | Out-File abc.txt -Width 5000
Method-2: Format-List
Get-Process | Format-List -Property *
OR
Get-Process | Format-List *
OR
Get-Process | FL *
Method-3: ConvertTo-Html
Get-Process | ConvertTo-Html | Out-File services1.html ; invoke-item services1.html
Method-4: Out-GridView
Get-Process | Select * | Out-GridView
Comparision of results to show parameters usage:
Format-Table/Format-List If you want to include all columns then always use -Property * parameter
Format-Table always capture output to a file using Out-File because sometime not all columns are included if you show result on screen.
FormatTable always specify reasonable width using -Width parameter otherwise column values are truncated in result.
Format-Table always use -Wrap so that column with large text is not trimmed but is shown in multiple line in long column.
CovertTo-Html properties with collections will only display Type Name of Collection insted of comma seperated values of collection items. This display is bit different from how Format-Table, Format-List & ConvertTo-Html display property with collection
This question already has answers here:
How to get an object's property's value by property name?
(6 answers)
Closed 5 years ago.
I am working on a script which takes Hostnames from a CSV, Files them against Get-ADComputer and then saves certain Objects in certain columns of the original CSV.
While the solution seems like a basic Task (code below), my problem is, that the Output of Get-ADComputer always (you can see I played around with Out-String but also tried other formatting options) contains a lot of NewLine characters or other formatting issues which make the CSV confusing.
Clear-Host
Import-Module ActiveDirectory
$import = Import-Csv 'XXX' -Delimiter ';'
Foreach ($row in $import){
$hostname = $row.HOSTNAME
if($hostname.length -gt 3){
$computer = Get-ADComputer -Filter {Name -like $hostname} -Properties LastLogonDate, LastLogonTimeStamp
$row.AD_LastLogon.ToString() = $computer | Select-Object LastLogonDate | Select-Object -first 1 | FT -HideTableHeaders | Out-String
$row.AD_LLTimestamp = $computer | Select LastLogonTimestamp |Select-Object -first 1 | FT -HideTableHeaders | Out-String
}
}
$import | Export-Csv 'XXX' -Delimiter ';' -NoType
My question now is, if anyone could help with a method to get the bare string result of for example Get-ADComputer's LastLogonDate, without any formatting or headers included.
Thanks in advance!
Use the -ExpandProperty parameter of Select-Object to extract just the parameter you want. You can only specify one parameter to exapand at a time.
$row.AD_LastLogon = $computer | Select-Object -ExpandProperty LastLogonDate -First 1 | Out-String
$row.AD_LLTimestamp = $computer | Select-Object -ExpandProperty LastLogonTimestamp -First 1
I don't believe the -First 1 should be necessary. Get-ADComputer shouldn't be finding multiple computers with the same name.
Also, you shouldn't need to retrieve both LastLogonDate and LastLogonTimestamp. The former is the same value as the latter, just converted to a DateTime from the irritating NT Time Epoch that LastLogonTimestamp uses. Have you got a system that requires both?
Finally, just a note but this:
$row.AD_LastLogon.ToString() = $computer | [...]
It doesn't make sense. You can't assign a value to a method. I would be surprised if that didn't error or otherwise do nothing at all.
I am trying to run this simple script to get the services and the accounts that are running them. My problem is that the data looks correct in the report but the server name does not change in the report. Here is the code.
$servers = get-content C:\temp\servers.txt
foreach ($server in $servers)
{
Get-WmiObject win32_service | Select-Object -Property SystemName, DisplayName, startname | format-list -GroupBy startname | Out-File c:\temp\results.txt
}
This will work.
$servers = get-content C:\temp\servers.txt
foreach ($server in $servers)
{
Get-WmiObject win32_service -Computername $server | Select-Object -Property SystemName, DisplayName, startname | format-list -GroupBy startname | Out-File -append c:\temp\results.txt
}
You can also use the following but note SystemName is not a property of Win32_Service. To troubleshoot this, try using Get-Service | Select -first 1 | Get-Member will display the available attributes (sorry if this is the wrong term) with the important one being MachineName thus replace SystemName for MachineName and you'll get the desired results. Look up Hey Scripting Guy articles for further information. For example, this page
gc .\Servers.txt | foreach {get-service -ComputerName $_ | `
Select-Object -Property MachineName, DisplayName, startname | `
format-list -GroupBy startname | Out-File -append c:\temp\results.txt}
Note, I'm using the backtick ` to make the command readable, paste into the Powershell ISE to save/run the script or just paste the lines into the console and press enter twice to run the multi-line script.
When I look at the Win32_ComputerSystem class, it shows loads of properties like Status, PowerManagementCapabilities, etc. However, when in PowerShell I do the below I only get back a couple:
PS C:\Windows\System32\drivers> Get-WmiObject -Class "Win32_computersystem"
Domain : YYY.com
Manufacturer : VMware, Inc.
Model : VMware Virtual Platform
Name : LONINEGFQEF58
PrimaryOwnerName : Authorised User
TotalPhysicalMemory : 2147016704
How can I see all properties?
Try this:
Get-WmiObject -Class "Win32_computersystem" | Format-List *
Get-WmiObject -Class "Win32_computersystem" | Format-List -Property *
For certain objects, PowerShell provides a set of formatting instructions that can affect either the table or list formats. These are usually meant to limit the display of reams of properties down to just the essential properties. However there are times when you really want to see everything. In those cases Format-List * will show all the properties. Note that in the case where you're trying to view a PowerShell error record, you need to use "Format-List * -Force" to truly see all the error information, for example,
$error[0] | Format-List * -force
Note that the wildcard can be used like a traditional wilcard this:
Get-WmiObject -Class "Win32_computersystem" | Format-List M*
If you want to know what properties (and methods) there are:
Get-WmiObject -Class "Win32_computersystem" | Get-Member
You can also use:
Get-WmiObject -Class "Win32_computersystem" | Select *
This will show the same result as Format-List * used in the other answers here.
I like
Get-WmiObject Win32_computersystem | format-custom *
That seems to expand everything.
There's also a show-object command in the PowerShellCookbook module that does it in a GUI. Jeffrey Snover, the PowerShell creator, uses it in his unplugged videos (recommended).
Although most often I use
Get-WmiObject Win32_computersystem | fl *
It avoids the .format.ps1xml file that defines a table or list view for the object type, if there are any. The format file may even define column headers that don't match any property names.
The most succinct way to do this is:
Get-WmiObject -Class win32_computersystem -Property *
You can list all properties of object using Four ways
Method-1: Format-Table
Get-Process | Format-Table -Property * -Wrap | Out-File abc.txt -Width 5000
OR
Get-Process | Format-Table * -Wrap | Out-File abc.txt -Width 5000
OR
Get-Process | FT * -Wrap | Out-File abc.txt -Width 5000
Method-2: Format-List
Get-Process | Format-List -Property *
OR
Get-Process | Format-List *
OR
Get-Process | FL *
Method-3: ConvertTo-Html
Get-Process | ConvertTo-Html | Out-File services1.html ; invoke-item services1.html
Method-4: Out-GridView
Get-Process | Select * | Out-GridView
Comparision of results to show parameters usage:
Format-Table/Format-List If you want to include all columns then always use -Property * parameter
Format-Table always capture output to a file using Out-File because sometime not all columns are included if you show result on screen.
FormatTable always specify reasonable width using -Width parameter otherwise column values are truncated in result.
Format-Table always use -Wrap so that column with large text is not trimmed but is shown in multiple line in long column.
CovertTo-Html properties with collections will only display Type Name of Collection insted of comma seperated values of collection items. This display is bit different from how Format-Table, Format-List & ConvertTo-Html display property with collection
I want to be able to output data from PowerShell without any column headings. I know I can hide the column heading using Format-Table -HideTableHeaders, but that leaves a blank line at the top.
Here is my example:
get-qadgroupmember 'Domain Admins' | Select Name | ft -hide | out-file Admins.txt
How do I eliminate the column heading and the blank line?
I could add another line and do this:
Get-Content Admins.txt | Where {$_ -ne ""} | out-file Admins1.txt
But can I do this on one line?
In your case, when you just select a single property, the easiest way is probably to bypass any formatting altogether:
get-qadgroupmember 'Domain Admins' | foreach { $_.Name }
This will get you a simple string[] without column headings or empty lines. The Format-* cmdlets are mainly for human consumption and thus their output is not designed to be easily machine-readable or -parseable.
For multiple properties I'd probably go with the -f format operator. Something along the lines of
alias | %{ "{0,-10}{1,-10}{2,-60}" -f $_.COmmandType,$_.Name,$_.Definition }
which isn't pretty but gives you easy and complete control over the output formatting. And no empty lines :-)
A better answer is to leave your script as it was. When doing the Select name, follow it by -ExpandProperty Name like so:
Get-ADGroupMember 'Domain Admins' | Select Name -ExpandProperty Name | out-file Admins.txt
If you use "format-table" you can use -hidetableheaders
add the parameter -expandproperty after the select-object, it will return only data without header.
The -expandproperty does not work with more than 1 object. You can use this one :
Select-Object Name | ForEach-Object {$_.Name}
If there is more than one value then :
Select-Object Name, Country | ForEach-Object {$_.Name + " " + $Country}
Joey mentioned that Format-* is for human consumption. If you're writing to a file for machine consumption, maybe you want to use Export-*? Some good ones are
Export-Csv - Comma separated value. Great for when you know what the columns are going to be
Export-Clixml - You can export whole objects and collections. This is great for serialization.
If you want to read back in, you can use Import-Csv and Import-Clixml. I find that I like this better than inventing my own data formats (also it's pretty easy to whip up an Import-Ini if that's your preference).
First we grab the command output, then wrap it and select one of its properties. There is only one and its "Name" which is what we want. So we select the groups property with ".name" then output it.
to text file
(Get-ADGroupMember 'Domain Admins' |Select name).name | out-file Admins1.txt
to csv
(Get-ADGroupMember 'Domain Admins' |Select name).name | export-csv -notypeinformation "Admins1.csv"
$server = ('*')+(Read-Host -prompt "What Server Context?")+'*'
$Report = (Get-adcomputer -SearchBase "OU=serverou,DC=domain,DC=com" -filter {name -like $server} -SearchScope Subtree|select Name |Sort -Unique Name)
$report.Name | Out-File .\output\out.txt -Encoding ascii -Force
$Report
start notepad .\output\out.txt
Put your server SearchBase in above.
If you are not sure what your server OU is try this function below...
#Function Get-OSCComputerOU($Computername)
{
$Filter = "(&(objectCategory=Computer)(Name=$ComputerName))"
$DirectorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$DirectorySearcher.Filter = $Filter
$SearcherPath = $DirectorySearcher.FindOne()
$DistinguishedName = $SearcherPath.GetDirectoryEntry().DistinguishedName
$OUName = ($DistinguishedName.Split(","))[1]
$OUMainName = $OUName.SubString($OUName.IndexOf("=")+1)
# $Obj = New-Object -TypeName PSObject -Property #{"ComputerName" = $ComputerName
# "BelongsToOU" = $OUMainName
# "Full" = $DistinguishedName}
$Obj = New-Object -TypeName PSObject -Property #{"Full" = $DistinguishedName}
$Obj
}
Makes sure to run the Get-OSCComputerOU Servername with a select -expandproperty Full filter.
Then just plug in the response to the Searchbase...
All thanks to http://www.jaapbrasser.com