Contain current variable name in Exported CSV - powershell

I am trying to write a simple script to scan through a list of workstations, pull their local user info, and export it to a CSV. The code works for doing that, but I am having trouble including any identifier of what workstation the information is related to. At the moment I just get a large list of users and their info.
$computerList = gc "C:\Temp\ComputerList.txt"
ForEach ($Computer in $computerList){
Get-LocalUser | Export-Csv C:\temp\passUser.csv -NoTypeInformation -Append }

You need to add the property Computer to the objects that are output from Get-LocalUser.
Also, you are currently running Get-LocalUser on your own local machine in each iteration.
Try
$computerList = Get-Content "C:\Temp\ComputerList.txt"
Invoke-Command -ComputerName $computerList -ScriptBlock {
Get-LocalUser |
Select-Object #{Name = 'Computer'; Expression = {$env:ComputerName}}, *
} | Export-Csv -Path C:\temp\passUser.csv -NoTypeInformation
Invoke-Command can take an array of computernames.
It also has a -Credential parameter with which you can specify the credentials of a user that has permissions to perform the actions inside the scriptblock

Related

Powrshell to export list of all PCs and if they have specific application install

I currently use the following powershell script to export the list of all VMs on our network with their information and export into an excel file:
#// Set CSV file name
$uDateTime = Get-Date -f "yyyy-MM"
$uCSVFile = "C:\Servers"+$uDateTime+".csv"
#//Export out to csv file.
Get-ADComputer -filter * -Properties ipv4Address, OperatingSystem,DistinguishedName |
select-object Name, ipv4Address, OperatingSystem, #{label='OU';expression=
{$_.DistinguishedName.Split(',')[1].Split('=')[1]}} |
export-csv -path $uCSVFile
The excel content would look something like this:
I want to add another column to indicate if specific application exists on each server or not like this one
Upon googling around I see that I can utilize the Get-ItemProperty to read the registry in order to check if certain program is installed on individual VM, but I am having problem tying the code to my existing one. It gives me the same result based on the machine where this PowerShell scripts runs on instead of each VM registry individually ...
Can you help me making this script read each VM's registry
#// Set CSV file name
$uDateTime = Get-Date -f "yyyy-MM"
$uCSVFile = "C:\Servers"+$uDateTime+".csv"
#//Export out to csv file.
Get-ADComputer -filter * -Properties ipv4Address, OperatingSystem,DistinguishedName |
select-object Name, ipv4Address, OperatingSystem, #{label='OU';expression=
{$_.DistinguishedName.Split(',')[1].Split('=')[1]}},
#{label='HelloKitty Installed';expression={(Get-ItemProperty "HKLM:\Software\HelloKitty\*" | Where {
$_.Version -ne $null }) -ne $null}}|
export-csv -path $uCSVFile
To read a registry key from the computer you are targetting instead of the computer the script is currently running from, you should use the Invoke-Command cmdlet.
However, keep in mind that Get-ADComputer can also list computers that are currently off-line, so I would suggest using a ForEach-Object loop which will give you a chance to test for that first.
Something like this:
#// Set CSV file name
$uCSVFile = 'C:\Servers{0:yyyy-MM}.csv' -f (Get-Date)
#//Export out to csv file.
$result = Get-ADComputer -Filter * -Properties ipv4Address, OperatingSystem,DistinguishedName |
ForEach-Object {
if (Test-Connection -ComputerName $_.Name -Count 1 -Quiet) {
# computer is on line. If need be, add -Credential to the Invoke-Command cmdlet
# because reading the HKEY_LOCAL_MACHINE hive needs Administrator permissions.
# Also, the targetted machines must have the 'Remote Registry' service enabled.
try {
$installed = Invoke-Command -ComputerName $_.Name -ScriptBlock {
$null -ne (Get-ItemProperty "HKLM:\SOFTWARE\HelloKitty\*" |
Where-Object { $null -ne $_.Version }).Version
} -ErrorAction Stop
}
catch { $installed = "ERROR" }
}
else { $installed = "OFF-LINE" }
# output an object
$_ | Select-Object Name, ipv4Address, OperatingSystem,
#{Name = 'HelloKitty Installed'; Expression = { $installed }}
}
# now export to CSV
$result | Export-Csv -Path $uCSVFile -UseCulture -NoTypeInformation
I have added switch -UseCulture to the Export-Csv cmdlet so the delimiter character used in the csv file will be the same as your local Excel expects

Powershell Script for getting username and lastlogon/off from text file

$Inventory = Get-Content -Path "C:\Temp\computer list.txt"
foreach ($Computer in $Inventory) {
(Get-WmiObject -Class win32_process -ComputerName $Computer | Where-Object name -Match explorer).getowner().user
}
I'm trying to run a script that will get me the username and timestamp of lastlogon through a list of computer names in a text file associated with AD.
I can manage to get the names but I run into null-valued errors as it goes through the list and takes longer than expected to finish.
How would I go about fixing that and adding a timestamp for users who last logged on/off?
A better method would be to parse through event logs to find their log on log off times
this script looks like it fits the bill
https://gallery.technet.microsoft.com/scriptcenter/Find-user-logon-duration-667b8c48
you could then use it like this
$Inventory = Get-Content -Path 'C:\Temp\computerlist.txt'
ForEach ($Computer in $Inventory) {
Get-OSCUserLogonDuration -ComputerName $Computer -IncludeRemoteInteractive -
Verbose | FT -AutoSize
}

Powershell out-file and name the file

I want to automate our auditing process, where we provide the local admin members, currently this is done with screenshots. I cobbled together the below code, which prompts for a server name and create a file with the local admin members. However this requires me to rename the file.
I want to be able to input the server name and have that also be the out-file name. I'm just not seeing the tree through the forest an how I go about it. Lots of stuff for appending file names but I didn't see anything for renaming a file you create.
Thanks
function get-localadmins {
[cmdletbinding()]
Param(
[string]$computerName
)
$group = get-wmiobject win32_group -ComputerName $computerName -Filter "LocalAccount=True AND SID='S-1-5-32-544'"
$query = "GroupComponent = `"Win32_Group.Domain='$($group.domain)'`,Name='$($group.name)'`""
$list = Get-WmiObject win32_groupuser -ComputerName $computerName -Filter $query
$list | % {$_.PartComponent} | % {$_.substring($_.lastindexof("Domain=") + 7).replace("`",Name=`"", "\")}
}
$Workstation = Read-Host "Computer Name"
get-localadmins $Workstation | Out-File c:\temp\ENTERSERVERNAME_LocalAdmin.txt
Try this out
| Out-File -FilePath "C:\Temp\${Workstation}_LocalAdmin.txt" -Append

Powershell Multipart WMI query output

When using this code:
$Prodservers = Get-ADComputer -Filter {OperatingSystem -like '*Server*'} -SearchScope Subtree -SearchBase $ProdSB -Server $DCprod -Credential $ProdCred -ErrorAction SilentlyContinue |
select -Expand DnsHostname
foreach ($P in $Prodservers) {
[PSCustomObject]#{
Hostname = $P
'Support team' = (Invoke-Command -ComputerName $P -ScriptBlock {$env:supportteam} -Credential $ProdCred)
'Local Admins' = (Invoke-Command -ComputerName $P -ScriptBlock {$ADSIComputer = [ADSI]('WinNT://localhost,computer');$lgroup = $ADSIComputer.psbase.children.find('Administrators', 'Group');$lgroup.psbase.invoke('members') | % {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}} -Credential $ProdCred)
'Host Reachable' = [bool](Invoke-Command -ComputerName $P -ScriptBlock {1} -Credential $ProdCred)
}
}
This works, however an group membership of more than two members in the local administrators group returns similar to this:
{Administrator, Domain Admins, Prod Server Admin...
How would I expend the output to show the full membership?
Also after pointers for selecting only certain groups that match group name x or y or return True is group x is present etc.
You might be running into output display formatting issues, where the column data exceeds the displayable width in table format in PowerShell.
You can try use the Format-List cmdlet to display things in a list instead to see if your local administrators group with multiple members displays correctly. Check out the link above to see how it helps, but a basic example of using it would be:
Get-Service | Format-List
As for your filtering question, it looks like you're using reflection to invoke methods that collect that data, so it would be harder to use PS cmdlets to help there, so I would suggest getting that data as you do now, but do it separately, into a temporary variable, then filter the data there selecting your specific groups you want using something like this to match your group names, and in the if statement, put the relevant data into another variable, which you then use for your final output.
if ($item -match "groupNameX") { #Then... }
Finally worked it out.
Came across this answer.
First, found a script block that outputted the memberships as a PSObject property:
$SB = {
$members = net localgroup administrators |
where {$_ -AND $_ -notmatch "command completed successfully"} |
select -skip 4
New-Object PSObject -Property #{
Members=$members
}
}
Then modified the local admins column:
'Local Admins' = $admins.Members -join ','
The output is still truncated, however now instead of export-CSV showing the column contents as System.Object[] it now shows the full output with the separator specified in -join.

Powsershell reading server list from a text file

I am having trouble with powershell reading my servers from a text file. When I declare a variable with get-content but when i call it, powershell doesnt read the server names. Here is the code.
$Server = Get-Content C:\servers.txt
Get-WmiObject -Class Win32_PerfFormattedData_PerfOS_System -ComputerName $Server |
Select-Object #{Name = “ComputerName”; Expression = {$_.__SERVER}},
#{Name = “SystemUpTime”; Expression = {New-TimeSpan -Seconds $_.SystemUpTime}}| Export-CSV C:\test2.txt.
If I change the $server to the list form It will work. Any ideas?
I changed the code so the servers are an array and its working now