How to change an output formed by hashstables Powershell - powershell

I am storing the following query value in a variable:
$unquotedPaths = Get-WmiObject -Class Win32_Service | Select-Object -Property Name,DisplayName,PathName,StartMode | Select-String "auto"
The problem starts when i print that variable becouse the variable takes from the query an object which is formed by hashtables like in this output:
PS C:\Users\pc> Get-WmiObject -Class Win32_Service | Select-Object -Property Name,DisplayName,PathName,StartMode | Select-String "auto"
#{Name=AGMService; DisplayName=Adobe Genuine Monitor Service; PathName="C:\Program Files (x86)\Common Files\Adobe\AdobeGCClient\AGMService.exe"; StartMode=Auto}
#{Name=AGSService; DisplayName=Adobe Genuine Software Integrity Service; PathName="C:\Program Files (x86)\Common Files\Adobe\AdobeGCClient\AGSService.exe"; StartMode=Auto}
#{Name=asComSvc; DisplayName=ASUS Com Service; PathName=C:\Program Files (x86)\ASUS\AXSP\1.01.02\atkexComSvc.exe; StartMode=Auto}
#{Name=AudioEndpointBuilder; DisplayName=Compilador de extremo de audio de Windows; PathName=C:\WINDOWS\System32\svchost.exe -k LocalSystemNetworkRestricted -p; StartMode=Auto}
How i can get and output like this:
Name DisplayName PathName Startmode
---------- ------------- ------------ ------------
ExampleName ExampleDisplayName C:\Example Auto

Select-String is meant to search and match patterns among strings and files, If you need to filter an object you can use Where-Object:
$unquotedPaths = Get-WmiObject -Class Win32_Service |
Where-Object StartMode -EQ Auto |
Select-Object -Property Name,DisplayName,PathName,StartMode
If the filtering required more complex logic you would need to change from Comparison Statement to Script Block, for example:
$unquotedPaths = Get-WmiObject -Class Win32_Service | Where-Object {
$_.StartMode -eq 'Auto' -and $_.State -eq 'Running'
} | Select-Object -Property Name,DisplayName,PathName,StartMode

Related

How to take a powershell output and copy files to it?

I am trying to copy files to any local drive with volume named "Data", but I am unsure how to parse out the drive letter for the copy.
This is the line I am using to grab the volumes:
$drive=Get-WmiObject -class Win32_logicaldisk |
Where-Object {$_.VolumeName -eq "Data"} |
select DeviceID
Then I want to do an xcopy from c:\temp to $drive/backupfolder (this is where it fails as $drive shows
DeviceId
--------
D:
$drive isn't a string. But an Object with the property DeviceId which is a string. You can either expand the property
$drive = Get-WmiObject -Class Win32_logicaldisk |
Where-Object {$_.VolumeName -eq "Data"} |
Select-Object -ExpandProperty DeviceID
Or expand the property this way:
$drive = (Get-WmiObject -Class Win32_logicaldisk | Where-Object {$_.VolumeName -eq "Data"}).DeviceID
Or reference the property on the variable:
"$($drive.DeviceID)\backupfolder"

Get-ADComputer | Get-Process

When I run this:
Get-Process -name csrss -ComputerName (
Get-AdComputer -Filter {
(name -eq "gate") -or (name -eq "client")
} | Select-Object -ExpandProperty name
) | Select-Object Name,MachineName
or
Get-Process -name csrss -ComputerName gate,client | Select-Object Name,MachineName
I get selected processes from the two computers:
Name MachineName
---- -----------
csrss CLIENT
csrss GATE
csrss CLIENT
csrss GATE
But when I run this:
Get-AdComputer -Filter {(name -eq "gate") -or (name -eq "client")} |
Select-Object #{Name='computername';Expression={$_.name}} |
Get-Process -name csrss |
Select-Object name,machinename
I get this output:
Name MachineName
---- -----------
csrss GATE
csrss GATE
If i change name client to DC (it's a localhost) it shows processes only from DC. And it doesn't matter in which order I type the computer names (GATE first or DC first).
Even if I type this:
Get-AdComputer -Filter * |
Select-Object #{Name='computername';Expression={$_.name}} |
Get-Process -name csrss |
Select-Object name,machinename
I get output only from one machine (DC=localhost):
Name MachineName
---- -----------
csrss DC
csrss DC
Why does this happen? Why do I get processes only from one machine?
I can't get the logic, how Get-Process is getting ComputerName in the third case.
You are having difficulties because Get-ADComputer is returning two objects rather than one object with a two value array for computername. Here are four scenarios to illustrate the difference:
# One Object, two value property
[pscustomobject]#{computername="GATE","CLIENT"} |
Get-Process csrss
# Two Objects, one value property
[pscustomobject]#{computername="GATE"},[pscustomobject]#{computername="CLIENT"} |
Get-Process csrss
# Two Objects, one value property using a ForEach-Object
[pscustomobject]#{computername="GATE"},[pscustomobject]#{computername="CLIENT"} |
ForEach-Object { Get-Process csrss -Computername $_.Computername}
# Two Objects, one value property using a ForEach-Object with a nested pipe
[pscustomobject]#{computername="GATE"},[pscustomobject]#{computername="CLIENT"} |
ForEach-Object { $_ | Get-Process csrss}
Applying this concept to your code would look like this:
Get-AdComputer -Filter {(name -eq "gate") -or (name -eq "client")} |
Select-Object #{Name='computername';Expression={$_.name}} |
ForEachObject {
Get-Process -name csrss -Computername $_.Computername |
Select-Object name,machinename
}
Or alternatively using the pipeline inside the ForEach-Object
Get-AdComputer -Filter {(name -eq "gate") -or (name -eq "client")} |
Select-Object #{Name='computername';Expression={$_.name}} |
ForEachObject { $_ |
Get-Process -name csrss |
Select-Object name,machinename
}

Remove column name from PowerShell select-object results

Overall my goal is to get the VNC version for a list of remote computers along with the uninstall GUID so I can remotely uninstall VNC Viewer from certain computers. I have used the Get-WmiObject -Class Win32_Product but that is extremely slow.
I have the following script but in the results it includes the name of the select-object parameter.
$computers = Get-Content -Path "C:\Computers.txt"
$Results = #()
ForEach ($Computer in $Computers) {
$Results += New-Object PSObject -Property #{
"ComputerName" = $Computer
"Name" = Invoke-Command -ComputerName $Computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* } `
| Where-Object -FilterScript {$_.DisplayName -like "VNC V*"} | select-object DisplayName
"DisplayVersion" = Invoke-Command -ComputerName $Computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* } `
| Where-Object -FilterScript {$_.DisplayName -like "VNC V*"} | select-object DisplayVersion
"ModifyPath" = Invoke-Command -ComputerName $Computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* } `
| Where-Object -FilterScript {$_.DisplayName -like "VNC V*"} | select-object ModifyPath
"Vendor" = Invoke-Command -ComputerName $Computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* } `
| Where-Object -FilterScript {$_.DisplayName -like "VNC V*"} | select-object Publisher
}
}
$Results | Select-Object ComputerName,Name,DisplayVersion,ModifyPath,Vendor | Sort-Object ComputerName | Export-Csv C:\VNC.csv -notype ;
My results look like this:
ComputerName : ComputerName
Name : #{DisplayName=VNC Viewer 5.2.3}
DisplayVersion : #{DisplayVersion=5.2.3}
ModifyPath : #{ModifyPath=MsiExec.exe /I{18B1E36F-0DA3-4FDA-BC57-DD815B0DF3B2}}
Vendor : #{Publisher=RealVNC Ltd}
I would want it to look like this:
ComputerName : ComputerName
Name : VNC Viewer 5.2.3
DisplayVersion : 5.2.3
ModifyPath : MsiExec.exe /I{18B1E36F-0DA3-4FDA-BC57-DD815B0DF3B2}
Vendor : RealVNC Ltd
Is this possible or am I going about this script entirely wrong? I haven't figured out a way to run this Invoke-Command for multiple parameters and still output the results in individual columns any other way.
This script works but takes forever for 100's of computers:
if (Test-Path C:\VNCInstalled.csv) {Remove-Item C:\VNCInstalled.csv}
if (Test-Path C:\Computers.txt) {Remove-Item C:\Computers.txt}
$DirSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi]'')
$DirSearcher.Filter = '(&(objectClass=Computer)(!(cn=*esx*)) (!(cn=*slng*)) (!(cn=*dcen*)) )'
$DirSearcher.FindAll().GetEnumerator() | sort-object { $_.Properties.name } `
| ForEach-Object { $_.Properties.name }`
| Out-File -FilePath C:\Computers.txt
Get-Content -Path c:\Computers.txt `
| ForEach-Object {Get-WmiObject -Class Win32_Product -ComputerName $_} `
| Where-Object -FilterScript {$_.Name -like "VNC V*"} `
| select-object #{Name="ComputerName";Expression={$_.PSComputerName}},
Name,
#{Name="InstallLocation";Expression={$_.PackageCache}},
Vendor,
Version,
#{Name="GUID";Expression={$_.IdentifyingNumber}} `
| Sort-Object ComputerName `
| Export-CSV -path c:\VNCInstalled.csv -notype
Change all of your Select-Object commands to Select-Object
-ExpandProperty PropertyName, to discard the property name / column header.
This is the answer I gave three years ago and I think it was really a poor answer. Let me do a better job now.
Why your current code is slow
Your current code enumerates all machines from AD and puts them in a file called Computers.txt. Simple, and you do it fine.
Next up, your code performs this operation:
Get-Content -Path c:\Computers.txt |
ForEach-Object {Get-WmiObject -Class Win32_Product -ComputerName $_} `
| Where-Object -FilterScript {$_.Name -like "VNC V*"} [...]
This can be summarized as 'For each computer, request the full Win32_product table, and then after that, filter down to apps named VNC.' This is HUGELY performance impacting and for a few reasons.
Even on a fast modern computer, querying Win32_Product will take 30 seconds or more, because it returns every application installed. (on a new VM for me it took more than a minute with just a handful of apps installed!)
Querying Win32_Product also has this fun quirk which makes it take even longer, quoted from MSDN Documentation on the Win32_Product Class
Warning Win32_Product is not query optimized. Queries such as "select * from Win32_Product where (name like 'Sniffer%')" require WMI to use the MSI provider to enumerate all of the installed products and then parse the full list sequentially to handle the “where” clause. This process also initiates a consistency check of packages installed, verifying and repairing the install. With an account with only user privileges, as the user account may not have access to quite a few locations, may cause delay in application launch and an event 11708 stating an installation failure. For more information, see KB Article 794524.
So to summarize, querying Win32_Product is slow, AND it also triggers a consistency chceck on every app, AND we also have this query written to retrieve every single app before filtering. These add up to a process which probably takes ~3 minutes per pc, and will operate serially (one after the other) and take forever.
How to fix it
Software info can be retrieved reliably in two places:
If you have SCCM/ConfigMgr installed on your devices, it adds the Win32_AddRemoveProgram WMI Class you can query, which is a super fast version of Win32_Product
If not, we can always retrieve info from the registry.
Here's a short snippet to get applications like VLC installed on a computer (I don't have VNC like you, so I'm making due)
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-object DisplayName -like "VLC*" |Select-Object DisplayName, DisplayVersion, Publisher, InstallDate,UninstallString
DisplayName : VLC media player
DisplayVersion : 3.0.8
Publisher : VideoLAN
InstallDate :
UninstallString : "C:\Program Files (x86)\VideoLAN\VLC\uninstall.exe"
This operation is much faster, only 400 MS or so. Sadly we cannot get much faster using the registry as it has a very weird PowerShell provider that doesn't implement the -Filter parameter, so we do have to retrieve all programs and then filter to our desired choice.
Updating your script to use this function instead
I took the liberty of rewriting your script to use this approach, and restructured it a bit for better readability.
$results = New-object System.Collections.ArrayList
$computers = Get-Content -Path c:\Computers.txt
foreach ($computer in $computers){
#get VNC entries from remote computers registry
$VNCKeys = Invoke-Command -ComputerName $computer -ScriptBlock {
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
Where-object DisplayName -like "VNC V*" |
Select-Object DisplayName, DisplayVersion, Publisher, UninstallString, #{Name=‘ComputerName‘;Expression={$computer}}
}#end of remote command
if ($VNCKeys -ne $null){
forEach($VNCKey in $VNCKeys){
[void]$results.Add($VNCKey)
}
}
}
$results | Sort-Object ComputerName | Export-CSV -path c:\VNCInstalled.csv -NoTypeInformation

Only shows one computer name instead of many systems in servers.txt

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.

How to format the output so that they are all aligned in the .log file?

I am working on a script for my college assignment that basically gathers your computer information and outputs it to a .log file. I've written the script already but when it outputs the information to the .log file, the Installed Software Names, Installed Software GUIDs, and the name of all users in the computer are listed like this:
But I want it to look like this:
Anyway I can edit my script to make it like this? Here's my script:
#Checking For Log File
$LogLocation = "$Home\Desktop\"
$LogFile = "Baabbasi.log"
$TestPathResult = Test-Path $Home\Desktop\Baabbasi.log
If ($TestPathResult -eq "False") {New-Item -Path $LogLocation -Name $LogFile -ItemType File}
#The Process After
Clear-Host
$TodaysDate = Get-Date
$ComputerName = $env:ComputerName
$BiosName = Get-WMIObject Win32_BIOS | Select-Object -ExpandProperty Name
$BiosVersion = Get-WMIObject Win32_BIOS | Select-Object -ExpandProperty Version
$HDSizes = Get-WMIObject Win32_LogicalDisk -filter "DriveType=3" | Select-Object #{Name="size(GB)";Expression={"{0:N2}" -f($_.size/1gb)}}
$TotalHDSize = ($HDSizes | Measure-Object "size(GB)" -Sum).Sum
$PhysicalMemory = (Get-WMIObject Win32_PhysicalMemory).Capacity
$PhysicalMemoryinGB = $PhysicalMemory/1gb
$OSVersion = (Get-WmiObject -Class Win32_OperatingSystem).Version
$OSName = $env:OS
$InstalledSoftwareNames = Get-WMIObject Win32_Product | Select-Object -ExpandProperty Name | Out-String
$InstalledSoftwareGUID = Get-WMIObject Win32_Product | Select-Object -ExpandProperty IdentifyingNumber| Out-String
$LatestHotfix = Get-Hotfix | select-object HotFixID,InstalledOn | Sort-Object InstalledON -descending | Select -first 1 | Select-Object -ExpandProperty HotfixID
$UserAccount = [Environment]::UserName
$AllUserAccounts = Get-WmiObject Win32_UserAccount | Select-Object -ExpandProperty Name | Out-String
Add-Content $Home\Desktop\Baabbasi.log "
Date: $TodaysDate
======================================================================
Computer Name: $ComputerName
================ ======================================================
BIOS Name: $BiosName
BIOS Version: $BiosVersion
HD Size: $TotalHDSize GB
RAM Size: $PhysicalMemoryinGB GB
Operating System: $OSName
Operating System Version: $OSVersion
Installed Software Name:
$InstalledSoftwareNames
Installed Software GUID:
$InstalledSoftwareGUID
Last Installed Hot Fix: $LatestHotfix
Name of Registered System User: $UserAccount
Names of All Registered System Users on the System:
$AlluserAccounts
========================================================================
========================================================================
"
Change the statement
$InstalledSoftwareGUID = Get-WMIObject Win32_Product |
Select-Object -ExpandProperty IdentifyingNumber| Out-String
to something like this:
$InstalledSoftwareGUID = Get-WMIObject Win32_Product |
Select-Object -ExpandProperty IdentifyingNumber |
% { (' ' * 20) + $_ } | Out-String
That will prepend each GUID with 20 spaces (adjust the number to your desired indention depth) before converting the list to a single string.