Powershell 2.0 Get users for a local group - powershell-2.0

How can I get user list from a local group? I only have PS 2.0 and it does not have Get-ADGroup command.
I can get local groups:
$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$groups = $adsi.Children | Where { $_.SchemaClassName -eq 'Group' }
$group | ft Name
What I need is to list all the members for each group.

You can try the following
$obj = [ADSI]"WinNT://$env:COMPUTERNAME"
$admingroup = $obj.Children | Where { $_.SchemaClassName -eq 'group'} | where {$_.name -eq 'Administrators'}
$admingroup.Invoke('Members') | % {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}
$admingroup.Invoke('Members') | % {$_.GetType().InvokeMember('Name', 'GetProperty', $null, $_, $null)}
Here are the common properties
String :
Description, FullName, HomeDirectory, HomeDirDrive, Profile, LoginScript, ObjectSID
Integer :
UserFlags, PasswordExpired, PrimaryGroupID
Time :
PasswordAge
You'll find more in Microsoft documentation.

Try this
$computer = [ADSI]"WinNT://$env:COMPUTERNAME"
$computer.psbase.children | where { $_.psbase.schemaClassName -eq 'group' } | foreach {
write-host $_.name
write-host "------"
$group =[ADSI]$_.psbase.Path
$group.psbase.Invoke("Members") | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
write-host
}
This doesn't give the domain though, hence i had to look for other ways, like:
If you want to see members of a local group quickly:
PS C:\> net localgroup USERS
Alias name USERS
Comment Users are prevented from making accidental or intentional system-wide changes and can run most applications
Members
-------------------------------------------------------------------------------
NT AUTHORITY\Authenticated Users
NT AUTHORITY\INTERACTIVE
The command completed successfully.
Now you can manipulate this output a bit to get what you need:
$computer = [ADSI]"WinNT://$env:COMPUTERNAME"
$groups = $computer.psbase.children | where { $_.psbase.schemaClassName -eq 'group' } | select -ExpandProperty Name
Foreach($group in $groups)
{
write-host $group
write-host "------"
net localgroup $group | where {$_ -notmatch "command completed successfully"} | select -skip 6
Write-host
}

Related

Parse GUID out of string

I am running into an issue with this following using trim. It is removing some of the GUID. I would like to just get the GUID out of this. If anyone could help it would be appreciative.Thank you in advanced.
((Get-ADOrganizationalUnit -Filter {Name -eq "OUName"} -Properties LinkedGroupPolicyObjects,gplink) | ForEach-Object {if($_.GPlink){$_.GPlink.Split(",") | ForEach-Object {if($_ -like 'DC=DCNAME*'){if($_.length -gt 10){(((($_).trim('DC=DCNAME;0][LDAP://cn={')).trim('}')) ) }} }}})
My output is this:
754FF9F1-078A-4E05-913D-4F36572B2FC6
EDDAAB18-2BA6-42E6-A5EC-21B0227BE71A
7DF312DB-EB73-418E-8F64-3E391F4639B7
6E3512-4100-48A3-9A65-4DA17A0E2D87
72EF89D6-2C57-40AC-A116-2CAD89F453ED
2][LDAP://cn={31BB7749-F6DC-4098-8F10-9D8B4B0F0C0A
78528B0-F379-4E8F-A166-ACE1448AF9B2
I'm not sure how that DC=.. filter is helping you. The DC= part comes after the guid, so since you're splitting on ,, won't the first GUID be ignored by the time you get a match with -like 'DC=DCNAME*'? Ex.
[LDAP://cn={7BE35F55-E3DF-4D1C-8C3A-38F81F451D86},cn=policies, cn=system,DC=wingtiptoys,DC=local;2][LDAP://cn={7BE35F55-E3DF-4D1C-8111111},cn=......
If you only want to extract the guids, I would just extact {GUID}, like:
Get-ADOrganizationalUnit -Filter {Name -eq "OUName"} -Properties LinkedGroupPolicyObjects, gplink |
ForEach-Object {
if($_.GPlink) {
#Anything between { and }
[regex]::Matches($gplink,'(?<=\{).*?(?=\})') | ForEach-Object { $_.Value }
}
}
without your input i cannot be sure, but you might try something like this
Get-ADOrganizationalUnit -Filter {Name -eq 'OUName'} -Properties LinkedGroupPolicyObjects, gplink | ForEach-Object {
if ($_.GPlink) {
$_.GPlink.Split(',') | ForEach-Object {
if ($_ -like 'DC=DCNAME*' -and $_.length -gt 10) {
#$_ = $_ -replace 'DC=DCNAME;\d+\]\[LDAP:\/\/cn=\{'
#$_.trim('}')
$_ -replace '^.*([a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}).*$', '$1'
}
}
}
}

exception calling "Parse" with 1 argument: Input string was not in a correct format

I have a script that works properly when run as an administrator but gives a Parse error when run as a normal user. Any Ideas?;
SCRIPT
`NeverExpires = 9223372036854775807;
$ExpireMin = (Get-Date).AddDays(4);
$ExpireMax = (Get-Date).AddDays(9);
$Userlist = Get-ADUser -Filter * -Properties name, samaccountname, accountexpirationdate, enabled, distinguishedname, accountExpires | Where-object {($_.DistinguishedName -notlike "*OU=Terminated,OU=Users,OU=Home Office,DC=Domain,DC=com")} |
Where-Object {$_.accountExpires -ne $NeverExpires `
-and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax `
-and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin }
$Userlist | select name, samaccountname, accountexpirationdate, enabled, distinguishedname | export-csv $ReportName -notypeinformation
Send-MailMessage -To $To -From $From -Subject $Subject -Body $Body -SMTPServer $SMTPServer -Attachments $ReportName
Get-ADUser -Filter * -Properties accountExpires |
Where-Object {$_.accountExpires -ne $NeverExpires `
-and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -lt $ExpireMax `
-and [datetime]::FromFileTime([int64]::Parse($_.accountExpires)) -gt $ExpireMin } | ForEach {
$account = $_
$manager = Get-ADUser -Identity $account -Properties EmailAddress,Manager | %{(Get-AdUser $_.Manager -Properties EmailAddress).EmailAddress}`
I would say that $_.accountExpires is null either because the property could not be retrieved or $_ is itself null. Powershell will quietly convert null to the empty string resulting an invalid format for parsing. Note that the Parse call is completely unnecessary because powershell will automatically try to coerce the string for you and will likely give you a much better error message. Although null will be coerced to 0 as a long.

Powershell: Parse a structured text file and save to .CSV

I'm very new to Powershell. Only have been using it for about 2 weeks.
I have a file that is structured like this:
Service name: WSDL
Service ID: 14234321885
Service resolution path: /gman/wsdlUpdte
Serivce endpoints:
--------------------------------------------------------------------------------
Service name: DataService
Service ID: 419434324305
Service resolution path: /widgetDate_serv/WidgetDateServ
Serivce endpoints:
http://servername.company.com:1012/widgetDate_serv/WidgetDateServ
--------------------------------------------------------------------------------
Service name: SearchService
Service ID: 393234543546
Service resolution path: /ProxyServices/SearchService
Serivce endpoints:
http://servername.company.com:13010/Services/SearchService_5_0
http://servername2.company.com:13010/Services/SearchService_5_0
--------------------------------------------------------------------------------
Service name: Worker
Service ID: 14187898547
Service resolution path: /ProxyServices/Worker
Serivce endpoints:
http://servername.company.com:131009/Services/Worker/v9
--------------------------------------------------------------------------------
I'd like to parse the file and have Service name, Service ID, Service Resolution Path and Service Endpoints (which sometimes contain multiple or no values) in individual columms (CSV).
Beyond using Get-Content and looping through the file, I have no idea even where to start.
Any help will be appreciated.
Thanks
with PowerShell 5 you can use the fabulous command 'convertfrom-string'
$template=#'
Service name: {ServiceName*:SearchService}
Service ID: {serviceID:393234543546}
Service resolution path: {ServicePath:/ProxyServices/SearchService}
Serivce endpoints:
http://{ServiceEP*:servername.company.com:13010/Services/SearchService_5_0}
http://{ServiceEP*:servername2.tcompany.tcom:13011/testServices/SearchService_45_0}
--------------------------------------------------------------------------------
Service name: {ServiceName*:Worker}
Service ID: {serviceID:14187898547}
Service resolution path: {ServicePath:/ProxyServices/Worker}
Serivce endpoints:
http://{ServiceEP*:servername3.company.com:13010/Services/SearchService}
--------------------------------------------------------------------------------
Service name: {ServiceName*:WSDL}
Service ID: {serviceID:14234321885}
Service resolution path: {ServicePath:/gman/wsdlUpdte}
Serivce endpoints:
http://{ServiceEP*:servername4.company.com:13010/Services/SearchService_5_0}
--------------------------------------------------------------------------------
'#
#explode file with template
$listexploded=Get-Content -Path "c:\temp\file1.txt" | ConvertFrom-String -TemplateContent $template
#export csv
$listexploded |select *, #{N="ServiceEP";E={$_.ServiceEP.Value -join ","}} -ExcludeProperty ServiceEP | Export-Csv -Path "C:\temp\res.csv" -NoTypeInformation
Give this a try:
Read the file content as one string
Split it by 81 hyphens
Split each splited item on the colon char and take the last array item
Create new object for each item
$pattern = '-'*81
$content = Get-Content D:\Scripts\Temp\p.txt | Out-String
$content.Split($pattern,[System.StringSplitOptions]::RemoveEmptyEntries) | Where-Object {$_ -match '\S'} | ForEach-Object {
$item = $_ -split "\s+`n" | Where-Object {$_}
New-Object PSobject -Property #{
Name=$item[0].Split(':')[-1].Trim()
Id = $item[1].Split(':')[-1].Trim()
ResolutionPath=$item[2].Split(':')[-1].Trim()
Endpoints=$item[4..($item.Count)]
} | Select-Object Name,Id,ResolutionPath,Endpoints
}
Try this:
Get-Content | ? { $_ -match ': ' } | % { $_ -split ': ' } | Export-Csv Test.csv;
Basically it boils down to:
Get all text content as an array
Filter for lines that contain ': '
For each line left over, split it on ': '
Export object arrays to a CSV file named test.csv
Hope this points you in the right direction.
Note: Code is untested.
Here is a general way parsing files with records and records of records (and so on), it use the powerfull PowerShell switch instruction with regular expressions and the begin(), Process(), end() function template.
Load it, debug it, correct it ...
function Parse-Text
{
[CmdletBinding()]
Param
(
[Parameter(mandatory=$true,ValueFromPipeline=$true)]
[string]$ficIn,
[Parameter(mandatory=$true,ValueFromPipeline=$false)]
[string]$ficOut
)
begin
{
$svcNumber = 0
$urlnum = 0
$Service = #()
$Service += #{}
}
Process
{
switch -regex -file $ficIn
{
# End of a service
"^-+"
{
$svcNumber +=1
$urlnum = 0
$Service += #{}
}
# URL, n ones can exist
"(http://.+)"
{
$urlnum += 1
$url = $matches[1]
$Service[$svcNumber]["Url$urlnum"] = $url
}
# Fields
"(.+) (.+): (.+)"
{
$name,$value = $matches[2,3]
$Service[$svcNumber][$name] = $value
}
}
}
end
{
#$service[3..0] | % {New-Object -Property $_ -TypeName psobject} | Export-Csv c:\Temp\ws.csv
# Get all the services except the last one (empty -> the file2Parse is teerminated by ----...----)
$tmp = $service[0..($service.count-2)] | Sort-Object #{Expression={$_.keys.count };Descending=$true}
$tmp | % {New-Object -Property $_ -TypeName psobject} | Export-Csv $ficOut
}
}
Clear-Host
Parse-Text -ficIn "c:\Développements\Pgdvlp_Powershell\Apprentissage\data\Text2Parse.txt" -ficOut "c:\Temp\ws.csc"
cat "c:\Temp\ws.csv"

Powershell - Query firewall list of servers export to csv

I'm using the following to query the firewall rules of a list of servers.
$servers = Get-Content fw_servers.txt
foreach($serv in $servers) {
$fw = New-Object -ComObject hnetcfg.fwpolicy2
$fw.rules |
Where-Object { $_.enabled -and $_.LocalPorts -like 3389 } |
Select-Object -Property direction,protocol, localports,name
}
I would like to export this information to a csv file. Can someone please let me know how I can use Export-CSV for this? I've tried making it into an array but it's not working for me. I'm using 2.0
I'd also like the exported data to look like the following
Server Direction Protocol LocalPorts Name
testsrv1 1 6 3389 Remote Desktop (TCP-In)
testsrv2 1 6 3389 Research Remote Desktop Policy
Thank you for your help.
Amelia
I had an epiphany and somehow figured it out. The following, although not pretty, works for me.
$servers = Import-CSV fw_servers.csv
$servers | Foreach {
$serv = $_.serv
foreach-object {
$name = $_."Server"
$fw = New-Object -ComObject hnetcfg.fwpolicy2
$fw.rules |
Where-Object { $_.enabled -and $_.LocalPorts -like 3389 } |
Select-Object #{Name="Server"; Expression={$name}}, direction, protocol, localports, name
}
} | Export-CSV C:\Users\trankaa\desktop\fw_res.csv -NoTypeInformation -Force

Scripting a URL validity check from a text file list

I am trying to modify the PowerShell script I have found on ElegantCode.Com. I want to change it to specify a large text file of HTTP links, rather than naming the links as a parameter individually.
Once the script parses the file, I want it to pipe or echo out only the links that are valid back to a new file.
I am falling at the first hurdle and can't even figure out how I pass the input file in as a parameter.
Direct link for the script is here
BEGIN {
}
PROCESS {
$url = $_;
$urlIsValid = $false
try
{
$request = [System.Net.WebRequest]::Create($url)
$request.Method = 'HEAD'
$response = $request.GetResponse()
$httpStatus = $response.StatusCode
$urlIsValid = ($httpStatus -eq 'OK')
$tryError = $null
$response.Close()
}
catch [System.Exception] {
$httpStatus = $null
$tryError = $_.Exception
$urlIsValid = $false;
}
$x = new-object Object | `
add-member -membertype NoteProperty -name IsValid -Value $urlIsvalid -PassThru | `
add-member -membertype NoteProperty -name Url -Value $_ -PassThru | `
add-member -membertype NoteProperty -name HttpStatus -Value $httpStatus -PassThru | `
add-member -membertype NoteProperty -name Error -Value $tryError -PassThru
$x
}
}
END {
}
It appears the script it expecting the url to be piped in. The variable $_ represents the current pipeline object. So if the text file contained on URL per line you could do something like this:
Get-Content Urls.txt | Where {$_ -notmatch '^\s*$'} | Check-Url
I put the where in the pipe to eliminate blank lines.
To pipe the valid urls to a file as requested (adding to Keith's answer):
$validUrls = ".\ValidUrls.txt"
if (Test-Path $validUrls) { Remove-Item -Force $validUrls }
$result = New-Item -Type File -Path $validUrls
Get-Content Urls.txt | Where {$_ -notmatch '^\s*$'} | Foreach-Object {
$url = ($_ | Check-Url)
if ($url.IsValid)
{
$url.Url | Out-File $result -Append
}
}

Resources