I wanted to extract a list of users logged on to remote pc, the ps names would be fed in using a .csv file.
I was able to get a command
Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer | Select Antecedent -Unique
to query the user names, could any one help me more on how to write this code?
Assuming the csv file contains a ComputerName header:
Import-Csv computers.csv | Foreach-Object{
Get-WmiObject Win32_LoggedOnUser -ComputerName $_.ComputerName | Select-Object __SERVER,Antecedent -Unique | Foreach-Object {
$domain,$user = [regex]::matches($_.Antecedent,'="([^"]+)"') | Foreach-Object {$_.Groups[1].Value}
$_ | Select-Object __SERVER,#{Name='Domain';Expression={$domain}},#{Name='User';Expression={$user}}
}
}
Related
I can get list the processes but how would I get them to show by highest usage instead of alphabetically?
Wmic path win32_performatteddata_perfproc_process get Name,PercentProcessorTime
From powershell you don't need to make direct calls to wmic, Get-CimInstance is meant to easily query all instances of WMI and CIM classes and output objects which are easy to manipulate. Sorting objects in PowerShell can be done with Sort-Object.
Get-CimInstance Win32_PerfFormattedData_PerfProc_Process |
Sort-Object PercentPrivilegedTime -Descending |
Select-Object Name, PercentProcessorTime
You could even go one step further and group the objects by their name with the help of Group-Object:
Get-CimInstance Win32_PerfFormattedData_PerfProc_Process |
Group-Object { $_.Name -replace '#\d+$' } | ForEach-Object {
[pscustomobject]#{
Instances = $_.Count
Name = $_.Name
PercentProcessorTime = [Linq.Enumerable]::Sum([int[]] $_.Group.PercentProcessorTime)
}
} | Sort-Object PercentProcessorTime -Descending
Can anyone please correct?
Individual runs of user1 and user 2 running good and appending results
(get-aduser -Identity user1 -Properties memberof | select -expand memberof | get-adgroup) |
select Name, groupscope | Out-File -Append c:\scripts\resultsusersad.txt
(get-aduser -Identity user2 -Properties memberof | select -expand memberof | get-adgroup) |
select Name, groupscope | Out-File -Append c:\scripts\resultsusersad.txt
When I tried to save both users in a text file and used for loop I am getting error.
This is what I did, given below (Update):
$file = Get-Content -path "c:\scripts\usersad.txt"
foreach ($i in $file)
{
(get-aduser -Identity $($i) -Properties memberof | select -expand memberof | get-adgroup) | select Name, groupscope | Add-Content -Path c:\scripts\resultsusersad.txt
}
Please correct where I am doing wrong.
I always have trouble with out-file.
What I would do is:
Either create a new file in the script, or have one already created and waiting.
Variablize the output. Something like
$Var1 = #(user1 -Properties memberof | select -expand memberof | get-adgroup) | select Name, groupscope)
Use 'Add-Content' to write to the file
Add-Content -Path .\myfile.txt -Value $Var1
I it will append the string as a new line right under the previous one. I use to use a similar method to build CSVs from grabbing data from AD.
How do I properly use $_ in out-file? Here's my code:
get-content computers.txt |
Where {$_ -AND (Test-Connection $_ -Quiet)} |
foreach { Get-Hotfix -computername $_ } |
Select CSName,Description,HotFixID,InstalledBy,InstalledOn |
convertto-csv | out-file "C:\$_.csv"
I'm trying to execute a get-hotfix for all the computers listed in the text file then I want them to be exported to CSV with the computer name as the filename.
You need one pipeline to process the computers.txt files, and a nested one inside the foreach to process the list of hotfixes for each computer:
get-content .\computers.txt |
Where {$_ -AND (Test-Connection $_ -Quiet)} |
foreach {
Get-Hotfix -computername $_ |
Select CSName,Description,HotFixID,InstalledBy,InstalledOn |
convertto-csv | out-file "C:\$_.csv"
}
Edit: Changed computers.txt to .\computers.txt, as this is required for local paths in powershell
i can see with this:
get-content .\computers.txt | Where {$_ -AND (Test-Connection $_ -Quiet)} | foreach{ Get-Hotfix -id KB4012212 -computername $_ | Select CSName,Description,HotFixID,InstalledBy,InstalledOn | convertto-csv | out-file "C:\$_.csv" }
i can see only in which PC is the fix (KB4012212) installed.
it's possible to see the following
CSNAME Fix(Inst/NotInst)
PC1 FIxInstalled
PC2 FixNotinstalled
PC3 FixnotInstalled
..
..
etc
I monkeyed with this for a while and nothing I found on-line worked until I used this combo.
I used the method is this thread but it was SO slow and I wanted to learn more about using jobs so this is what ended up working for me on Windows 7 PS Ver 4.
All other options were either too slow or did not return data from the remote system.
$VMs = get-content C:\WinVms.txt #Generate your hostnames list however you deem best.
foreach ($vm in $vms)
{
Write-Host "Attempting to get hotfixes on:" $vm
invoke-command -computername $vm -ScriptBlock {start-job -scriptblock {(get-hotfix | sort installedon)[-1]} | wait-job | receive-job} -AsJob
}
start-sleep 60 # give it a minute to complete
get-job | ? { $_.state -eq "Completed"} | receive-job -keep | export-csv c:\temp\win-patch.csv
you can check your failures too like this:
get-job | ? { $_.state -eq "Failed"}
So i have the bottom scriptblock:
Import-csv C:\file_location.csv | foreach-object {
Get-WmiObject -computername $_.computername -class Win32_ComputerSystem | select username} | `
Select-Object computername, username | Export-CSV C:\file_location.csv -notypeinformation
the exported csv shows the Computer Name header but no actual computer and the username header is just fine. What and where am I missing something from?
Thank You!
select (which is an alias for Select-Object) returns an object with only the properties you specify. So when you did your first select username you got an object with just the username; all other properties were discarded, so when the second Select-Object call runs, there is no computername for it to return.
The first select seems completely unnecessary there; just take it out and I think everything will work as expected.
EDIT: I see now that computername is not a property of the returned WMI object; it came from the CSV. Your ForEach-Object is only returning the WMI object, so the CSV row object is being discarded.
What you need to do is add the computername from the CSV to the WMI object, which you can do with Select-Object (with a computed column) or Add-Member:
Import-csv C:\file_location.csv |
ForEach-Object {
Get-WmiObject -computername $_.computername -class Win32_ComputerSystem |
Select-Object #{Name='ComputerName';Expression={$_.computername}},username
} |
Export-CSV C:\file_location.csv -notypeinformation
Or:
Import-csv C:\file_location.csv |
ForEach-Object {
Get-WmiObject -computername $_.computername -class Win32_ComputerSystem |
Add-Member -NotePropertyName computername -NotePropertyValue $_.computername -Force -PassThru
} |
Select-Object computername, username
Export-CSV C:\file_location.csv -notypeinformation
I have a powershell query here which look in a particular group in AD and extracts the users into a CSV. Currently it only extracts the SamAcountName and Display name. How would I get it extract the group membership of each user in that group ?
Get-ADGroupMember -identity GLS-IW-APP-QV-KPI-Full | select -Property Name,SamAccountName | Export-csv -path X:\QlikView_AD_Groups\GLS-IW-APP-QV-KPI-Full.csv -NoTypeInformation
So if you are looking to get the group membership of all users in a certain group this would be one approach. You need to add a calculated propery in your Select-Object
Get-ADGroupMember -identity GLS-IW-APP-QV-KPI-Full |
Select-Object -Property Name,SamAccountName,#{Label="MemberOf";Expression={(Get-ADUser -identity $_.SamAccountName -Properties memberof).memberof -Join ";"}} |
Export-csv -path X:\QlikView_AD_Groups\GLS-IW-APP-QV-KPI-Full.csv -NoTypeInformation
What the #{} portion does is take the SamAccountName and call Get-Aduser to extract the memberof property. Since that returns an object we concat that to a semicolon delimited string with a -Join for proper/better CSV output