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'
}
}
}
}
Related
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
}
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.
I'm using iTextSharp to search a PDF for a keyword, and extract any line(s) that contain that keyword. What I'd like to do is not only extract the line(s) with the keyword but subsequent lines.
Line with keyword and the next line, Line with keyword and the next 2 lines, etc.
I've been hung up on this for awhile, trying arrays, hash tables, iterators...none of them are working right. Any help is appreciated. This is the basic design i've been working with:
$reader = New-Object iTextSharp.text.pdf.pdfreader -ArgumentList anypdf.pdf
for ($page = 1; $page -le $reader.NumberOfPages; $page++) {
$lines = [char[]]$reader.GetPageContent($page) -join "" -split "`n"
foreach ($line in $lines) {
if ($line -match $searchstring) {
$line = $line -replace "^\[\(|\)\]TJ$", "" -split "\)\-?\d+\.?\d*\(" -join ""
$line = $line -replace "\\([\S])", $matches[1]
Write-host $line
}
}
}
I can't take credit for the logic that strips out the unwanted characters from the PDF, and that may be why I haven't figured this out yet. The above code gets me any line that contains the keyword. The problem seems to be the PDF is split into pages and those pages are split into lines (which are each an array of characters). It would be nice and efficient if I could simply create a hash table of every line in the PDF from the start.
That's what Select-String was invented for.
for ($page = 1; $page -le $reader.NumberOfPages; $page++) {
[char[]]$reader.GetPageContent($page) -join "" -split "`n" `
| Select-String $searchstring -Context 0,2 `
| % {
$_ -replace "^\[\(|\)\]TJ$", "" `
-split "\)\-?\d+\.?\d*\(" -join "" `
-replace "\\([\S])", $_.Matches.Value
}
}
I don't quite understand all the splitting and joinging and replacing you're doing there, so you may need to adjust that.
Also, the above doesn't include the after context, since I wouldn't know where you want it to go. It can be accessed via $_.Context.PostContext.
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
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
}
}