Import Local Group from remote server via Powershell - powershell

I am working on the easiest way to copy security settings from one server to another, using Powershell, and I'm curious if it's possible to import and entire group, including it's Description and Members properties?
Below is the script I currently have. It appears that I can access the local Group on the remote server using the ADSI adapter, however the Create command bombs with the following error message
Exception calling "Create" with "2" argument(s): "Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))"
At \prdhilfs02\install\Monet\ServerUpgrade\DEVHILWB119\Scripts\LocalUsersAndGroups.ps1:25 char:1+ $objCreate = $cn.Create("Group", $objRemote)
$computerName = "DEVWB89"
$objRemote = [ADSI]("WinNT://$computerName/$groupName")
$cn = [ADSI]"WinNT://localhost"
$cn.Create("Group", $objRemote)
EDIT
So I can accomplish what I want by using the script below. I can use the Group Name and Description from the remote server as well as the group information. However, is there a way to use Powershell to simply add the System.DirectoryServices.DirectoryEntry object, and all it's properties, to the local machine? Also, another drawback, is that I have to hard-code the domain for the Group's users.
$cn = [ADSI]"WinNT://localhost"
$computerName = "DEVWB89"
foreach($groupName in $groupArray)
{
$objRemote = [ADSI]("WinNT://$computerName/$groupName")
$objGroup = $cn.Create("Group", $($objRemote.Name))
$objGroup.setinfo()
$objGroup.description = $objGroup.Description
$objGroup.setinfo()
$Members = #($objRemote.psbase.Invoke("Members"))
$Members | ForEach-Object {$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null) + ",";}
$tempArray = $MemberNames -split ","
foreach($member in $tempArray)
{
$objGroup.Add("WinNT://SYMETRA/$member, user")
}
}

This will list out all the members of the groups:
$Members = #($objRemote.psbase.Invoke("Members"))
$Members | ForEach-Object {$MemberNames += $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null);}
$MemberNames
More helpful info:
PS C:\Users\YourUser\Desktop> $objAdmin = [ADSI]("WinNT://localhost/Administrator")
PS C:\Users\YourUser\Desktop> $objAdmin | gm
TypeName: System.DirectoryServices.DirectoryEntry
Name MemberType Definition
---- ---------- ----------
ConvertDNWithBinaryToString CodeMethod static string ConvertDNWithBinaryToString(psobject deInstance, psobject dnWithBinaryIns...
ConvertLargeIntegerToInt64 CodeMethod static long ConvertLargeIntegerToInt64(psobject deInstance, psobject largeIntegerInstance)
AutoUnlockInterval Property System.DirectoryServices.PropertyValueCollection AutoUnlockInterval {get;set;}
BadPasswordAttempts Property System.DirectoryServices.PropertyValueCollection BadPasswordAttempts {get;set;}
Description Property System.DirectoryServices.PropertyValueCollection Description {get;set;}
FullName Property System.DirectoryServices.PropertyValueCollection FullName {get;set;}
HomeDirDrive Property System.DirectoryServices.PropertyValueCollection HomeDirDrive {get;set;}
HomeDirectory Property System.DirectoryServices.PropertyValueCollection HomeDirectory {get;set;}
LastLogin Property System.DirectoryServices.PropertyValueCollection LastLogin {get;set;}
LockoutObservationInterval Property System.DirectoryServices.PropertyValueCollection LockoutObservationInterval {get;set;}
LoginHours Property System.DirectoryServices.PropertyValueCollection LoginHours {get;set;}
LoginScript Property System.DirectoryServices.PropertyValueCollection LoginScript {get;set;}
MaxBadPasswordsAllowed Property System.DirectoryServices.PropertyValueCollection MaxBadPasswordsAllowed {get;set;}
MaxPasswordAge Property System.DirectoryServices.PropertyValueCollection MaxPasswordAge {get;set;}
MaxStorage Property System.DirectoryServices.PropertyValueCollection MaxStorage {get;set;}
MinPasswordAge Property System.DirectoryServices.PropertyValueCollection MinPasswordAge {get;set;}
MinPasswordLength Property System.DirectoryServices.PropertyValueCollection MinPasswordLength {get;set;}
Name Property System.DirectoryServices.PropertyValueCollection Name {get;set;}
objectSid Property System.DirectoryServices.PropertyValueCollection objectSid {get;set;}
Parameters Property System.DirectoryServices.PropertyValueCollection Parameters {get;set;}
PasswordAge Property System.DirectoryServices.PropertyValueCollection PasswordAge {get;set;}
PasswordExpired Property System.DirectoryServices.PropertyValueCollection PasswordExpired {get;set;}
PasswordHistoryLength Property System.DirectoryServices.PropertyValueCollection PasswordHistoryLength {get;set;}
PrimaryGroupID Property System.DirectoryServices.PropertyValueCollection PrimaryGroupID {get;set;}
Profile Property System.DirectoryServices.PropertyValueCollection Profile {get;set;}
UserFlags Property System.DirectoryServices.PropertyValueCollection UserFlags {get;set;}
PS C:\Users\YourUser\Desktop> $Members[0].GetType().InvokeMember("FullName", "GetProperty", $null, $Members[0], $null)
Exception calling "InvokeMember" with "5" argument(s): "The specified domain either does not exist or could not be contacted.
"
At line:1 char:1
+ $Members[0].GetType().InvokeMember("FullName", "GetProperty", $null, $Members[0] ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : COMException
PS C:\Users\YourUser\Desktop> $Members[0].GetType().InvokeMember("PasswordAge", "GetProperty", $null, $Members[0], $null)
PS C:\Users\YourUser\Desktop> $Members[0].GetType().InvokeMember("UserFlags", "GetProperty", $null, $Members[0], $null)

Related

Exporting a Powershell object containing multiple sets to CSV

I have a Powershell object which is the result of DSInternals Test-PasswordQuality cmdlet that I'd like to use as a Power BI dataset; it's a bunch of sets of user accounts, ex.
PS C:\> $result | get-member
TypeName: DSInternals.PowerShell.PasswordQualityTestResult
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
AESKeysMissing Property System.Collections.Generic.ISet[string] AESKeysMissing {get;set;}
ClearTextPassword Property System.Collections.Generic.ISet[string] ClearTextPassword {get;set;}
DefaultComputerPassword Property System.Collections.Generic.ISet[string] DefaultComputerPassword {get;set;}
DelegatableAdmins Property System.Collections.Generic.ISet[string] DelegatableAdmins {get;set;}
DESEncryptionOnly Property System.Collections.Generic.ISet[string] DESEncryptionOnly {get;set;}
DuplicatePasswordGroups Property System.Collections.Generic.IEnumerable[System.Collections.Generic.ISet[string]] DuplicatePasswordGroup…
EmptyPassword Property System.Collections.Generic.ISet[string] EmptyPassword {get;set;}
Kerberoastable Property System.Collections.Generic.ISet[string] Kerberoastable {get;set;}
LMHash Property System.Collections.Generic.ISet[string] LMHash {get;set;}
PasswordNeverExpires Property System.Collections.Generic.ISet[string] PasswordNeverExpires {get;set;}
PasswordNotRequired Property System.Collections.Generic.ISet[string] PasswordNotRequired {get;set;}
PreAuthNotRequired Property System.Collections.Generic.ISet[string] PreAuthNotRequired {get;set;}
SmartCardUsersWithPassword Property System.Collections.Generic.ISet[string] SmartCardUsersWithPassword {get;set;}
WeakPassword Property System.Collections.Generic.ISet[string] WeakPassword {get;set;}
PS C:\> $result | select LMHash
LMHash
------
{a_user, another_user, yet_another_user…}
I'd like to export this to one csv where each array is its own column. If I simply do
$result | export-csv .\result.csv -NoTypeInformation
I do get a separate column for each set, but then just the the Set object type under each, ex.
How can I get a list of users, with each user in it's own cell, like this?
UPDATE
As an example, one of the elements of $result.PSObject.Properties is:
MemberType : Property
Value : {user, another_user, another_user…}
IsSettable : True
IsGettable : True
TypeNameOfValue : System.Collections.Generic.ISet`1[[System.String, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e]]
Name : LMHash
IsInstance : True
So I think I need to iterate through the $result.PSObject.Properties for the column names and then also iterate through essentially $(result.PSObject.Properties).Value to get the users into separate cells in the csv. But doing them via index, i.e. $(result.PSObject.Properties).Value[1] results in the property types in the csv instead of the actual values. I tried nested foreach loops but still couldn't quite crack it.
Given the scenario, you can use a loop (in this case I will use a for loop to demonstrate this) to iterate through the listings using a PSCustomObject:
$maxCount = [math]::Max($result.LMHash.Count,$result.ClearTextPassword.Count)
for ($i = 0; $i -lt $maxCount; $i++)
{
[PSCustomObject]#{
LMHash = $result.LMHash[$i]
ClearTextPassword = $result.ClearTextPassword[$i]
} #| Export-Csv -Path ".\result.csv" -Append -NoTypeInformation
}
$maxCount will be the max number of iterations the for loop should iterate to; given those two properties of LMHash, and ClearTextPassword.

Win Powershell get list of active local users

I want to get the list of active local users on the windows server. When I do Get-LocalUser, I get following output
Name Enabled Description
---- ------- -----------
DefaultAccount False A user account managed by the system.
Guest False Built-in account for guest access to the computer/domain
labadmin True Built-in account for administering the computer/domain
Test True
WDAGUtilityAccount False A user account managed and used by the system for Windows Defender Application Guard scen...
I tried GetLocalUser -Enabled True and got following error
Get-LocalUser : A parameter cannot be found that matches parameter name 'Enabled'.
At line:1 char:79
+ ... ng = New-Object Text.UTF8Encoding $false; Get-LocalUser -Enabled True
+ ~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-LocalUser], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetLocalUserCommandnon-zero return code
What is the correct parameter to filter out the disabled users?
Get-Help -Name "Get-LocalUser" (also written help get-localuser) will show you that the only available parameters are:
SYNTAX
Get-LocalUser [[-Name] <String[]>] [<CommonParameters>]
Get-LocalUser [[-SID] <SecurityIdentifier[]>] [<CommonParameters>]
And there is no parameter to filter on the enabled users. You need to get the results back, then filter afterwards. From the results in your question, the Enabled column shows you that the user objects probably have a property called Enabled which you can check for the filtering:
$users = Get-LocalUser
$enabledUsers = $users | Where-Object { $_.Enabled }
If you did not know that, or that did not work because the column name is not exactly the same as the property name, you could run $users | Get-Member to see what properties the user objects have, and then look through them for ones to check. Enabled is shown in the result:
TypeName: Microsoft.PowerShell.Commands.LocalUser
Name MemberType Definition
---- ---------- ----------
Clone Method Microsoft.PowerShell.Commands.LocalUser Clone()
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
AccountExpires Property System.Nullable[datetime] AccountExpires {get;set;}
Description Property string Description {get;set;}
Enabled Property bool Enabled {get;set;}
FullName Property string FullName {get;set;}
LastLogon Property System.Nullable[datetime] LastLogon {get;set;}
Name Property string Name {get;set;}
ObjectClass Property string ObjectClass {get;set;}
PasswordChangeableDate Property System.Nullable[datetime] PasswordChangeableDate {get;set;}
PasswordExpires Property System.Nullable[datetime] PasswordExpires {get;set;}
PasswordLastSet Property System.Nullable[datetime] PasswordLastSet {get;set;}
PasswordRequired Property bool PasswordRequired {get;set;}
PrincipalSource Property System.Nullable[Microsoft.PowerShell.Commands.PrincipalSource] PrincipalSource {ge...
SID Property System.Security.Principal.SecurityIdentifier SID {get;set;}
UserMayChangePassword Property bool UserMayChangePassword {get;set;}

Powershell Get-EventLog find event with the matching string in its message

I need to look through eventLog security ID 4648, and find the last time the user connected to the machine.
Currently this is my code:
$Values = invoke-command -ComputerName $ComputerName {Get-EventLog -LogName Security -InstanceID 4648 | Select-Object -ExpandProperty Message| ForEach-Object {if($_.Log -match "$String2"){
$_
Break }}}
$Values
The aim was to go through each log until a log where the message has the previously defined username is found, and then stop going through EventLog and return that log.
This is working well, except its not matching the correct log with the specified string.
Is there a way to improve how the matching works? So it actually finds the correct log with the specified user?
# Fill in the regex for the userName
$userName = "userName"
$Values = #(invoke-command -ComputerName $ComputerName {
Get-EventLog -LogName Security -InstanceID 4648 | Where-Object { $_.message -match $Using:userName } | Select-Object -First 1)
}
Your above sample won't work since message is of type string, therefore it doesn't have a Log property. Since we want $userName to be avaiable for read access on the remote machine we can use the $Using: syntax. To break the pipeline "iteration" I'm using Select-Object -First 1 which will return the first object passing the Where-Objectclause.
Resulting from that $Values points to a collection of (deserialized) objects (using the #() operator) of type:
TypeName: System.Diagnostics.EventLogEntry#Security/Microsoft-Windows-Security-Auditing/4648
Which means you can change the -First parameter to e.g. 10 and sort the result on the client machine:
$Values | sort TimeGenerated -Descending
If you want to know which properties are available you can use:
> $Values | gm
TypeName: System.Diagnostics.EventLogEntry#Security/Microsoft-Windows-Security-Auditing/4648
Name MemberType Definition
---- ---------- ----------
Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs)
CreateObjRef Method System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Diagnostics.EventLogEntry otherEntry), bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetLifetimeService Method System.Object GetLifetimeService()
GetObjectData Method void ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
GetType Method type GetType()
InitializeLifetimeService Method System.Object InitializeLifetimeService()
ToString Method string ToString()
Category Property string Category {get;}
CategoryNumber Property int16 CategoryNumber {get;}
Container Property System.ComponentModel.IContainer Container {get;}
Data Property byte[] Data {get;}
EntryType Property System.Diagnostics.EventLogEntryType EntryType {get;}
Index Property int Index {get;}
InstanceId Property long InstanceId {get;}
MachineName Property string MachineName {get;}
Message Property string Message {get;}
ReplacementStrings Property string[] ReplacementStrings {get;}
Site Property System.ComponentModel.ISite Site {get;set;}
Source Property string Source {get;}
TimeGenerated Property datetime TimeGenerated {get;}
TimeWritten Property datetime TimeWritten {get;}
UserName Property string UserName {get;}
EventID ScriptProperty System.Object EventID {get=$this.get_EventID() -band 0xFFFF;}
Hope that helps.

Can't access Environment Variable from Remote Server with PowerShell

I have a script to query a list of remote windows servers to retrieve the value of an Environment Variable I have created.
I can see that the variable is indeed there because I can see it when I print all variables: $EnvObj:
try
{
$Name="MY_VAR"
$VerbosePreference="Continue"
# Read a list of server names
$file = New-Object System.IO.StreamReader -Arg "C:\Users\foo\Documents\test.txt"
while ($Computer = $file.ReadLine())
{
if(!(Test-Connection -ComputerName $Computer -Count 1 -quiet))
{
Write-Verbose "$Computer is not online"
Continue
}
try
{
$EnvObj = #(Get-WMIObject -Class Win32_Environment -ComputerName $Computer -EA Stop)
if(!$EnvObj)
{
Write-Verbose "$Computer returned empty list of environment variables"
Continue
}
if($Name)
{
Write-Verbose "Looking for environment variable with the name $name"
$Env = $EnvObj | Where-Object {$_.Name -eq $Name}
# None of these work but printing $EnvObj shows that $Name ("MY_VAR") is there:
$res=[environment]::GetEnvironmentVariable($Name, "Process")
$res1=[environment]::GetEnvironmentVariable($Name, "User")
$res2=[environment]::GetEnvironmentVariable($Name, "Machine")
$res4=$Env:Name
if(!$Env)
{
Write-Verbose "$Computer has no environment variable with name $Name"
Continue
}
}
else
{
Write-Verbose "No environment variable specified. Listing all"
$EnvObj # shows that the requested environment variable is present
}
}
catch
{
Write-Verbose "Error occurred while querying $Computer. $_"
Continue
}
}
}
finally
{
$file.close()
}
The variable itself is owned by <SYSTEM>:
VariableValue Name UserName
------------- ---- --------
1234 MY_VAR <SYSTEM>
But when I try to retrieve it with any of the possible enumerations, it just returns nothing:
None of these work but printing $EnvObj shows that $Name ("MY_VAR") is there:
# .Net way
$res=[environment]::GetEnvironmentVariable($Name, "Process")
$res1=[environment]::GetEnvironmentVariable($Name, "User")
$res2=[environment]::GetEnvironmentVariable($Name, "Machine")
# PS Way
$res4=$Env:Name
... even though when I print the $EnvObj object I can see that $Name is definitely there.
What is wrong?
Your line
$EnvObj = #(Get-WMIObject -Class Win32_Environment -ComputerName $Computer -EA Stop)
Will return an array of [ManagementObject].
To examine all the properties you can pipe one of these objects to Get-Member
$EnvObj[0] | Get-Member
TypeName: System.Management.ManagementObject#root\cimv2\Win32_Environment
Name MemberType Definition
---- ---------- ----------
PSComputerName AliasProperty PSComputerName = __SERVER
Caption Property string Caption {get;set;}
Description Property string Description {get;set;}
InstallDate Property string InstallDate {get;set;}
Name Property string Name {get;set;}
Status Property string Status {get;set;}
SystemVariable Property bool SystemVariable {get;set;}
UserName Property string UserName {get;set;}
VariableValue Property string VariableValue {get;set;}
__CLASS Property string __CLASS {get;set;}
__DERIVATION Property string[] __DERIVATION {get;set;}
__DYNASTY Property string __DYNASTY {get;set;}
__GENUS Property int __GENUS {get;set;}
__NAMESPACE Property string __NAMESPACE {get;set;}
__PATH Property string __PATH {get;set;}
__PROPERTY_COUNT Property int __PROPERTY_COUNT {get;set;}
__RELPATH Property string __RELPATH {get;set;}
__SERVER Property string __SERVER {get;set;}
__SUPERCLASS Property string __SUPERCLASS {get;set;}
PSStatus PropertySet PSStatus {Status, Name, SystemVariable}
ConvertFromDateTime ScriptMethod System.Object ConvertFromDateTime();
ConvertToDateTime ScriptMethod System.Object ConvertToDateTime();
From this you can see that the value property is called VariableValue.
So,
$EnvLookup = $EnvObj | Where-Object {$_.Name -eq $Name}
$res = $EnvLookup.VariableValue

How to discover device properties and their powershell/WMI equivalent?

I have this powershell code (I didn't write it) :
$nics = Get-WmiObject Win32_NetworkAdapter -filter "AdapterTypeID = '0' `
AND PhysicalAdapter = 'true' `
AND NOT Description LIKE '%Centrino%' `
AND NOT Description LIKE '%wireless%' `
AND NOT Description LIKE '%WiFi%' `
AND NOT Description LIKE '%Bluetooth%'"
foreach ($nic in $nics)
{
$nicName = $nic.Name
...
}
Question
How did the author knew that the NIC has those properties :
Win32_NetworkAdapter
AdapterTypeID
PhysicalAdapter
Description
In other words : How can I inspect all the properties that NIC/Other_Device has ?
get-member or (gm) gets you all properties:
PS C:\Users\bjorn> Get-WmiObject Win32_NetworkAdapter | gm
TypeName: System.Management.ManagementObject#root\cimv2\Win32_NetworkAdapter
Name MemberType Definition
---- ---------- ----------
PSComputerName AliasProperty PSComputerName = __SERVER
Disable Method System.Management.ManagementBaseObject Disable()
Enable Method System.Management.ManagementBaseObject Enable()
Reset Method System.Management.ManagementBaseObject Reset()
SetPowerState Method System.Management.ManagementBaseObject SetPowerState(System.UInt16 PowerState, System.String Time)
AdapterType Property string AdapterType {get;set;}
AdapterTypeId Property uint16 AdapterTypeId {get;set;}
AutoSense Property bool AutoSense {get;set;}
Availability Property uint16 Availability {get;set;}
...
or with e.g. the ISESteroids plugin: