ServiceNamePrincipal to nslookup - powershell

# Source / credit:
# https://social.technet.microsoft.com/wiki/contents/articles/18996.active-directory-powershell-script-to-list-all-spns-used.aspx
cls
$search = New-Object DirectoryServices.DirectorySearcher([ADSI]"")
$search.filter = "(servicePrincipalName=*)"
## You can use this to filter for OU's:
## $results = $search.Findall() | ?{ $_.path -like '*OU=whatever,DC=whatever,DC=whatever*' }
$results = $search.Findall()
foreach( $result in $results ) {
$userEntry = $result.GetDirectoryEntry()
Write-host "Object Name = " $userEntry.name -backgroundcolor "yellow" -foregroundcolor "black"
Write-host "DN = " $userEntry.distinguishedName
Write-host "Object Cat. = " $userEntry.objectCategory
Write-host "servicePrincipalNames"
$i=1
foreach( $SPN in $userEntry.servicePrincipalName ) {
Write-host "SPN(" $i ") = " $SPN
$i+=1
}
Write-host ""
}
nslookup $SPN
I would like to use nslookup on the service principal names.

Related

Powershell - Move Mail

I'm newbie to powershell, and I have a challenge on process my script. It did everything perfectly, but it wont move the message to the target folder and I don't know why.
I thought maybe to process at end cycle, but the issue is that I can encour that will transfer also file that have not any reference, and I would avoid to process something that I have no info about.
I tried this
$MailboxName = "fatture#abc.com"
write-host "Now Processing" -ForegroundColor Yellow
write-host "Searching on Fatture" -ForegroundColor Yellow
$olFolderInbox = 6
$outlook = new-object -com outlook.application;
$namespace = $outlook.GetNameSpace("MAPI");
$recipient = $namespace.CreateRecipient($MailboxName)
$inbox = $namespace.GetSharedDefaultFolder($recipient,6)
$messages = $inbox.Folders.Item("Carriers").folders.Item("Gpac").folders.item("BLR")
$MoveTarget = $inbox.Folders.Item("Carriers").folders.Item("Gpac").folders.item("BLS")
$filepath = "C:\temp\FATTURE\Automation\"
$messages.Items | % {
Write-Host "New Message " $_.Subject
$msg = $_
$Ref = $_.Subject -replace ' ',''
$RefStr = $ref.split('#')
$SearchSTR = $RefStr[2]
write-host $SearchStr
# $invNbr = $body.Substring($body.IndexOf("INVOICE NO")+19,10)
#write-host "The Invoice Number is : $invNbr" -ForegroundColor Cyan
write-host "Querying for $SearchSTR" -ForegroundColor Green
$t = (Query_file($SearchSTR))[-1].CONSOL_REF
write-host "File Found : $t" -ForegroundColor Cyan
write-host $t
if ($t -ne $null) {
$filetype = $t.Substring(0,1)
$date = Get-Date -format "yyyyMMddhhmmss"
write-host "Today is Date is $date" -ForegroundColor Red
Switch($filetype.tostring())
{
{($_ -eq 1) -or ($_ -eq 2) -or ($_ -eq 7) -or ($_ -eq 7) -or ($_ -eq 8) }{($dept = "0001"), ($dept1 = "ZLAG")}
{($_ -eq "F") -or ($_ -eq "V") -or ($_ -eq "M")}{($dept = "0002"), ($dept1 = "Zero"), ($type = "MOR")}
{($_ -eq 3) -or ($_ -eq 5) -or ($_ -eq "J")} {($dept = "0028"), ($dept1 = "One"), ($type = "OBR") }
{($_ -eq 9)} {($dept = "0031"), ($dept1 = "CONSOLE")}
}
write-host "The KEY TYPE is $dept1 " -ForegroundColor Yellow
$fileStr = $t + "_INV_" + $dept + "_$date_.tsk"
write-host " FILE Path: " $fileStr -ForegroundColor Cyan
$msg.attachments | ?{$_.filename -like "*.pdf"} | %{
$file = $filestr
$_.saveasfile((Join-Path $filepath $filestr))
}
$msg.UnRead = $false
$msg.Move($MoveTarget)
}
#fine cycle messages
}
I tried to move from the cycle but the issue is that it goes for all of email, instead, I want to process only the email that should be. I would like when the attachment has being downloaded, that the email will be moved.

How to display the variable result as table in email body or console screen?

The below script to get the logon users and send as email was working great but only on the console output only.
I am trying to get the result as a table so the result in the console and the email body will be like:
Server, ConnectionType, User, ID, State
PRDSVR16, rdp-tcp#44, SVC-SQL, 4, Active
PRDSVR10, rdp-tcp#27, Admin.domain, 6, Disc
SVR25-VM,console,domain.admin,8,Active
Open in new window
This is the script:
$Today = Get-Date -Format 'F'
$SessionList = "`n`nRDP Session List - " + $Today + "`n`n"
$CurrentSN = 0
# Get a list of servers from Active Directory
write-progress -activity "Getting list of servers from Active Directory" -status "... please wait ..."
$Servers = (Get-ADComputer -Filter { Enabled -eq $True -and OperatingSystem -like "*Server*" } -Properties OperatingSystem -SearchBase "OU=Data Center,DC=Company,DC=com") |
Where-Object { Test-Connection $_.Name -Count 1 -Quiet } |
Select-Object -ExpandProperty Name
$NumberOfServers = $Servers.Count
# Iterate through the retrieved list to check RDP sessions on each machine
ForEach ($Server in $Servers)
{
Write-Host "Processing $Server ..." -ForegroundColor Yellow
Write-progress -activity "Checking RDP Sessions" -status "Querying $Server" -percentcomplete (($CurrentSN / $NumberOfServers) * 100)
try
{
$SessionList += qwinsta /server:$Server |
Select-Object -Skip 1 |
% {
[PSCustomObject] #{
Type = $_.Substring(1, 18).Trim()
User = $_.Substring(19, 20).Trim()
ID = $_.Substring(41, 5).Trim()
State = $_.Substring(48, 6).Trim()
}
} |
? { $_.Type -notin 'console', 'services', 'rdp-tcp' -and $_.User -ne $null -and $_.User -ne 65536 } |
% {
"`n$Server logged in by $($_.User) on $($_.Type), session id $($_.ID) $($_.state)"
}
}
catch
{
$SessionList += "`n Unable to query " + $Server
write-host "Unable to query $Server! `n $($Error[0].Exception)" -foregroundcolor Red
}
$CurrentSN++
}
# Send the output the screen.
$SessionList + "`n`n"
$sendMailArgs = #{
From = "$env:USERNAME#$env:userdnsdomain"
To = 'SOC#domain.com'
SmtpServer = 'SMTP.domain.com'
Priority = 'High'
Body = $SessionList | Select-Object #{ N = 'Server'; E = { $Server } },
#{ N = 'User'; E = { $_.User } },
#{ N = 'LogonType'; E = { $_.Type } },
#{ N = 'ID'; E = { $_.ID } },
#{ N = 'State'; E = { $_.State } }
Subject = "$($SessionList.Count) Logged On users from $($NumberOfServers) online servers as at $($Today)"
}
Send-MailMessage #sendMailArgs
Rendering collected information in different places is way easier if you keep strict separation between data and presentation (or formatting) of said data.
For the $SessionList for example, that means doing less than what you're currently trying to do inside the loop:
$ErrorList = #()
$SessionList = foreach($server in $servers){
try{
qwinsta /server:$Server |Select-Object -Skip 1 |ForEach-Object {
[PSCustomObject] #{
Server = $server
Type = $_.Substring(1, 18).Trim()
User = $_.Substring(19, 20).Trim()
ID = $_.Substring(41, 5).Trim()
State = $_.Substring(48, 6).Trim()
}
} |Where-Object { $_.Type -notin 'console', 'services', 'rdp-tcp' -and $_.User -ne $null -and $_.User -ne 65536 }
}
catch{
$ErrorList += [pscustomobject]#{
Server = $server
ErrorRecord = $_
}
}
}
Notice how I don't construct any strings - I just create the custom objects, filter them - and then leave them as-is.
Now it becomes much easier to format the data as desired for different output media:
# For console output, simply pipe to Format-Table
$SessionList |Format-Table
if($ErrorList.Count -gt 0){
Write-Warning "The following servers had errors, please inspect"
$ErrorList |Format-Table
}
# For email output we can use `ConvertTo-Html`
$Body = $SessionList |ConvertTo-Html -As Table -Fragment
if($ErrorList.Count -gt 0){
$ErrorTable = $ErrorList |ConvertTo-Html -As Table -Fragment
$Body = $Body,$ErrorTable -join '<br />'
}
$sendMailArgs = #{
# ...
Body = ConvertTo-Html -Body $Body -Title "Session list"
BodyAsHtml = $true
# ...
}

find site, app pool and recycling schedule using Powershell

I'm trying to get the below format printed for few of our servers:
[serverName]|[siteName]|[appPoolName]|[appPoolState]|[appPoolRecycleSchedule]
This is what I've gotten so far:
$Pool = Get-ChildItem IIS:\AppPools
foreach ( $p in $Pool )
{
$app_pool = $p.Name
$timing = Get-ItemProperty IIS:\\AppPools\$app_pool -name recycling.periodicRestart.schedule.collection
Write-Host "$($compName)|$($app_pool)|$($p.state)|$($timing.value)"
}
How do I get the site name in here?
Thanks,
Arun
I was able to get this working - thanks to a whole bunch of websites!.
$Pool = Get-ChildItem IIS:\AppPools
foreach ( $p in $Pool )
{
$app_pool = $p.Name
$apps = (Get-WebConfigurationProperty "/system.applicationHost/sites/site/application[`
#applicationPool='$app_pool']" "machine/webroot/apphost" -name path).ItemXPath
$site = ''
foreach ($s in $apps) {
$name = $s -replace "\/system.applicationHost\/sites\/site\[\#name='", ""
$name = $name -replace "' and \#id='\d{1,10}'\]\/application\[\#path='", ""
$name = $name -replace "'\]",""
if($site -eq ''){
$site = $name
}
else{
$site = $site + ", " + $name
}
}
if($site -eq "")
{
$site = "NotFound"
}
$timing = Get-ItemProperty IIS:\\AppPools\$app_pool -name recycling.periodicRestart.schedule.collection
Write-Host "$($compName)|$($app_pool)|$($p.state)|$($timing.value)|$($site)"
}

My script runs in powershell ISE but not powershell console?

function Get-LoggedOnUsers ($server) {
if($server -eq $null){
$server = "localhost"
}
$users = #()
# Query using quser, 2>$null to hide "No users exists...", then skip to the next server
$quser = quser /server:$server 2>$null
if(!($quser)){
Continue
}
#Remove column headers
$quser = $quser[1..$($quser.Count)]
foreach($user in $quser){
$usersObj = [PSCustomObject]#{Server=$null;Username=$null;SessionName=$null;SessionId=$Null;SessionState=$null;LogonTime=$null;IdleTime=$null}
$quserData = $user -split "\s+"
#We have to splice the array if the session is disconnected (as the SESSIONNAME column quserData[2] is empty)
if(($user | select-string "Disc") -ne $null){
#User is disconnected
$quserData = ($quserData[0..1],"null",$quserData[2..($quserData.Length -1)]) -split "\s+"
}
# Server
$usersObj.Server = $server
# Username
$usersObj.Username = $quserData[1]
# SessionName
$usersObj.SessionName = $quserData[2]
# SessionID
$usersObj.SessionID = $quserData[3]
# SessionState
$usersObj.SessionState = $quserData[4]
# IdleTime
$quserData[5] = $quserData[5] -replace "\+",":" -replace "\.","0:0" -replace "Disc","0:0"
if($quserData[5] -like "*:*"){
$usersObj.IdleTime = [timespan]"$($quserData[5])"
}elseif($quserData[5] -eq "." -or $quserData[5] -eq "none"){
$usersObj.idleTime = [timespan]"0:0"
}else{
$usersObj.IdleTime = [timespan]"0:$($quserData[5])"
}
# LogonTime
$usersObj.LogonTime = (Get-Date "$($quserData[6]) $($quserData[7]) $($quserData[8] )")
$users += $usersObj
}
return $users
}
function LogOutUser {
$test = Get-LoggedOnUsers
$count = 0
$nameArray = #()
$sessionArray = #()
$logonTimeArray = #()
foreach($line in $test){
$field1 = $line.Username
$field2 = $line.SessionID
$field3 = $line.LogonTime
$nameArray += $field1
$sessionArray += $field2
$logonTimeArray += $field3
$count+=1
}
$session1 = [INT]$sessionArray[0]
$session2 = [INT]$sessionArray[1]
Write-Host $nameArray
Write-Host $sessionArray
Write-Host $logonTimeArray
Write-Host $count
Write-Host $session1
Write-Host $session2
if(($count -gt 1) -and ($session2 -gt $session1 )){
logoff $session1
}
}
Get-LoggedOnUsers
LogOutUser
this code works in the ISE but it does not work when running from the console, what is happening? It does exactly what i want it to do through the ISE but when I try running as a scheduled task it doesn't work also it doesnt work when trying to run with console. i have tried powershell.exe -noexit -file c:\logofftest1.ps1 but still no success

Export table to file twice due to incorrect format

I'm using this code:
Function Main
{
$domain = "LDAP://www.example.com"
$outfile = 'C:\Scripts\Tests\usersDump.csv'
$properties = "SamAccountName", "lastLogonTimestamp", "AccountExpires", "FirstName", "LastName", "distinguishedName", "employeeNumber", "employeeID", "description", "extensionattribute8", "userAccountControl"
Write-Host "Searching AD..."
$dn = New-Object System.DirectoryServices.DirectoryEntry($domain)
$ds = New-Object System.DirectoryServices.DirectorySearcher($dn)
$ds.Filter = '(&(objectCategory=User)(samAccountType:1.2.840.113556.1.4.803:=805306368))'
$ds.PageSize=1000
$ds.PropertiesToLoad.AddRange($properties)
$list = $ds.FindAll()
Write-Host "Complete"
# The AD results are converted to an array of hashtables.
Write-Host "Exporting User Attributes to table..."
$table = #()
$garbageCounter = 0
foreach($item in $list) {
$hash = #{}
foreach($name in $properties){
if ($item.Properties[$name]) {
$hash.$name = $item.Properties[$name][0]
} else {
$hash.$name = $null
}
}
$table += New-Object PSObject -Property $hash
$garbageCounter++
if ($garbageCounter -eq 1000)
{
[System.GC]::Collect()
$garbageCounter = 0
}
}
[System.GC]::Collect()
Write-Host "Complete."
$listOfBadDateValues = '9223372036854775807', '9223372036854770000', '0'
$maxDateValue = '12/31/1600 5:00 PM'
Write-Host "fixing table values for `"lastLogonTimestamp`" and `"AccountExpires`""
$tableFixedValues = $table | % {
if ($_.lastLogonTimestamp) {
$_.lastLogonTimestamp = ([datetime]::FromFileTime($_.lastLogonTimestamp)).ToString('g')
}; if (($_.AccountExpires) -and ($listOfBadDateValues -contains $_.AccountExpires)) {
$_.AccountExpires = $null
} else {
if (([datetime]::FromFileTime($_.AccountExpires)).ToString('g') -eq $maxDateValue) {
$_.AccountExpires = $null
} Else {
$_.AccountExpires = ([datetime]::FromFileTime($_.AccountExpires)).ToString('g')
}
};$_}
Write-Host "Complete"
Write-Host "Exporting table to csv file $outfile"
$tableFixedValues | Export-Csv $outfile –encoding "unicode" -NoTypeInformation -Force
Write-Host "Complete"
Write-Host "Done."
}
Main
The problem is the file is written so everything is in 1 column. In order to make the properties in their own column, I use this code...
Write-Host "Converting $outfile to csv file $OutputResultsFile"
$outFileFixed = 'C:\Scripts\Tests\usersDumpFixed.csv'
Import-Csv $outfile | Export-Csv $outFileFixed -NoTypeInformation -Force
Write-Host "Complete"
Is there a way I can do this Without having to open-close it again?
Remove the -Encoding Unicode Parameter from the Export-csv then it will not be in one column