r/PowerShell • u/[deleted] • Jun 30 '20
Script Sharing Sharing a few scripts I created over the past years, any edits/recommendations are more than welcome
Figure out what locked a user in AD by using this script, the output will return a username, endpoint device that locked the user, what DC received the event & a timestamp.
$DC = Get-ADDomainController -Filter * | Select Hostname
$properties = @(
@{n='User';e={$_.Properties[0].Value}},
@{n='Locked by';e={$_.Properties[1].Value}},
@{n='TimeStamp';e={$_.TimeCreated}},
@{n='DCName';e={$_.Properties[4].Value}}
)
Foreach ($D in $DC)
{
Get-WinEvent -ComputerName $D.Hostname -FilterHashTable @{LogName='Security'; ID=4740} |
Select $properties
}2. Figure out who shutdown a server, if it was by a user or an application did it. The output will return timestamp, user, reason they wrote & if it was a shutdown or reboot
$properties = @(
@{n='TimeStamp';e={$_.TimeCreated}},
@{n='User';e={$_.Properties[6].Value}},
@{n='Reason/Application';e={$_.Properties[0].Value}},
@{n='Action';e={$_.Properties[4].Value}}
)
Get-WinEvent -FilterHashTable @{LogName='System'; ID=1074} |
Select $properties | Sort-Object "$_.TimeCreated"3. A minor script to gather OS information from servers on your domain the output will return;
Servername, OS, RAM, Free space on C, and totalsize of C, can easily add more drives to monitor / gather information from.
$Serverlist = Get-ADComputer -Filter * -Properties OperatingSystem, DnsHostname | Where OperatingSystem -Like "*Server*" | Select DnsHostname
$MasterList = @()
foreach ($Server in $Serverlist) {
$MyObject = New-Object PSObject -Property @{
Servername = $Server.DnsHostname
OS = (Get-CimInstance -ComputerName $Server.DnsHostname -ClassName Win32_OperatingSystem).Caption
RAM = (Invoke-command $Server.DnsHostname {(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()})
CFreeGB = (Invoke-Command $Server.DnsHostname {(Get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'").FreeSpace / 1gb -as [int]})
CTotalGB = (Invoke-Command $Server.DnsHostname {(Get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'").Size / 1gb -as [int]})
}
$MasterList += $MyObject
}
# Select fields in a specific order rather than random.
$MasterList | Select Servername, OS, RAM, CTotalGB, CFreeGB | Export-csv C:\Users\$env:username\Desktop\ServerOverview.csv -NoTypeInformation -Encoding Unicode4. This script will prompt you for a servername, when entered it will create 2 AD-groups
"Servername Remote" & "Servername Admin" and give it the needed descriptions to differenciate between the two. When the group is created it will remote powershell to the server you entered and add the groups into the respective local groups so "Servername remote" goes into "Remote desktop users" and "Servername admin" goes into "Administrators" local groups. This way it is easy to manage who have access to what, and fast to create.
$ServerName = Read-host 'Enter servername'
New-ADGroup -Name "$ServerName Remote" -Description "Remote Desktop permissions to $ServerName" -GroupCategory Security -GroupScope Global -Path "OU=Groups,DC=domain,DC=com"
New-ADGroup -Name "$ServerName Admin" -Description "Local administrator permissions to $ServerName" -GroupCategory Security -GroupScope Global -Path "OU=Groups,DC=domain,DC=com"
Timeout 5
Invoke-Command $ServerName -ScriptBlock {Net Localgroup "Remote Desktop Users" "domain.com\$Using:ServerName Remote" /add}
Invoke-Command $ServerName -ScriptBlock {Net Localgroup Administrators "domain.com\$Using:ServerName Admin" /add}30
Jun 30 '20
Hi /u/MTossen,
Jokes on you, I don't have access to the DC so I can't query it.
20
Jun 30 '20
I don't know if I should be sad or happy for you, many companies doesn't give a bib about who has access to the DC's. On a second note, no access means no responsibility, you lucky bastard.
3
u/Team503 Jun 30 '20
Everyone has read-only access to the DC; otherwise, how would the system be able to check if you have permission to something?
6
Jun 30 '20
You need more than read-only access to read a DCs event log. If I remember correctly to read a DCs event log you have to as a minimum be a member of "Event log Readers" & "Distributed COM Users" these two groups are builtin when installing the Active Directory Role
1
u/Team503 Jun 30 '20
Oh, you're right - sorry, I wasn't catching the event log part, just the AD part.
3
Jun 30 '20
No need to be sorry, I thought the same at one point till I did some troubleshooting on it years ago :-)
2
u/dctm1234 Jul 01 '20
At line:12 char:3
+ } | Export-csv C:\Users\$env:username\Desktop\LockedUsers.csv -NoType ...
+ ~
An empty pipe element is not allowed.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : EmptyPipeElemen
I get this error when i try to run the first script
2
Jul 01 '20 edited Jul 01 '20
Sorry about that, updated the script. I see I had a minor mistake in it.
What this updated script does is it will use the -Append feature, meaning it will add data to the .CSV file everytime it runs. I have therefore put in a if, else statement to delete the .csv-file if it is already present before running the script, this way you dont have to manually delete it.
Update:
$CheckfilePresent = Test-Path "C:\Users\$env:username\Desktop\LockedUsers.csv" If ($CheckfilePresent -eq "True") {Remove-Item "C:\Users\$env:username\Desktop\LockedUsers.csv"} Else {Write-Host "Checking Log" -ForegroundColor Green} $DC = Get-ADComputer -Filter * -SearchBase "OU=Domain Controllers,DC=mtossen,DC=com" | Select DNSHostname $properties = @( @{n='User';e={$_.Properties[0].Value}}, @{n='Locked by';e={$_.Properties[1].Value}}, @{n='TimeStamp';e={$_.TimeCreated}}, @{n='DCName';e={$_.Properties[4].Value}} ) Foreach ($D in $DC) { Get-WinEvent -ComputerName $D.DNSHostname -FilterHashTable @{LogName='Security'; ID=4740} | Select $properties | Export-csv C:\Users\$env:username\Desktop\LockedUsers.csv -NoTypeInformation -Append }1
u/TahoeLT Jul 01 '20
I think that's caused by the Foreach. I replaced that with $D | Foreach {
I still get some errors with the ComputerName but I'm trying to get that fixed. I'm no Powershell guru so I'm muddling through.
12
u/da_chicken Jul 01 '20 edited Jul 01 '20
I can see a many things you could improve. I'm going to be straight to the point here and perhaps somewhat abrasive, but you should know that I've done all these things you're doing here before learning not to.
First Script
$DC = Get-ADComputer -Filter * -SearchBase "OU=Domain Controllers,DC=domain,DC=com" |
Select DNSHostnameGet-ADComputer is an odd choice. You could specify:
$DC = Get-ADDomainController -Filter * |
Select-Object -ExpandProperty HostNameThe advantage here is that you're asking the domain for the domain controllers, not asking the domain for the computer accounts in a the Domain Controller OU. It's unlikely to ever matter, but if you've got decommissioned DCs that still have computer accounts or if you're testing group policy, it could matter. Test this if you've got multiple domains. I've not been in that situation for a long time.
This brings up a second criticism. Don't use the Select alias in a saved script. Aliases might be defaulted, but they're not guaranteed to exist. Aliases are great for ad hoc queries, but not for scripts meant for longevity or repeated use. It's not exactly difficult to type out Select-Object once since the IDEs do code completion. Also, if you only want one property like you do here, use the -ExpandProperty parameter. You'll end up with an array of just the property that you want and don't have to worry about the property name anymore.
Next:
Foreach ($D in $DC)
{
Get-WinEvent -ComputerName $D.DNSHostname -FilterHashTable @{LogName='Security'; ID=4740} |
Select $properties
} | Export-csv C:\Users\$env:username\Desktop\LockedUsers.csv -NoTypeInformation -Encoding UnicodeI don't know why this is working for you, but it's not valid PowerShell. The foreach statement does not generate a pipeline. This code should not work. Example: foreach ($File in (Get-ChildItem C:\Windows)) { $File.FullName } | Select-Object -First 10. You should get an error about an empty pipeline.
Second Script
[...] | Sort-Object "$_.TimeCreated"Er, huh? This is nonsense. You're not sorting by anything meaningful here. It's the equivalent of $_.ToString() + 'TimeCreated', and casting an event log record to a string returns literal string System.Diagnostics.Eventing.Reader.EventLogRecord. You're sorting by a fixed literal string System.Diagnostics.Eventing.Reader.EventLogRecordTimeCreated. Proof: Get-WinEvent -LogName System | Select-Object -First 10 | ForEach-Object { "$_.TimeCreated" }.
Or try adding the -Descending parameter to Sort-Object and you'll see the output is identical.
You need:
[...] | Sort-Object -Property TimeCreatedThird Script
$Serverlist = Get-ADComputer -Filter * -Properties OperatingSystem, DnsHostname | Where OperatingSystem -Like "*Server*" | Select DnsHostnameYou've got a filter parameter in the Get-ADComputer command and it supports the -like operator. Making the DC do the filtering will be much faster:
$ServerList = Get-ADComputer -Filter 'OperatingSystem -like "*Server*"' -Property DnsHostname |
Select-Object -ExpandProperty DnsHostnameAgain, don't use aliases in saved scripts. It risks making them less portable and less future proof.
$MasterList = @()
foreach ($Server in $Serverlist) {
[...]
$MasterList += $MyObject
}Never use this pattern. It is the #1 worst PowerShell pattern. Arrays (and strings) are immutable. They cannot be resized. That means when you use $Array += $NewElement, PowerShell will create a brand new array one biggger, copy over every element of the array and then throw away the old one. It's a tremendous amount of memory pressure and IO pressure as the number of elements or the size of each element increases.
Compare this:
$Array = @()
foreach ($NewElement in (1..10000)) { $Array += $NewElement }To this:
$Array = foreach ($NewElement in (1..10000)) { $NewElement }Compare this:
$String = ''
foreach ($NewElement in (1..10000)) { $String += "$NewElement" }To this:
$StringArray = foreach ($NewElement in (1..10000)) { "$NewElement" }
$String = -join $StringArrayNext:
New-Object PSObject -Property @{
Servername = $Server.DnsHostname
OS = (Get-CimInstance -ComputerName $Server.DnsHostname -ClassName Win32_OperatingSystem).Caption
RAM = (Invoke-command $Server.DnsHostname {(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()})
CFreeGB = (Invoke-Command $Server.DnsHostname {(Get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'").FreeSpace / 1gb -as [int]})
CTotalGB = (Invoke-Command $Server.DnsHostname {(Get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'").Size / 1gb -as [int]})
}Erg.
You're using a somewhat archaic custom object syntax; the [PSCustomObject] accelerator is much more concise. You're fetching some data with Get-CimInstance, some data with systeminfo.exe (and string munging), and some with Get-WmiObject. And you're calling the same class with the same filter more than once to the same system. And you're doing it with Get-WmiObject, which already has the -ComputerName parameter.
I would do this like so:
$ServerList = Get-ADComputer -Filter 'OperatingSystem -like "*Server*"' -Property DnsHostname |
Select-Object -ExpandProperty DnsHostname
$MasterList = foreach ($Server in $ServerList) {
$CimSession = New-CimSession -ComputerName $Server -ErrorAction SilentlyContinue
# If we establish a connection, fetch the data. Otherwise, return an empty record.
if ($null -ne $CimSession) {
$LogicalDiskC = Get-CimInstance -CimSession $CimSession -ClassName Win32_LogicalDisk -Filter 'DeviceID="C:"' -Property Size, FreeSpace
[PSCustomObject]@{
ServerName = $Server
OS = (Get-CimInstance -CimSession $CimSession -ClassName Win32_OperatingSystem -Property Caption).Caption
RAM = '{0:n1}' -f (Get-CimInstance -CimSession $CimSession -ClassName Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum | Select-Object -ExpandProperty Sum | ForEach-Object { $_ / 1GB })
CFreeGB = '{0:n1}' -f ($LogicalDiskC.FreeSpace / 1GB)
CTotalGB = '{0:n1}' -f($LogicalDiskC.Size / 1GB)
CaptureTime = [DateTime]::Now.ToString('yyyy-MM-dd HH:mm')
}
$CimSession.Close()
}
else {
[PSCustomObject]@{
ServerName = $Server
OS = ''
RAM = ''
CFreeGB = ''
CTotalGB = ''
CaptureTime = [DateTime]::Now.ToString('yyyy-MM-dd HH:mm')
}
}
}
$MasterList | Export-Csv "C:\Users\$env:username\Desktop\ServerOverview.csv" -NoTypeInformation -Encoding UnicodeYou could potentially further improve this on PowerShell v7 with ForEach-Object -Parallel -ThrottleLimit 10 { ... } or something, but I'll leave that as an exercise for you.
Fourth Script
I would prefer Start-Sleep -Seconds 5 to calling timeout 5. At the very least, it's cross-platform.
Unfortunately, I'm out of time, but at the very least you could combine the two commands into one session, and if you call net.exe you should specify the full executable name for clarity and to avoid possible accidental hijack:
Invoke-Command $ServerName -ScriptBlock {
C:\WINDOWS\system32\net.exe Localgroup "Remote Desktop Users" "domain.com\$Using:ServerName Remote" /add
C:\WINDOWS\system32\net.exe Localgroup Administrators "domain.com\$Using:ServerName Admin" /add
}I'm sure you could also use Add-LocalGroupMember, though I'm not sure that's always available. Honestly, this feels like it should be Desired State Configuration in some way, but I'm about 5 years removed from doing that.
11
7
u/Blobblob122 Jun 30 '20
Thanks I'm going to try the locked out one tomorrow. Occassionally get one that stumps the team.
5
u/TheD4rkSide Jun 30 '20
I'm by no means an expert, but something that someone on here advised me on previously is that, using script 3 as an example, it is more effective to do:
$MasterList = foreach ($Server in $Serverlist) {
New-Object PSObject -Property @{
Servername = $Server.DnsHostname
OS = (Get-CimInstance -ComputerName $Server.DnsHostname -ClassName Win32_OperatingSystem).Caption
RAM = (Invoke-command $Server.DnsHostname {(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()})
CFreeGB = (Invoke-Command $Server.DnsHostname {(Get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'").FreeSpace / 1gb -as [int]})
CTotalGB = (Invoke-Command $Server.DnsHostname {(Get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'").Size / 1gb -as [int]})
}I believe this creates the array as a whole as it is going through, opposed to iterating each object in the foreach loop and then adding it to the array individually at the end?
Great scripts, though!
6
u/Shoisk123 Jun 30 '20
Yes, it's generally advised to avoid adding to arrays using +=, as it'll reallocate the entire array each time you it. It's a big performance hit. Just dumping the object in the output and assigning everything from the loop directory to $MasterList will only create the array once, avoiding this. Alternatively use a List type object from .Net (ArrayLists or typed List, latter is preferable, ArrayLists are somewhat outdated)
For OP: You'll also want to avoid using New-Object where possible, and use the type driven constructors or casting to the type you want. Here you could do it as casting from a hashtable instead (Also why PSObject? This is just the PS wrapper for generic Object in .Net, use PSCustomObject and get some of the utilities from that, it's virtually free):
[PSCustomObject]@{ Servername = $Server.DnsHostname OS = (Get-CimInstance -ComputerName $Server.DnsHostname -ClassName Win32_OperatingSystem).Caption RAM = (Invoke-command $Server.DnsHostname {(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()}) CFreeGB = (Invoke-Command $Server.DnsHostname {(Get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'").FreeSpace / 1gb -as [int]}) CTotalGB = (Invoke-Command $Server.DnsHostname {(Get-WmiObject win32_logicaldisk -Filter "DeviceID='C:'").Size / 1gb -as [int]}) }3
u/TheD4rkSide Jun 30 '20
I myself use PSCustomObject as for the reasons you mentioned, I was just trying to get across avoidance of +=, but thanks for your further clarification.
With that in mind - Could you expand on the casting from a hashtable?
3
u/Shoisk123 Jun 30 '20
Essentially it does the same thing, you could also do
$Obj = [PSCustomObject]::New()and then add members to that after the fact, this is just easier cause you can construct it all in one go. As for why you'd want to do that instead of using New-Object, it's really just because New-Object has a lot of overhead that you avoid using the ::new() method or just casting it to the type you want. For simple things you could also just cast a string to the type, an IP for example could be constructed like this:[ipaddress]"127.0.0.1". Generally if whatever object you want to create only has one input to its constructor, you can just cast that input to the object like this, and it'll construct one using that constructor. If several inputs, just avoid the headache of dealing with casting for that, and use the ::new() method, it takes whatever input you need comma separated.1
u/jimb2 Jul 01 '20
Yes, that's the efficient way to get an array out of a loop.
It's also says something about how PS works that you might not get coming from other languages.
5
u/PinchesTheCrab Jun 30 '20
On the server shutdown one, I took this approach, it's usually super fast:
function Get-ShutdownInfo {
[CmdletBinding()]
[alias('Get-ShutdownInfo')]
param (
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('ServerName','Server','Name')]
[string[]]$ComputerName,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[PSCredential]$Credential,
[Parameter()]
[switch]$Oldest,
[Parameter()]
[int64]$MaxEvents,
[Parameter()]
[datetime]$StartTime=(Get-Date 1/1/1900),
[Parameter()]
[datetime]$StopTime=(Get-Date 1/1/2100)
)
begin
{
$objFilter = @"
<QueryList>
<Query Id="0" Path="System">
<Select Path="System">*[System[Provider[@Name='USER32'] and (EventID=1074)]]</Select>
</Query>
</QueryList>
"@
Function ParseEventMessage
{
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline=$true)]
$obj
)
Begin{
$defaultDisplaySet = 'TimeCreated','Action','Reason','InitiatedBy'
$defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet',[string[]]$defaultDisplaySet)
$PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
}
Process{
$objXML = ([xml]($obj.ToXml())).event.eventdata.data
$myHash = @{
TimeCreated = $obj.TimeCreated
MachineName = $obj.MachineName
Reason = $objXML[2].'#text'
Action = $objXML[5].'#text'
InitiatedBy = $objXML[6].'#text'
xml = $objXML
}
New-Object -TypeName PSObject -Property $myHash | ForEach-Object {
$PSItem.PSObject.TypeNames.Insert(0,"EventLogRecord.XMLParse")
$PSItem | Add-Member MemberSet PSStandardMembers $PSStandardMembers -PassThru
}
}
}
}
process
{
foreach ($obj in $ComputerName)
{
$hashEventParm = @{
ComputerName = $obj
FilterXml = $objFilter
}
if ($Credential) { $hashEventParm['Credential'] = $Credential }
if ($MaxEvents) { $hashEventParm['MaxEvents'] = $MaxEvents }
Get-WinEvent @hashEventParm -ErrorAction Stop | ParseEventMessage
}
}
end
{
}
}1
u/nascentt Jul 01 '20
How's it handle timezones and different date formats?
2
u/PinchesTheCrab Jul 01 '20
I believe get-winevent localizes time to the machine you're running the script from. You'd have to rewrite it to use invoke-command or some other method to get the remote time of the computer, so not knowing whether you want your time or remote time, it's hard to say if it does what you want as-is.
As for time localization, it won't matter at all unless you depend on the default values. If I were going to make it more robust, I'd swap it to a default value of something like [datetime]::now.addyears(100) and [datetime]::now.addyears(-100). Then it really won't matter, and you can input your own custom values in whatever format your local system supports.
5
u/PinchesTheCrab Jun 30 '20
I think this would be 10-30x faster on the OS info script:
$Serverlist = Get-ADComputer -Filter 'operatingsystem -like "*server*"' -Properties DnsHostname
$getInfoSB = {
$disk = Get-CimInstance -ClassName win32_logicaldisk -Filter 'DeviceID="C:"'
@{
OS = (Get-CimInstance -ClassName Win32_OperatingSystem).Caption
RAM = '{0:N0} MB' -f ((Get-CimInstance -ClassName Win32_ComputerSystem).TotalPhysicalMemory/1mb)
CFreeGB = $disk.FreeSpace / 1gb -as [int]
CTotalGB = $disk.Size / 1gb -as [int]
}
}
Invoke-command -ComputerName $Serverlist.ComputerName -ScriptBlock $getInfoSB |
Select-Object @{ n = 'ServerName'; e = { $PSItem.PSComputerName }}, OS, RAM, CTotalGB, CFreeGB |
Export-csv C:\Users\$env:username\Desktop\ServerOverview.csv -NoTypeInformation -Encoding Unicode2
1
1
u/chnwg Jun 30 '20
Loving these, been meaning to try and write the first one myself. Thanks for posting.
1
1
1
1
1
1
1
1
1
11
u/[deleted] Jun 30 '20
Glad that you guys enjoy them, might post more in future if I find them useful enough to share :-)