Get local group members: version agnostic - powershell

I found this thread that offers two basic approaches to getting local group members.
This works for me in all versions of powershell, but depends on using the old NET command line utility.
function Get-LocalGroupMembers() {
param ([string]$groupName = $(throw "Need a name") )
$lines = net localgroup $groupName
$found = $false
for ($i = 0; $i -lt $lines.Length; $i++ ) {
if ( $found ) {
if ( -not $lines[$i].StartsWith("The command completed")) {
$lines[$i]
}
} elseif ( $lines[$i] -match "^----" ) {
$found = $true;
}
}
}
This works for me in PowerShell 2.0, but barfs in PS5.0 with Error while invoking GetType. Could not find member.
It only barfs on some groups, including Administrators, which has me thinking it's some sort of security feature, like requiring elevated privileges to REALLY have admin rights in a script.
Function Get-LocalGroupMembers
{
Param(
[string]
$server = "."
)
Try
{
$computer = [ADSI]"WinNT://$( $Server ),computer"
$computer.psbase.children |
where {
$_.psbase.schemaClassName -eq 'group'
} |
ForEach {
$GroupName = $_.Name.ToString()
$group =[ADSI]$_.psbase.Path
$group.psbase.Invoke("Members") |
foreach {
$memberName = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) -replace "WinNT:", ""
$props = #{
"LocalGroup" = $GroupName
"MemberName" = $memberName
}
$obj = New-Object -TypeName psobject -Property $props
Write-Output $obj
} # foreach members
} # foreach group
}
Catch
{
Throw
}
}
I think I read somewhere that PS5.1 has a native CMDlet finally. But I can't depend on a particular version of PS, I need to support everything from PS2.0 in Win7 up. That said, is there a single version agnostic solution that doesn't depend on a command line utility kludge? Or do I need to have code that uses the old hack or the new CMDlet depending on PS version I am running on?

So, I am having good luck with this solution.
$hostname = (Get-WmiObject -computerName:'.' -class:Win32_ComputerSystem).name
$wmiQuery = Get-WmiObject -computerName:'.' -query:"SELECT * FROM Win32_GroupUser WHERE GroupComponent=`"Win32_Group.Domain='$Hostname',Name='$group'`""
if ($wmiQuery -ne $null) {
:searchLoop foreach ($item in $wmiQuery) {
if (((($item.PartComponent -split "\,")[1] -split "=")[1]).trim('"') -eq $user) {
$localGroup = $true
break :searchLoop
}
}
}
I'm not sure yet if I like that overly complex IF vs some variables, but the functionality is there and working across all versions of PS without resorting to command line kludges, which was the goal.
Note that this just returns true if the user is a member of the group, which is all I need. The other code I posted would provide a list of members, which is the basis of doing a check, and I just hadn't modified it to show the real end goal, since the problem manifested without that.

Instead this :
$memberName = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) -replace "WinNT:", ""
You can try this :
$memberName = ([ADSI]$_).InvokeGet("Name")

Related

Powershell - Exchange JSON output without needing to write to a file

EDIT: Added Setupconfigfiles.ps1
I'm a bit new to detailed scripting so please bear with me.
I have two Powershell scripts
Setupconfigfiles.ps1 generates JSON output to be fed to an API.
Script2 uses that JSON data to execute API commands.
Script 2 can call setupconfigfiles.ps1 as indicated below and use the output data.
.\SetupConfigFiles.ps1 -type $Type -outfile .\Templist.json
$servers = Get-Content -Raw -Path .\templist.json | ConvertFrom-Json
setupconfigfiles.ps1:
param (
# If this parameter is set, format the output as csv.
# If this parameter is not set, just return the output so that the calling program can use the info
[string]$outfile,
# this parameter can be 'production', 'development' or 'all'
[string]$type
)
enum MachineTypes {
production = 1
development = 2
all = 3
}
$Servers = Get-ADObject -Filter 'ObjectClass -eq "computer"' -SearchBase 'Obfuscated DSN' | Select-Object Name
$output = #()
$count = 0
# Set this to [MachineTypes]::production or [MachineTypes]::development or [MachineTypes]::all
if ($type -eq "all") {
$server_types = [MachineTypes]::all
}
ElseIf ($type -eq "production") {
$server_types = [MachineTypes]::production
}
else {
$server_types = [MachineTypes]::development
}
ForEach ($Server in $Servers)
{
$count = $count + 1
$this_server = #{}
$this_server.hostname = $Server.Name
$this_server.id = $count
$this_server."site code" = $this_server.hostname.substring(1,3)
$this_server."location code" = $this_server.hostname.substring(4,2)
if ($this_server.hostname.substring(7,1) -eq "P") {
$this_server.environment = "Production"
}
ElseIf ($this_server.hostname.substring(7,1) -eq "D") {
$this_server.environment = "Development"
}
Else {
$this_server.environment = "Unknown"
}
if (($server_types -eq [MachineTypes]::production ) -and ($this_server.environment -eq "Production")) {
$output += $this_server
}
ElseIf (($server_types -eq [MachineTypes]::development ) -and ($this_server.environment -eq "Development")) {
$output += $this_server
}
Else {
if ($server_types -eq [MachineTypes]::all ) {
$output += $this_server
}
}
}
if ($outfile -eq "")
{
ConvertTo-Json $output
}
else {
ConvertTo-Json $output | Out-File $outfile
}
How can I do it without needing to write to the Templist.json file?
I've called this many different ways. The one I thought would work is .\SetupConfigFiles.ps1 $servers
Y'all are great. #Zett42 pointed me in a direction and #Mathias rounded it out.
The solution was to change:
"ConvertTo-Json $output" to "Write-Output $output"
Then it's handled in the calling script.
thanks!

Powershell.I want to add a object to my array $computers but it said that the index is out of bounds

I want to add a object to my array $computers
but it said that the index is out of bounds
function ajouterperipherique ($id, $emplacement, $type) {
$computers = import-csv -path "C:\Temp\Peripherique.csv"
echo $computers
$newObject = [pscustomobject]#{
idObject = $id
EmplacementObject = $emplacement
TypeObject=$type
}
for ($i = 0; $i -lt $computers.Count; $i++) {
if ($i +1 -eq $computers.count) {
$computers[$computers.count+1]=$newObject
}
}
Write-Host ($newObject | Format-List | Out-String)
}
ajouterperipherique "GLADIATOR" "ordinateur" "Statique"
Here is the solution proposed by Lee_Dailey:
$csvPath='C:\Temp\Peripherique.csv'
function ajouterperipherique {
param(
[string]$ID,
[string]$Emplacement,
[string]$Type,
[string]$Path
)
if(-not(Test-Path $Path) -or -not [IO.Path]::GetExtension($Path) -eq '.csv')
{
throw 'File doest not exist or is not a Csv...'
}
[pscustomobject]#{
Identifiant = $id
Type = $type
Emplacement = $emplacement
}|Export-Csv $Path -NoTypeInformation -Append
}
ajouterperipherique -ID "GLADIATOR" -Emplacement "ordinateur" -Type "Statique" -Path $csvPath
A few tips, as pointed out in comments, you shouldn't really use or you should try to avoid Write-Host whenever possible.
You shouldn't really hardcode paths inside your functions, since they're meant to be re-used, hardcoding information you know can change in the future is never a good idea.
You might also wanna consider setting your parameters as Mandatory, parameters are somewhat important in Powershell and can make your life easier. I recommend reading this article if you're thinking of creating more functions in the future: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters?view=powershell-7.1

Struggling with If Statements

I have problems of understanding values of variables in PowerShell and I check them with if statements.
$LDAPDirectoryService = '10.10.XXX.XXX:389'
$DomainDN = 'o=Enterprise'
#$LDAPFilter = '(&(objectCategory=Person)(memberOf=cn=alc-01-Planung-rw,ou=KT,o=enterprise))'
$LDAPFilter = '(&(cn=alc-01-Planung-rw))'
$null = [System.Reflection.Assembly]::LoadWithPartialName('System.Net')
$LDAPServer = New-Object System.DirectoryServices.Protocols.LdapConnection $LDAPDirectoryService
$LDAPServer.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous
$Scope = [System.DirectoryServices.Protocols.SearchScope]::Subtree
$AttributeList = #('*')
$SearchRequest = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $DomainDN,$LDAPFilter,$Scope,$AttributeList
$groups = $LDAPServer.SendRequest($SearchRequest)
$groups
if ($groups -eq $null) {"No Group found"}
if ($groups -eq " ") {"No Group found"}
foreach ($group in $groups.Entries) {
$users = $group.attributes['member'].GetValues('string')
foreach ($user in $users) {
Write-Host $user
}
}
I want to check if the group exists and then if users are existing in this group. I tried many statements but none of them seem to work.
It's not null or blank, even when nothing is written down in the console.
This is what I got when I use group which doesn't exist:
Can anybody show me a solution?
What version of PowerShell are you running? Why are you not using the built-in AD group cmdlets for this or are you not using ADDS but some other LDAP service?
Or you may be on OSX/Linux and are using PSCore, which the ADDS/RSAT cmdlets are not there, well, not yet?
For your goals of …
I want to check if the group exists and then if users are existing in
this group.
… On Windows, with PowerShell 3x or higher, it's really only this...
# Get all AD groups and all members of each group
Clear-Host
(Get-ADGroup -Filter '*').Name |
%{
"`n*** The members of $PSItem are as follows: ***`n"
If((Get-ADGroupMember -Identity $PSItem).Count -ge 1)
{
(Get-ADGroupMember -Identity $PSItem).SamAccountName
}
Else
{
Write-Warning -Message "$PSItem does not exist or has no members."
}
}
# Filtered
Clear-Host
((Get-ADGroup -Filter '*').Name -match 'Domain Admins|Domain Users' ) |
%{
"`n*** The members of $PSItem are as follows: ***`n"
If((Get-ADGroupMember -Identity $PSItem).Count -ge 1)
{
(Get-ADGroupMember -Identity $PSItem).SamAccountName
}
Else
{
Write-Warning -Message "$PSItem does not exist or has no members."
}
}
Using your LDAP approach though... How about this...
'Administrators','Distributed COM Users' |
ForEach {
# Define LDAP search root, the Global catalog of the domain
$sLDAPSearchRoot = "LDAP://$((Get-ADDomainController).IPv4Address):389"
# The Groupname to looking for
($sGroupName = "$_")
# The LDAP query - query string
$sSearchStr = "(&(objectCategory=group)(name="+$sGroupName+"))"
# Get the search object
$oSearch = New-Object directoryservices.DirectorySearcher($oADRoot,$sSearchStr)
# Looking for the group
$oFindResult = $oSearch.FindAll()
# On success, get a DirectoryEntry object for the group
$oGroup = New-Object System.DirectoryServices.DirectoryEntry($oFindResult.Path)
# And list all members
If (($oGroup.Member).Count -ge 1)
{
$oGroup.Member |
%{($oMembers = New-Object System.DirectoryServices.DirectoryEntry($sLDAPSearchRoot+"/"+$_))}
}
Else
{ Write-Warning -Message "$($oGroup.Member) does not exist or has no members"}
}

putting foreach loop into a csv file

im stuck on how to output my foreach loop into a csv or excel file. this script just get all computers off a local network and then test to see if that computer has a certain KBPatch. The script works just like I said I need help trying to make it output to a csv file. any tips/help is appreciated
Code Below
$strCategory = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$ObjSearcher.SearchRoot = $objDomain
$objSearcher.filter = ("(objectCategory=$strCategory)")
$colProplist = "name"
foreach($i in $colProplist)
{
$objSearcher.PropertiesToLoad.Add($i)
}
#Finds all operating systems and computer names
$colResults = $objSearcher.FindAll()
foreach($objResult in $colResults)
{
$objComputer = $objResult.Properties;
$names = $objComputer.name
# Define Hotfix to check
$CheckKBS = #(“patch#" , "patch#")
#Query the computers for the HotFix
foreach($name in $names)
{
foreach ($CheckKB in $CheckKBS) {
$HotFixQuery = Get-HotFix -ComputerName $name | Where-Object {$_.HotFixId -eq $CheckKB} | Select-Object -First 1;
if($HotFixQuery -eq $null)
{
Write-Host “Hotfix $CheckKB is not installed on $name”;
}
else
{
Write-Host “Hotfix $CheckKB was installed on $name by ” $($HotFixQuery.InstalledBy);
}
}}
}
To do this cleanly I usually use a custom object.
Before your foreach, instantiate an empty array:
$records = #()
and make an object template:
$tmpRecord = [PSCustomObject]#{
serverName = ''
missingKB = ''
}
Inside the foreach, clone the record obj:
$record = $tmpRecord.psobject.copy()
put your data into the record:
$record.serverName = $name
$record.missingKB = $CheckKb
Put the record into the array:
$records += $record
Then after the foreach, export to csv:
$records | export-csv yourcsv.csv
The need for an object template was confusing to me when I first learned this pattern. You need this because of the combination of scope and how objects are added to arrays (by reference).
If you try to get away with declaring an object inside the loop then that object will be scoped to the lifetime of the foreach loop. You'll then add a reference to that object to your $records array. After the foreach loop completes you will have an array full of references to objects that do not exist.

powershell script that pulls WMIC data from remote workstations

I am looking for a Powershell script that queries remote workstations for installed Windows updates looking for specific HotFixes (6 of them) and then reports back which ones (if any) are installed.
Query would get the remote host's name from a text file.
I found this script on Microsoft's site and tried to alter it, but I have no where near the skills needed to it.
Function Get-MSHotfix
{
$outputs = Invoke-Expression "wmic qfe list"
$outputs = $outputs[1..($outputs.length)]
foreach ($output in $Outputs) {
if ($output) {
$output = $output -replace 'y U','y-U'
$output = $output -replace 'NT A','NT-A'
$output = $output -replace '\s+',' '
$parts = $output -split ' '
if ($parts[5] -like "*/*/*") {
$Dateis = [datetime]::ParseExact($parts[5], '%M/%d/yyyy',[Globalization.cultureinfo]::GetCultureInfo("en-US").DateTimeFormat)
} elseif (($parts[5] -eq $null) -or ($parts[5] -eq ''))
{
$Dateis = [datetime]1700
}
else {
$Dateis = get-date([DateTime][Convert]::ToInt64("$parts[5]", 16))-Format '%M/%d/yyyy'
}
New-Object -Type PSObject -Property #{
KBArticle = [string]$parts[0]
Computername = [string]$parts[1]
Description = [string]$parts[2]
FixComments = [string]$parts[6]
HotFixID = [string]$parts[3]
InstalledOn = Get-Date($Dateis)-format "dddd d MMMM yyyy"
InstalledBy = [string]$parts[4]
InstallDate = [string]$parts[7]
Name = [string]$parts[8]
ServicePackInEffect = [string]$parts[9]
Status = [string]$parts[10]
}
}
}
}
Here's something I wrote up for a very similar situation:
ForEach($Server in $ServerList){
$QFE=Get-WmiObject Win32_QuickFixEngineering -ComputerName $Server
$IDRX = 3188732,3188743,3192392 -join '|'
$QFE|?{$_.HotFixId -match $IDRX}
}
Mind you, I was looking for QFEs 3188732, 3188743, and 3192392, but you could easily modify that line for the ones you are looking for.