Trying to back up my Bitlocker Key to ADDS Through Script - windows

I'm trying to automatize the process of storing BitLocker Keys to ADDS.
I wanna be able to run the following script at logon, in order to do that, as the OS is deployed through WDS which already encrypts the drive:
$BitVolume = Get-BitLockerVolume -MountPoint $env:SystemDrive
$RecoveryKey = $BitVolume.KeyProtector | Where-Object { $_.KeyProtectorType -eq 'RecoveryPassword' }
Backup-BitLockerKeyProtector -MountPoint $env:SystemDrive -KeyProtectorId $RecoveryKey.KeyProtectorID
BackupToAAD-BitLockerKeyProtector -MountPoint $env:SystemDrive -KeyProtectorId $RecoveryKey.KeyProtectorID
I always get access denied as this has to run as admin...
Is there any command I can use prior the code to run it as admin?
I've googled but I found no useful info to actually do this...

As for the access denied part... as was already sated, you need to start your PowerShell session as an admin. However, as a point of note about your code, you are only targeting the system/os volume... which may not be the only volume that's encrypted. If you want to programmatically backup all of the encrypted volumes, may I suggest one of the two following options...
One-liner:
Get-BitLockerVolume | where {$_.VolumeStatus -like "FullyEncrypted"} | foreach {foreach($Key in $_.KeyProtector){if($Key -like "RecoveryPassword"){Backup-BitLockerKeyProtector -MountPoint $_.mountpoint -KeyProtectorId $key.KeyProtectorId}}}
Or, if you prefer something a little bit easier to read...
Script Block:
foreach ($BLV in Get-BitLockerVolume){
if ($BLV.VolumeStatus -like "FullyEncrypted"){
foreach ($Key in $BLV.KeyProtector) {
if ($Key -like "RecoveryPassword") {
Backup-BitLockerKeyProtector -MountPoint $BLV.MountPoint -KeyProtectorId $Key.KeyProtectorId
}#if
}#foreach
}#if
}#foreach
Neither is super eloquent... but, with this method it will grab all of the encrypted volumes on the system and add them to AD. You would need to modify the code slightly to add the AAD backup option you cited of course.
P.S. I'm only responding because I recently had to solve this problem of multi-volume backups as a one-liner solution and figured I would share it since your post was a top search result when I looked for a pre-canned solution. Cheers! :)

Related

Powershell script: List files with specific change date (Amount if possible)

For license porpuses I try to automate the counting process instead of having to login into every single server, go into directory, search a file name and count the results based on the change date.
Want I'm aiming for:
Running a powershell script every month that checks the directory "C:\Users" for the file "Outlook.pst" recursively. And then filters the result by change date (one month or newer). Then packing this into an email to send to my inbox.
I'm not sure if that's possible, cause I am fairly new to powershell. Would appreciate your help!
It is possible.
I dont know how to start a ps session on a remote computer, but I think the cmdlet Enter-PSSession will do the trick. Or at least it was the first result while searching for "open remote powershell session". If that does not work use the Invoke-Command as suggested by lit to get $outlookFiles as suggested below.
For the rest use this.
$outlookFiles = Get-ChildItem -Path "C:\Users" -Recurse | Where-Object { $_.Name -eq "Outlook.pst" }
Now you have all files that have this name. If you are not familiar with the pipe in powershell it redirects all objects it found with the Get-ChildItem to the next pipe section and here the Where-Object will filter the received objects. If the current object ($_) will pass the condition it is returned by the whole command.
Now you can filter these objects again to only include the latest ones with.
$latestDate = (Get-Date).AddMonths(-1)
$newFiles = $outlookFiles | Where-Object { $_.LastAccessTime -gt $latestDate }
Now you have all the data you want in one object. Now you only have to format this how you like it e.g. you could use $mailBody = $newFiles | Out-String and then use Send-MailMessage -To x#y.z -From r#g.b -Body $mailBodyto send the mail.

How to use the log parser in Windows PowerShell by using for each loops to query the logs from multiple exchange servers?

I would like to use the below mentioned command in windows powershell by using the for each loops. Please let me know if you have any ideas on this query.
As I have little bit idea to input multiple values for the FROM parameter as because I need to search logs from the different servers from the given location.
I would like to feed the values for FROM filed like below but I don't have an complete idea to create the entire PowerShell script structure.
\\server1\d$\Program Files\Microsoft\Exchange\V15\Logging\HttpProxy\Mapi\*.*
\\server2\d$\Program Files\Microsoft\Exchange\V15\Logging\HttpProxy\Mapi\*.*
Command I created for individual server:
LogParser.exe "
SELECT DateTime,AuthenticatedUser,UserAgent
FROM 'd:\Program Files\Microsoft\Exchange\V15\Logging\HttpProxy\Mapi\*.*'
WHERE AuthenticatedUser LIKE '%user1%'
AND UserAgent LIKE '%Microsoft Office%'" -i:CSV -o:csv > "C:\Log parser\server1\1.csv"
Assuming you have access to the administrative shares on the remote servers you could do something like this:
$servers = 'server1', 'server2', ...
$servers | ForEach-Object {
LogParser.exe -i:csv -o:csv -q "SELECT DateTime,AuthenticatedUser,UserAgent
FROM '\\${_}\D$\Program Files\Microsoft\Exchange\V15\Logging\HttpProxy\Mapi\*.*'
WHERE AuthenticatedUser LIKE '%user1%'
AND UserAgent LIKE '%Microsoft Office%'" |
Out-File "C:\Log parser\${_}.csv"
}

List Last Windows Password Change For All Users On A Non-Domain System

I have found an answer to this question for systems that are attached to an AD domain controller. However, this question is for standalone systems where there is no possibility of attaching to a domain controller. Essentially, air-gapped systems.
Short and sweet: Is there a way to list the last time each user changed their Windows password for a non-domain, air-gapped system (either Windows 7 or 10) all at once either as a batch file or PowerShell script?
I know that net user {username} | find /I "Password last set" will do it for them one at a time. However, that would be tedious to run multiple times per machine and we have over 60 systems of this type. So I'm looking for a way to do this in one fell swoop, if possible.
As a caveat, we don't have the option of installing the activedirectory module in PowerShell for this. Also, since the majority of the systems are Windows 7, we don't have access to the Bash command line tools that would be available in Windows 10.
Any and all help with regard to this is appreciated.
Here's one way using the ADSI WinNT provider:
$computerName = [Net.Dns]::GetHostName() # i.e., local computer
$computer = [ADSI] "WinNT://$computerName,Computer"
$childObjects = $computer.Children
foreach ( $childObject in $childObjects ) {
if ( $childObject.Class -eq "User" ) {
if ( $childObject.PasswordAge[0] -gt 0 ) {
$pwdLastSet = (Get-Date).AddSeconds(-$childObject.PasswordAge[0])
}
else {
$pwdLastSet = $null
}
$childObject | Select-Object `
#{Name="AdsPath"; Expression={$_.AdsPath}},
#{Name="PasswordLastSet"; Expression={$pwdLastSet}}
}
}

Powershell Win32_ServerConnection on TS Server 2012 no result

I'm trying to execute a simple command on one of a TS part of a RDS farm and I get no result. I just want to see every connection on the TS using:
Get-WmiObject Win32_ServerConnection -ComputerName MYTSSERVER
and I get no result at all. Any idea what could be the cause?
Thank you
Win32_ServerConnection shows active connections to network shares on the machine. If you do not have active network shares or connections to them there will be no results.
I assume since they're terminal servers in an RDS farm that you're looking for remote sessions in which case you want Win32_LoggedOnUser. That said, Win32_LoggedOnUser doesn't clear sessions that have been disconnected or even closed. It shows all sessions since the last computer reboot whether that information is still valid or not.
It's incredibly annoying but the best way to list real and active sessions is to list all copies of explorer.exe running on the machine and who they belong to or use the cmd application query.exe. There are ways in PowerShell to turn the output of query.exe into objects:
$Users = query user /server:TERMSERV01 2>&1
$Users = $Users | ForEach-Object { (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1 none $2' -replace "\s{2,}", "," -replace "none", $null)) } | ConvertFrom-Csv
$Users

Retrieving computers where specified user is in local admin group?

I have windows domain network, i have about 3000 hosts in there. I would like to just check the info which of those hosts having specified technical user account in their local admin groups. I am not that great at power shell, though I know the base things.
I belive that I have to make a list of all hosts across several subnets I have and then run a script that will try to log on those hosts with looking account credentials.
What could be the best solution?
There is a very detailed post on TechNet about listing all computers in domain.
And here's the WMI query part (PowerShell, $aComputerList is a list of computer names):
foreach ($sComputerName in $aComputerList) {
$sUserPattern = 'Win32_UserAccount.Domain="domainname",Name="username"'
$sGroupPattern = 'Win32_Group.Domain="{0}",Name="Administrators"' -f $sComputerName
$oResult = Get-WmiObject -ComputerName $sComputerName -Class Win32_GroupUser | `
Where-Object {
($_.groupcomponent -match $sGroupPattern) -and `
($_.partcomponent -match $sUserPattern)
}
[Bool]$oResult
}
The hard part is that some computers probably won't be reachable (if they're turned off for instance). So you'll need to run your script several times and remove computers from the list as you get responses from them.

Resources