Using the example below:
Get-Service | ConvertTo-HTML -Property Name, Status > C:\services.htm
I was wondering if it is possible to alias the property name - the same way you could in SQL:
Example:
Get-Service | ConvertTo-HTML -Property Name AS NEWNAME , Status AS MYNEWSTATUSNAME> C:\services.htm
I know the above syntax wouldn't work... What is the correct way to alias a property name?
How about using select-object?
get-service | select-object -property #{N='MyNewStatus';E={$_.Status}}, #{N='MyNewName';E={$_.Name}} | ConvertTo-HTML > C:\services.htm
The way to alias a property name is to add an AliasPropery to the object.
Get-Service |
foreach {
$_ | Add-Member -MemberType AliasProperty -Name MYNEWSTATUSNAME -Value Status -PassThru
} |
Select Name,MYNEWSTATUSNAME
You could do an intermediate step of creating objects with the property names you want using the new-object cmdlet.
Get-Service | foreach{ new-object PSObject -property #{newname=($_.Name); newstatus=($_.Status)}} | ConvertTo-Html > .\services.htm
Related
I'm working on a quick string of code that allows me to search a specific print server and also its contents such as printers. What I want for it to do is once getting the printer information to be able to find a specific printer using the port name which in this case is an IP address not quite sure if is possible but I haven't found a command that lets me define a search using those values.
Get-Printer -computerName "server01"|select-object -Property Name, PortName
Name PortName
Printer01 X.XX.XXX.X
Prnter02 X.XX.XX.XX
is there a way to be able to find a printer using the Get-Printer commandlet and utilizing the port name to find the specific printer?
I'm just explaining in more detail #JeffZeitlin very correct answer.
Get-Printer - The Get-Printer cmdlet retrieves a list of printers installed on a computer. You can also use Get-Printer to retrieve the properties of a single printer, and then use that information as input into other cmdlets.
Get-Printer | Get-Member - The Get-Member cmdlet gets the members, the properties and methods, of objects.
Get-Printer | get-member
Get-Printer | Select-Object - The Select-Object cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array.
Get-Printer | select-object -Property Name, PortName
Get-Printer | Select-Object | Where-Object - The Where-Object cmdlet selects objects that have particular property values from the collection of objects that are passed to it. For example, you can use the Where-Object cmdlet to select files that were created after a certain date, events with a particular ID, or computers that use a particular version of Windows.
Get-Printer | select-object -Property Name, PortName | where PortName -eq "PORTPROMPT:"
Get-Printer -ComputerName
Get-Printer -ComputerName $env:Computername | select-object -Property Name, PortName | where PortName -eq "PORTPROMPT:"
Scripting Example Get-Printer
$server = "$env:Computername"
$printersportnames = Get-Printer -ComputerName $server | select-object -ExpandProperty PortName
#Write-Host $printersportnames
$results = New-Object System.Collections.ArrayList # Empty Array
ForEach ($printerportname in $printersportnames) {
$printerportname = $printerportname.ToString()
#Write-Host $printerportname
$output = Get-Printer -ComputerName $server | where-object {$_.PortName -eq $printerportname}
$x = $output.Name
$y = $output.PortName
$z = $output.CommunicationStatus
$a = $output.OperatingStatus
$Object = New-Object PSObject
$Object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $x
$Object | Add-Member -Name 'PortName' -MemberType Noteproperty -Value $y
$Object | Add-Member -Name 'CommStatus' -MemberType Noteproperty -Value $z
$Object | Add-Member -Name 'OperStatus' -MemberType Noteproperty -Value $a
$results += $object
}
$results
Get-NetTCPConnection | Select-Object -Property LocalAddress,LocalPort,RemoteAddress,RemotePort,State,#{name='NameofApp';expression={(Get-Process -id $_.OwningProcess).MainModule.FileVersionInfo.FileDescription}} | Format-Table -AutoSize
The above one works perfectly, Here I want to include the Username as well:
I know that Get-Process -IncludeUserName will return the UserName but I don't know how to join this in the above working command.
Using your current query, here is a simple modified approach that will solve your problem:
Get-NetTCPConnection | ForEach-Object {
$process = Get-Process -Id $_.OwningProcess -IncludeUserName
$description = $process.MainModule.FileVersionInfo.FileDescription
$username = $process.UserName
$properties = $_ | Select-Object -Property LocalAddress,LocalPort,RemoteAddress,RemotePort,State
$properties | Add-Member -Name "NameOfApp" -Type NoteProperty -Value $description
$properties | Add-Member -Name "UserName" -Type NoteProperty -Value $username
$properties
} | Format-Table -AutoSize
Explanation:
Pipe Get-NetTCPConnection through to Foreach-Object.
Get the process object with Get-Process, making sure to include User Names with the -IncludeUserName switch.
Store the descriptions and usernames in separate variables. Not necessary, but I split them up for clarity.
Get all the TCP connection properties that can be selected immediately with Select-Object into a System.Management.Automation.PSCustomObject. This uses the default pipeline variable $_ from Foreach-Object, which is basically the current item from GetNetTCPConnection. You can run Get-Help -Name about_Automatic_Variables to find out more about pipeline variables, and Get-Help -Name about_pipelines for finding out more about pipelines. Unfortunately, these Help files don't contain online versions.
Add the NameOfApp and UserName members to the object with Add-Member.
Format into a table with Format-Table and auto size columns with the -AutoSize switch.
You could also use regular foreach enumeration as well:
& {
foreach ($connection in Get-NetTCPConnection) {
$process = Get-Process -Id $connection.OwningProcess -IncludeUserName
$description = $process.MainModule.FileVersionInfo.FileDescription
$username = $process.UserName
$properties = $connection | Select-Object -Property LocalAddress,LocalPort,RemoteAddress,RemotePort,State
$properties | Add-Member -Name "NameOfApp" -Type NoteProperty -Value $description
$properties | Add-Member -Name "UserName" -Type NoteProperty -Value $username
$properties
}
} | Format-Table -AutoSize
The above is wrapping the foreach loop inside a script block, so you need to use the call operator & to run it. You can read more About Operators and About Script Blocks.
In PowerShell, how do you get an object's property value by specifying its name (a string)? I want something like the following:
$obj = get-something
# View the object's members:
$obj | gm
# I could retrieve a property by doing so:
write-host $obj.SomeProp
# But for many purposes, I would really want to:
write-host $obj | Get-PropertyByName "SomeProp"
Is there something similar to "Get-PropertyByName" in PowerShell?
Sure
write-host ($obj | Select -ExpandProperty "SomeProp")
Or for that matter:
$obj."SomeProp"
Expanding upon #aquinas:
Get-something | select -ExpandProperty PropertyName
or
Get-something | select -expand PropertyName
or
Get-something | select -exp PropertyName
I made these suggestions for those that might just be looking for a single-line command to obtain some piece of information and wanted to include a real-world example.
In managing Office 365 via PowerShell, here was an example I used to obtain all of the users/groups that had been added to the "BookInPolicy" list:
Get-CalendarProcessing conferenceroom#example.com | Select -expand BookInPolicy
Just using "Select BookInPolicy" was cutting off several members, so thank you for this information!
You can get a property by name using the Select-Object cmdlet and specifying the property name(s) that you're interested in. Note that this doesn't simply return the raw value for that property; instead you get something that still behaves like an object.
[PS]> $property = (Get-Process)[0] | Select-Object -Property Name
[PS]> $property
Name
----
armsvc
[PS]> $property.GetType().FullName
System.Management.Automation.PSCustomObject
In order to use the value for that property, you will still need to identify which property you are after, even if there is only one property:
[PS]> $property.Name
armsvc
[PS]> $property -eq "armsvc"
False
[PS]> $property.Name -eq "armsvc"
True
[PS]> $property.Name.GetType().FullName
System.String
As per other answers here, if you want to use a single property within a string, you need to evaluate the expression (put brackets around it) and prefix with a dollar sign ($) to declare the expression dynamically as a variable to be inserted into the string:
[PS]> "The first process in the list is: $($property.Name)"
The first process in the list is: armsvc
Quite correctly, others have answered this question by recommending the -ExpandProperty parameter for the Select-Object cmdlet. This bypasses some of the headache by returning the value of the property specified, but you will want to use different approaches in different scenarios.
-ExpandProperty <String>
Specifies a property to select, and indicates that an attempt should
be made to expand that property
https://technet.microsoft.com/en-us/library/hh849895.aspx
[PS]> (Get-Process)[0] | Select-Object -ExpandProperty Name
armsvc
powershell variables
Try this :
$obj = #{
SomeProp = "Hello"
}
Write-Host "Property Value is $($obj."SomeProp")"
Here is an alternative way to get an object's property value:
write-host $(get-something).SomeProp
$com1 = new-object PSobject #Task1
$com2 = new-object PSobject #Task1
$com3 = new-object PSobject #Task1
$com1 | add-member noteproperty -name user -value jindpal #Task2
$com1 | add-member noteproperty -name code -value IT01 #Task2
$com1 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$com2 | add-member noteproperty -name user -value singh #Task2
$com2 | add-member noteproperty -name code -value IT02 #Task2
$com2 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$com3 | add-member noteproperty -name user -value dhanoa #Task2
$com3 | add-member noteproperty -name code -value IT03 #Task2
$com3 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$arr += $com1, $com2, $com3 #Task4
write-host "windows version of computer1 is: "$com1.ver() #Task3
write-host "user name of computer1 is: "$com1.user #Task6
write-host "code of computer1 is: "$com1,code #Task5
write-host "windows version of computer2 is: "$com2.ver() #Task3
write-host "user name of computer2 is: "$com2.user #Task6
write-host "windows version of computer3 is: "$com3.ver() #Task3
write-host "user name of computer3 is: "$com1.user #Task6
write-host "code of computer3 is: "$com3,code #Task5
read-host
Could someone provide a PowerShell script to join two function results based on common key columns.
Example:
Result1 and Result2 has common field 'Name'. I want to join both the results and fetch the below informations.
$Result1 = get-wmiobject -ComputerName localhost -Class win32_service
$Result2 = get-service
Result
Name : wuauserv
DisplayName : Windows Update
Status : Running
StartMode : Manual
ProcessId : 400
Use below PowerShell script to join both the results based on common key column (Name).
$Result1=get-wmiobject -ComputerName localhost -Class win32_service
$Result2=get-service
$Result=#()
for($i=0;$i -lt $Result2.count;$i++)
{
$startmode=($Result1 | where{$_.Name -eq $Result2[$i].Name})|Select StartMode,ProcessId
$tempObj=new-object PSObject
$tempObj | Add-member noteproperty Name $Result2[$i].Name
$tempObj | Add-member noteproperty DisplayName $Result2[$i].DisplayName
$tempObj | Add-member noteproperty Status $Result2[$i].Status
$tempObj | Add-member noteproperty StartMode $startmode.StartMode
$tempObj | Add-member noteproperty ProcessId $startmode.ProcessId
$Result += $tempObj
}
$Result
No need to combine the output of the two commands. All of the properties are already out from the Get-WMIObject. (Personally I like using the CIM cmdlets instead of WMI wherever possible too)
Get-CimInstance Win32_Service | select Name, DisplayName, State, StartMode, ProcessId
Edit: The output of State from gcim is the Status property of Get-Service (Here's a calculated property to fix that, if that's an issue)
Get-CimInstance Win32_Service | select Name, DisplayName, #{Name="Status";Expression={$_.State}}, StartMode, ProcessId
try this
$result=get-wmiobject -ComputerName localhost -Class win32_service | %{ New-Object psobject -Property #{ objectwmi=$_; objectgetservice=(get-service | where name -eq $_.Name | select -first 1)} }
I'm attempting to create a custom PowerShell object using data from the WebAdministration module for IIS7. The object should capture the ClientIPAddress and SiteID from the GetExecuteRequest WmiMethod for Worker Processes in IIS.
$p = Get-WmiObject WorkerProcess -Namespace root\WebAdministration -ComputerName . | Invoke-WmiMethod -Name GetExecutingRequests | Select-Object -ExpandProperty OutputElement
$wpob = #()
foreach($w in $p)
{
$webrequests = New-Object PSObject
$webrequests | Add-Member -Type NoteProperty -Name ClientIP -Value ($w | select -ExpandProperty ClientIPAddress)
$webrequests | Add-Member -Type NoteProperty -Name SiteID -Value ($W | select -ExpandProperty SiteID)
$wpobj += $webrequests
}
The Problem:
Object ($wpobj) contains the 'ClientIP' and 'SiteID' under get-member, but you cannot get those values by using $wpobj.clientip or $wpobj.siteid. Only way I could retrieve those values were to use $wpobj | select clientip or $wpobj | select siteid
Not being able to get the values for the properties in the above mentioned way makes it more difficult to sort/group the data as I can't select the values later on down the pipeline.
Anyone know what I may be missing? I have not seen this before. Only in this particular case
Solution was to upgrade Powershell to V4.0. IE.invoke won't work on earlier versions of Powershell.