How to remove Disabled account in Windows PowerShell Script - powershell

I have PowerShell script which access the AD users and insert into the SharePoint list.
Now the problem is some of the accounts are disabled or not active. I am using the following PowerShell script in the windows task scheduler which do the job in an interval. Can anyone Help me to figure out What I suppose to do in this script to filter only active accounts?
#if not already added
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$site = new-object Microsoft.SharePoint.SPSite("https://portal.company.gov.sa/");
$ServiceContext = [Microsoft.SharePoint.SPServiceContext]::GetContext($site);
#Get UserProfileManager from the My Site Host Site context
$ProfileManager = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($ServiceContext)
$AllProfiles = $ProfileManager.GetEnumerator()
# Open SharePoint List
$spWeb = Get-SPWeb "https://my.gac.gov.sa/"
$spData = $spWeb.GetList("Lists/EmployeesDirectory/")
$spDepartments = $spWeb.GetList("Lists/Departments/")
$total=0;
$withErros=0;
foreach($profile in $AllProfiles)
{
try
{
$DisplayName = $profile.DisplayName
$WorkEmail = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::WorkEmail]
$AccountName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName]
$Department = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::Department]
$Position = $profile.JobTitle
$LastName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::LastName]
$FirstName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::FirstName]
$FullName= "$FirstName $LastName"
$PreferredName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::PreferredName]
$WorkPhone =$profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::WorkPhone]
$Manager = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::Manager]
$JobTitleArabic=$profile["JobTitleArabic"];
if($Department -ine '' -and $Manager -ine ''){
$total++;
$departmnetItem = $spDepartments.Items | Where {$_["FF_TitleEn"] -eq $Department}
# Add properties to this list item
$user=$spWeb.EnsureUser($AccountName);
write-host $DisplayName "|" $AccountName "|" $Department "|" $Position "|" $PreferredName "|" $WorkPhone "|" $Manager ;
if($user.ID -gt 0)
{
#Query to filter List Items which contains user account
$SPQuery = new-object Microsoft.SharePoint.SPQuery
$Query = "<Where><Eq><FieldRef Name='FF_Emlpoyee' LookupId='TRUE'/><Value Type='User'>$($user.ID)</Value></Eq></Where>"
$SPQuery.Query=$Query
#Filter List Items by Query
$ListItems = $spData.GetItems($SPQuery)
if($ListItems.Count -gt 0)
{
$newItem=$ListItems[0];
}
else
{
#Create a new item
$newItem = $spData.Items.Add()
}
$newItem["FF_Emlpoyee"] = $user.ID;
# $newItem["FF_UserID"] = $user.ID;
$newItem["Title"] = $PreferredName
if($WorkPhone -ine '')
{
$newItem["FF_ExtensionNumber"] = $WorkPhone
}
try
{
if($Manager -ine $null)
{
$userManager=$spWeb.EnsureUser($Manager);
$newItem["FF_Manager"] = $userManager.ID
}
}
catch
{
write-host -ForegroundColor Red "Manager Not Found fro : " $user
}
$newItem["FF_Position"] = $Position
IF($JobTitleArabic -ine '')
{
$newItem["FF_PositionAr"] = $JobTitleArabic
}
$newItem["FF_FullNameAr"] = $FullName
$newItem["FF_Department"] = $departmnetItem.ID
$newItem.Update()
Write-Host "---------------------------------";
}
$user=$null
}
}
catch
{
write-host -ForegroundColor Red $_.Exception
$withErros+=1
}
}
Write-Host "Total: " $total;
Write-Host "withErros: " $withErros

Related

Parameterize a debug variable and insert it into the rest of the functions

$isDebug currently exists as a variable in the CleanStaleDevices function,
I need to make the variable into a optional parameter with a default value of $false.
Add the same parameter to the remaining functions.
I would like to set $isDebug as a variable at the initial function call, where CleanStaleDevices is called, then you can pass the value you set down the chain to the other functions. However, if you want to isolate debugging to an individual function you can override.
I tried converting $idDebug to a function itself but it didn't behave the way I was expecting
`function CleanStaleDevices($numDays) {
##Set debug flag
$isDebug = $true
#######Begin
Connect-AzureAD
###Get-AzureADDevice to get list of devices stale by 3 months and make sure devices aren't autopilot managed###
$dt = (Get-Date).AddDays($numDays)
$devices = Get-AzureADDevice -All:$true | Where-Object { $_.ApproximateLastLogonTimeStamp -le $dt } | select-object -Property AccountEnabled, DeviceId, DeviceOSType, DeviceOSVersion, DisplayName, DeviceTrustType, IsManaged, ApproximateLastLogonTimestamp
$fileNameDate = Get-Date -format "yyyyddMM"
$fileNameMiddle = "_AAD_Stale_Devices-"
##Get Intune devices
$intuneDevicesFileName = "$($fileNameDate)$($fileNameMiddle)Intune.csv"
$devices | ? { $_.IsManaged -eq $true } | Export-Csv c:\temp\$intuneDevicesFileName -NoTypeInformation
#######OUTSIDE ACTION#######
##Use Invoke-Device script to retire devices from generated CSV
##https://www.niallbrady.com/2017/08/23/getting-started-with-microsoft-graph-and-using-powershell-to-automate-things-in-intune/
#######END##################
$confirmation = Read-Host "Have you retired the detected Intune devices (y/n)?"
if ($confirmation -eq 'y') {
$hybridDevicesFileName = "$($fileNameDate)$($fileNameMiddle)Hybrid.csv"
$devices | ? { $_.DeviceTrustType -eq "ServerAd" } | Export-Csv c:\temp\$hybridDevicesFileName -NoTypeInformation
#######OUTSIDE ACTION#######
##Use DisableADComputersFromCSV.ps1 to disable the devices generated in the hybrid device csv
#######END##################
$confirmation = Read-Host "Have you disabled the on prem devices and ran a directory sync (y/n)?"
if ($confirmation -eq 'y') {
# proceed
###We don't have to open a new connection for each loop of the devices
$Connection = New-Object System.Data.SQLClient.SQLConnection
$serverName = "XXXXXXX"
$databaseName = "XXXXXXX"
$Connection.ConnectionString = "server='$serverName';database='$databaseName';trusted_connection=true;"
$Connection.Open()
if ($isDebug -eq $true) {
##debug array
$devicesweredisabled = #()
}
##Sort on DeviceTrustType so that AD Joined devices are disabled before AD registered
$devices = $devices | Sort-Object DeviceTrustType
foreach ($device in $devices) {
#if device is enabled
if ($device.AccountEnabled -eq $true) {
if ($isDebug -eq $true) {
##write to debug array
$devicesweredisabled += $device
Write-Host "Disable device" $device.DeviceId $device.DisplayName $device.AccountEnabled
}
else {
##don't disable Hybrid devices since they were disabled earlier
if ($_.DeviceTrustType -ne "ServerAd")
{
Write-Host "DISABLE " $device.DisplayName "with trust type" $device.DeviceTrustType
#$device.AccountEnabled = $false
}
##Check to see if device is in table already, if so check how long its been there
$disabledDateTimeValue = CheckIfDeviceISInTable $device.DeviceId $Connection
if ($null -eq $disabledDateTimeValue) {
##Device hasn't been added to table
WriteDisabledAADDevice $device.DeviceId $device.DisplayName $isDebug $Connection
}
}
}
else {
#device is not enabled
##Check to see if device is in table already, if so check how long its been there
$disabledDateTimeValue = CheckIfDeviceISInTable $device.DeviceId $Connection
if ($null -eq $disabledDateTimeValue) {
##Device is already disabled so we need to add it to the table for time tracking
WriteDisabledAADDevice $device.DeviceId $device.DisplayName $isDebug $Connection
}
else {
$numDaysSince = (Get-Date) - [datetime]$disabledDateTimeValue | % days
if ($numDaysSince -ge 90) {
if ($isDebug -eq $true) {
Write-Host "DEVICE WAS DELETED" $device.DeviceId $device.DisplayName $device.AccountEnabled
}
else {
Write-Host "DELETED..."
#device has been in table for 90 days so delete
##delete device
}
}
}
}
}
$Connection.Close()
if ($isDebug -eq $true) {
$devicesweredisabled | export-csv c:\temp\devicelist-olderthan-x-days-disabledtest.csv -NoTypeInformation
}
}
else{
Exit
}
}
else{
Exit
}
}
function WriteDisabledAADDevice {
Param(
[parameter(position = 3)]
$conn,
[parameter(position = 2)]
$logOnly,
[parameter(position = 1)]
$displayName,
[parameter(position = 0)]
$deviceId
)
$newId = (New-Guid).Guid
$disableDateTime = (Get-Date)
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $conn
$tableName = "DisabledAADDevice"
$insertquery = "
INSERT INTO $tableName
([DisabledAADDeviceId],[AADDeviceId],[DiplayName],[DisabledDateTime])
VALUES
('$newId','$deviceId','$displayName','$disableDateTime')"
if ($logOnly -eq $true) {
Write-Host $insertquery
}
else {
$Command.CommandText = $insertquery
$Command.ExecuteNonQuery()
}
}
function CheckIfDeviceISInTable {
Param(
[parameter(position = 1)]
$conn,
[parameter(position = 0)]
$deviceId
)
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $conn
$tableName = "DisabledAADDevice"
$selectQuery = "
Select [DisabledDateTime] FROM $tableName
WHERE [AADDeviceId] = '$deviceId'"
$Command.CommandText = $selectQuery
$resultValue = $Command.ExecuteScalar()
return $resultValue
}
CleanStaleDevices(-365)`

Setting variables based on value taken from CSV within a Foreach loop using an if else statement

I've created a script that takes new user data from a CSV file and connects to AzureAd and ExchangeOnline to create their AzureAD account, assigns them an Office license (not shown), and updates their Mailbox Office field.
CSV headers are Name, Department, OfficeLocation. The CSV used to contain a Domain and Company header. I removed those headers and added an if elseif statement to provide the logic to set those variables within the script. Prior to this addition, the script worked without any issues.
Now, the $company and $domain values are only updating for $main_offices and $corporate_offices Contoso and #contoso.com even when the OfficeLocation value is San Francisco or Austin and those values should be West/South Acme and west/south.acme.com.
Why are my $company and $domain values not being updated within the ForEach-Object loop as it iterates through the CSV? I confirmed that $company and $domain update properly when not reading in CSV data with ForEach-Object:
$new_users = Import-Csv -Path .\new-users.csv
...
$main_offices = 'New York','Los Angeles','Houston','Atlanta','Chicago'
$corporate_offices = 'Corporate Office (NY)','Corporate Office (LA)'
$west_office = 'San Francisco'
$south_office = 'Austin'
$new_users | ForEach-Object {
$first, $last = $_.Name.Split()
$mailnickname = $(($first.Substring(0,1) + $last).ToLower())
$password_profile = New-Object -TypeName Microsoft.Open.AzureAD.Model.PasswordProfile
$password_profile.Password = 'XXXXXXXXXXXXXXXXXX'
$password_profile.ForceChangePasswordNextLogin = $false
$off_loc = $_.OfficeLocation
if ($off_loc -in $main_offices -or $corporate_offices) {
$company = 'Contoso'
$domain = '#contoso.com'
} elseif ($off_loc -eq $west_office) {
$company = 'West Acme'
$domain = '#west.acme.com'
} elseif ($off_loc -eq $south_office) {
$company = 'South Acme'
$domain = '#south.acme.com'
} else { $off_loc = Read-Host 'Type an office location' } #CSV OfficeLocation field either missing or has a spelling error
$attr_new_user = #{
AccountEnabled = $true
CompanyName = $company
Department = $_.Department
DisplayName = $_.Name
GivenName = $first
MailNickname = $mailnickname
PasswordProfile = $password_profile
Surname = $last
UsageLocation = 'US'
UserPrincipalName = $mailnickname + $domain
}
try {
Write-Host ('>> Creating account for ' + $attr_new_user.DisplayName) -ForegroundColor Yellow
New-AzureADUser #attr_new_user | Out-Null
$user_upn = Get-AzureADUser -ObjectId $attr_new_user.UserPrincipalName | Select-Object -ExpandProperty UserPrincipalName
Write-Host ('>> ' + $user_upn + ' has been created') -ForegroundColor Green
}
catch {
Write-Host ('>> Something went wrong') -ForegroundColor Red
Write-Warning $Error[0]
}
...
try {
Write-Host ('>> Adding email alias: ' + $alternate_email + ' and office: ' + $off_loc + ' to ' + $user_upn) -ForegroundColor Yellow
Set-Mailbox -Identity $user_upn -EmailAddresses #{ add = $alternate_email } -Office $off_loc
Write-Host ('>> Email Alias: ' + $alternate_email + ' and office: ' + $off_loc + ' added to ' + $user_upn) -ForegroundColor Green
}
catch {
Write-Host ('>> Something went wrong') -ForegroundColor Red
Write-Warning $Error[0]
}
I've run the script and the $off_loc value is being inputted correctly in the Office field of the Mailbox settings. Which is why I am having trouble understanding how to get this information to create the user with the correct the $company and $domain fields.
Any insight into a solution to this issue is appreciated, thank you for taking the time to answer my question.
Per Santiago Squarzon:
This condition $off_loc -in $main_offices -or $corporate_offices will
always be $true because $corporate_offices is not $null or empty
string. It should be $off_loc -in $main_offices -or $off_loc -in
$corporate_offices
Confirmed this resolved the issue.

Powershell script to get certificate expiry for a website remotely for multiple servers

I am trying to create an script to get the certificate expiry date for an websites remotely for multiple servers. I have an script which is working for single server (Need to login into server and doing execution), I need to run this remotely for multiple servers. How can i modify this script to execute for multiple servers remotely. Please advice.
$servers = get-content D:\Certificate.txt
$DaysToExpiration = 60 #change this once it's working
$expirationDate = (Get-Date).AddDays($DaysToExpiration)
foreach ($server in $servers)
{
$sites = Get-Website | ? { $_.State -eq "Started" } | % { $_.Name }
$certs = Get-ChildItem IIS:SSLBindings | ? {
$sites -contains $_.Sites.Value
} | % { $_.Thumbprint }
Get-ChildItem CERT:LocalMachine/My | ? {
$certs -contains $_.Thumbprint -and $_.NotAfter -lt $expirationDate
}
}
Inspired by https://iamoffthebus.wordpress.com/2014/02/04/powershell-to-get-remote-websites-ssl-certificate-expiration/ I use following script:
$minimumCertAgeDays = 60
$timeoutMilliseconds = 10000
$urls = get-content .\check-urls.txt
#disabling the cert validation check. This is what makes this whole thing work with invalid certs...
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
foreach ($url in $urls)
{
Write-Host Checking $url -f Green
$req = [Net.HttpWebRequest]::Create($url)
$req.Timeout = $timeoutMilliseconds
$req.AllowAutoRedirect = $false
try {$req.GetResponse() |Out-Null} catch {Write-Host Exception while checking URL $url`: $_ -f Red}
$certExpiresOnString = $req.ServicePoint.Certificate.GetExpirationDateString()
#Write-Host "Certificate expires on (string): $certExpiresOnString"
[datetime]$expiration = [System.DateTime]::Parse($req.ServicePoint.Certificate.GetExpirationDateString())
#Write-Host "Certificate expires on (datetime): $expiration"
[int]$certExpiresIn = ($expiration - $(get-date)).Days
$certName = $req.ServicePoint.Certificate.GetName()
$certPublicKeyString = $req.ServicePoint.Certificate.GetPublicKeyString()
$certSerialNumber = $req.ServicePoint.Certificate.GetSerialNumberString()
$certThumbprint = $req.ServicePoint.Certificate.GetCertHashString()
$certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString()
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName()
if ($certExpiresIn -gt $minimumCertAgeDays)
{
Write-Host Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green
}
else
{
Write-Host WARNING: Cert for site $url expires in $certExpiresIn days [on $expiration] -f Red
Write-Host Threshold is $minimumCertAgeDays days. Check details:`nCert name: $certName -f Red
Write-Host Cert public key: $certPublicKeyString -f Red
Write-Host Cert serial number: $certSerialNumber`nCert thumbprint: $certThumbprint`nCert effective date: $certEffectiveDate`nCert issuer: $certIssuer -f Red
}
Write-Host
rv req
rv expiration
rv certExpiresIn
}
Alternatively, you might find this advanced script useful:
you can switch between report output as Text, Html or PSObject
use the script with urls (parameter array) or with input file for urls or with pipeline input
improved stability: correctly handle missing certificates on HTTP connections
just put the code into a file like Check-ExpiringSslCerts.ps1
Here the advanced script code:
[CmdletBinding(DefaultParametersetname="URLs in text file")]
Param(
[ValidateSet('Text','Html','PSObject')]
[string]$ReportType = 'Text',
[int]$MinimumCertAgeDays = 60,
[int]$TimeoutMilliseconds = 10000,
[parameter(Mandatory=$false,ParameterSetName = "URLs in text file")]
[string]$UrlsFile = '.\check-urls.txt',
[parameter(Mandatory=$false,ParameterSetName = "List of URLs",
ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)]
[string[]]$Urls
)
Begin
{
[string[]]$allUrls = #()
$returnData = #()
[bool]$ProcessedInputPipeLineByArrayItem = $false
function CheckUrl ([string]$url, [array]$returnData)
{
[string]$details = $null
if ($ReportType -eq "Html")
{
$stringHtmlEncoded = [System.Web.HttpUtility]::HtmlEncode($url)
Write-Host "<tr><td>$stringHtmlEncoded</td>"
}
if ($ReportType -eq "Text") { Write-Host Checking $url }
$req = [Net.HttpWebRequest]::Create($url)
$req.Timeout = $timeoutMilliseconds
$req.AllowAutoRedirect = $false
try
{
$req.GetResponse() |Out-Null
if ($req.ServicePoint.Certificate -eq $null) {$details = "No certificate in use for connection"}
}
catch
{
$details = "Exception while checking URL $url`: $_ "
}
if ($details -eq $null -or $details -eq "")
{
$certExpiresOnString = $req.ServicePoint.Certificate.GetExpirationDateString()
#Write-Host "Certificate expires on (string): $certExpiresOnString"
[datetime]$expiration = [System.DateTime]::Parse($req.ServicePoint.Certificate.GetExpirationDateString())
#Write-Host "Certificate expires on (datetime): $expiration"
[int]$certExpiresIn = ($expiration - $(get-date)).Days
$certName = $req.ServicePoint.Certificate.GetName()
$certPublicKeyString = $req.ServicePoint.Certificate.GetPublicKeyString()
$certSerialNumber = $req.ServicePoint.Certificate.GetSerialNumberString()
$certThumbprint = $req.ServicePoint.Certificate.GetCertHashString()
$certEffectiveDate = $req.ServicePoint.Certificate.GetEffectiveDateString()
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName()
if ($certExpiresIn -gt $minimumCertAgeDays)
{
if ($ReportType -eq "Html")
{
Write-Host "<td>OKAY</td><td>$certExpiresIn</td><td>$expiration</td><td> </td></tr>"
}
if ($ReportType -eq "Text")
{
Write-Host OKAY: Cert for site $url expires in $certExpiresIn days [on $expiration] -f Green
}
if ($ReportType -eq "PSObject")
{
$returnData += new-object psobject -property #{Url = $url; CheckResult = "OKAY"; CertExpiresInDays = [int]$certExpiresIn; ExpirationOn = [datetime]$expiration; Details = [string]$null}
}
}
else
{
$details = ""
$details += "Cert for site $url expires in $certExpiresIn days [on $expiration]`n"
$details += "Threshold is $minimumCertAgeDays days. Check details:`n"
$details += "Cert name: $certName`n"
$details += "Cert public key: $certPublicKeyString`n"
$details += "Cert serial number: $certSerialNumber`n"
$details += "Cert thumbprint: $certThumbprint`n"
$details += "Cert effective date: $certEffectiveDate`n"
$details += "Cert issuer: $certIssuer"
if ($ReportType -eq "Html")
{
Write-Host "<td>WARNING</td><td>$certExpiresIn</td><td>$expiration</td>"
$stringHtmlEncoded = [System.Web.HttpUtility]::HtmlEncode($details) -replace "`n", "<br />"
Write-Host "<tr><td>$stringHtmlEncoded</td></tr>"
}
if ($ReportType -eq "Text")
{
Write-Host WARNING: $details -f Red
}
if ($ReportType -eq "PSObject")
{
$returnData += new-object psobject -property #{Url = $url; CheckResult = "WARNING"; CertExpiresInDays = [int]$certExpiresIn; ExpirationOn = [datetime]$expiration; Details = $details}
}
rv expiration
rv certExpiresIn
}
}
else
{
if ($ReportType -eq "Html")
{
Write-Host "<td>ERROR</td><td>N/A</td><td>N/A</td>"
$stringHtmlEncoded = [System.Web.HttpUtility]::HtmlEncode($details) -replace "`n", "<br />"
Write-Host "<tr><td>$stringHtmlEncoded</td></tr>"
}
if ($ReportType -eq "Text")
{
Write-Host ERROR: $details -f Red
}
if ($ReportType -eq "PSObject")
{
$returnData += new-object psobject -property #{Url = $url; CheckResult = "ERROR"; CertExpiresInDays = $null; ExpirationOn = $null; Details = $details}
}
}
if ($ReportType -eq "Text") { Write-Host }
rv req
return $returnData
}
#disabling the cert validation check. This is what makes this whole thing work with invalid certs...
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
if ($ReportType -eq "Html")
{
Write-Host "<table><tr><th>URL</th><th>Check result</th><th>Expires in days</th><th>Expires on</th><th>Details</th></tr>"
Add-Type -AssemblyName System.Web
}
}
Process
{
if ($_ -ne $null)
{
CheckUrl $_ $returnData
$ProcessedInputPipeLineByArrayItem = $true
}
}
End
{
if ($ProcessedInputPipeLineByArrayItem -eq $false)
{
if ($Urls -eq $null)
{
$allUrls = get-content $UrlsFile
}
else
{
$allUrls = $Urls
}
foreach ($url in $allUrls)
{
$returnData = CheckUrl $url $returnData
}
}
if ($ReportType -eq "Html") { Write-Host "</table>" }
if ($ReportType -eq "PSObject") { return $returnData }
}
Output might look like e.g.:
"http://www.doma.com", "https://www.domb.com" | .\Check-ExpiringSslCerts.ps1 -ReportType PSObject | ft
Url ExpirationOn CertExpiresInDays CheckResult Details
--- ------------ ----------------- ----------- -------
http://www.doma.com ERROR No certificate in use for connection
https://www.domb.com 18.11.2017 09:33:00 87 OKAY
Put the whole code you've wrote in a script-block, in order to do so, just add at the beginning this code:
$sb = {
and at the bottom of your code add:
}
Once you have this script-block, you can run this script on the servers remotely using these commands:
$cred = Get-Credential
$servers = get-content D:\Certificate.txt
Invoke-Command -Credential $cred -ComputerName $servers -ScriptBlock $SB
Hope it helped!
Your code snippets are helpful but they will throw an error on HTTP errors -- that is the nature of the underlying .NET HttpWebRequest object to panic on everything that's not code 200.
So, if you're testing, say, API endpoints that only accept POST HTTP verb, your script will fail as it will get a 405 error message. Alternatively, if your URL returns HTTP 404, your script will fail as well. Luckily, you can catch layer 7 errors and capture the required info anyway just patch your code in this manner:
try {$req.GetResponse() | Out-Null } catch {
if ($_.Exception.InnerException.Status -eq 'ProtocolError') {
# saving the info anyway since this is a L7 error, e.g.:
$certExpiresOnString = $req.ServicePoint.Certificate.GetExpirationDateString()
[datetime]$expiration [System.DateTime]::Parse($req.ServicePoint.Certificate.GetExpirationDateString())
$certIssuer = $req.ServicePoint.Certificate.GetIssuerName() # ...
} else {
# this is a real error - timeout, DNS failure etc
Write-Host "$url, $_" -ForegroundColor Red
Continue
}
}
Taken mostly from https://gist.github.com/jstangroome/5945820, although with some changes. The following will obtain the certificate. $certificate.NotBefore and $certificate.NotAfter will then need to be checked.
function GetCertificate([string]$domain, [Int16]$port) {
$certificate = $null
$TcpClient = New-Object -TypeName System.Net.Sockets.TcpClient
$TcpClient.ReceiveTimeout = 1000
$TcpClient.SendTimeout = 1000
try {
$TcpClient.Connect($domain, $port)
$TcpStream = $TcpClient.GetStream()
$Callback = { param($sender, $cert, $chain, $errors) return $true }
$SslStream = New-Object -TypeName System.Net.Security.SslStream -ArgumentList #($TcpStream, $true, $Callback)
try {
$SslStream.AuthenticateAsClient($domain)
$certificate = $SslStream.RemoteCertificate
}
finally {
$SslStream.Dispose()
}
}
finally {
$TcpClient.Dispose()
}
if ($certificate) {
if ($certificate -isnot [System.Security.Cryptography.X509Certificates.X509Certificate2]) {
$certificate = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList $certificate
}
}
return $certificate
}

Delete local administrator account with delete() method ADSI with Powershell

I am writing a powershell script to manage our local administrator accounts using a csv file.
#variable to store the data in data.csv
$userobjects = Import-CSV C:-data.csv
function main-list{
Write-Host "--------------------------------------"
Write-Host "Windows Powershell Account Manager"
Write-Host "--------------------------------------"
Write-Host "1 - Change Name"
Write-Host "2 - Disabled Account"
Write-Host "3 - Delete User"
Write-Host "4 - Exit"
[int]$action = Read-Host "Enter the menu number from above"
if ($action -eq 1){change-name}
if ($action -eq 2){disable-account}
if ($action -eq 3){delete-user}
if ($action -eq 4){cls; break}
}
function change-name
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
# Rename
if (($user.Account -ne $user.Rename) -and ($user.Rename -ne '' ))
{
#Write-Host "old name :"$FileHostname"/"$FileAccount "-> new name :"$FileHostname"/"$FileNewname
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://$connection")
if ($accName.path -eq "WinNT://"+$connection+"")
{
$accName.psbase.Rename($FileNewname)
Write-Host "Account(s) renamed"
$user.Account = $user.Rename
}
else
{
Write-Host "Account name :"$connection "can't be found on the host"
}
$user.Account = $user.Rename
$userobjects | export-csv C:-data.csv -notype
}
}
Write-Host "--------------------------------------"
main-list
}
function disable-account
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
if ($user.Disable -eq 'yes')
{
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://"+$connection+"")
if ($accName.UserFlags -eq '515')
{
Write-Host "Account :"$connection "is already disabled"
}
else
{
$accName.description = "Account disabled"
$accName.UserFlags = 2
$accName.setinfo()
Write-Host "Account(s) disabled"$connection
}
}
}
Write-Host "--------------------------------------"
main-list
}
function delete-user
{
foreach ($user in $userobjects)
{
#Assign the content to variables
$FileHostname = $user.Host
$FileAccount = $user.Account
$FileNewname = $user.Rename
$FileDisable = $user.Disable
$FileDelete = $user.Delete
#Delete
if ($user.Delete -eq 'yes')
{
$connection = $FileHostname+"/"+$FileAccount
$accName = [ADSI]("WinNT://"+$connection+"")
$accName.delete("user",$accName.name)
#Write-Host $connection deleted
}
else
{
Write-Host "Account name :"$connection "can't be found on the host"
}
}
}
}
$userobjects | export-csv C:-\data.csv -notype
main-list
I don't really know why I have this message when I am trying to use the delete function : "Unknown name", it is like it doesn't find the local account to delete it but I am not sure. However, It works perfectly when I want to rename or disable accounts.
My data file looks like that
http://www.noelshack.com/2016-05-1454622367-capture.png
I will post the real message when I will be back to work tomorow.
Thank you for your help.
Quick skim... wouldn't this need to be used instead? I think your $accName.name would be using the machine name.
$accName.delete("user",$user.account)
You delete() the user from the computer, so your [adsi] object should bind to the computer and call Delete() on that instead:
# Just the machine name, nothing more:
$Machine = [ADSI]"WinNT://$FileHostname"
# Now delete the user account from the machine
$Machine.Delete('user',$FileAccount)

WMI Warranty information

I have a Powershell script(1) that collects the Warranty information for a Dell system and will display it to the screen. I also have a second script(2) that creates a WMI Namespace and (3)one for a class. What I am trying to do it to get the information gathered by the warranty script to end up in the WMI class so we can pull it through SCCM. The code below is what I have so far. Any help would be greatly appreciated.
(1)
{
$service = New-WebServiceProxy -Uri http://{143.166.84.118}/services/assetservice.asmx?WSDL
if($args.count -ne 0){
$serial = $args[0]
}
else {
$system = Get-WmiObject win32_SystemEnclosure
$serial = $system.serialnumber
}
$guid = [guid]::NewGuid()
$info = $service.GetAssetInformation($guid,'check_warranty.ps1',$serial)
if($info.count -eq 0)
{
Write-Host "Machine is not a Dell"
}
else
{
$warranty = $info[0].Entitlements[0]
$expires = $warranty.EndDate
$days_left = $warranty.DaysLeft
if($days_left -eq 0)
{
Write-Host "Warranty has expired"
}
else{
`enter code here`
set objwmiservice = getobject("winmgts:\\computer\root\warranty")
set colitems = objwmiservice.execquery("select * from warranty_warranty")
objitem.Warranty = $expires
objitem.put_
next
Write-Host "Warranty expires $expires."
Write-Host "Warranty is valid for $days_left days."
}
}
}
(2)
'Create namespace
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root")
Set objItem = objWMIService.Get("__Namespace")
Set objNamespace = objItem.SpawnInstance_
objNamespace.Name = "Warranty"
objNamespace.Put_ '
(3)
' $newClass = New-Object System.Management.ManagementClass `
("root\Warranty", [String]::Empty, $null);
$newClass["__CLASS"] = "Warranty";
$newClass.Qualifiers.Add("Static", $true)
$newClass.Properties.Add("Warranty", `
[System.Management.CimType]::String, $false)
$newClass.Properties["Warranty"].Qualifiers.Add("Key", $true)
$newClass.Put()'`enter code here`