Getting Registry Key of all machines in the domain - powershell

sorry if it's a silly question. I'm trying to get the "EnableDCOM" Registry Key of all the machines on the domain and disable them. I'm kinda stuck with getting the status of the registry key.
Get-Adcomputer -Filter * | Get-itemProperty -path HKLM:\Software\Microsoft\OLE -name "EnableDCOM"
Here is the error:
Get-ItemProperty : Cannot process argument transformation on parameter 'Credential'. userName
At line:1 char:28
... -filter * | Get-ItemProperty -path HKLM:\Software\Microsoft\OLE -name ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidData: (CN=DAYGROUP-PCI...=daygroup,DC=ca:PSObject) [Get-ItemProperty], ParameterB
indingArgumentTransformationException
FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.PowerShell.Commands.GetItemPropertyComman
d
After trying to use the domain admin credential:
The provider does not support the use of credentials. Perform the operation again without specifying credentials.
At line:1 char:1
get-adcomputer -filter * | Get-ItemProperty -path HKLM:\Software\Micr ...
+ CategoryInfo : NotImplemented: (:) [], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported

This code can help you. Don`t forget to specify different credential if needed.
$ADComputers = ( Get-ADComputer -Filter * ).Name
$ResultArray = #()
foreach ( $Computer in $ADComputers ){
#Maybe you need specify different credential -Credential $cred
$Value = Invoke-Command -ComputerName $Computer -ScriptBlock {
$Value = Get-ItemPropertyValue -path 'HKLM:\Software\Microsoft\OLE' -name 'EnableDCOM'
return $Value
}
$PSO = [PSCustomObject]#{
Computer = $Computer
Value = $Value
}
$ResultArray += $PSO
}
$ResultArray

Related

Update definition of SCEP on windows servers using powershell

i am trying to update the definition of SCEP on remote Windows Servers using MpCmdRun.exe which exists under "C:\ProgramData\Microsoft\Windows Defender\platform\*\MpCmdRun.exe. Unfortunately it is not accepting -filepath. says its null or empty. below is my code
$comp = "SRV1234"
$MpCmdRun = invoke-Command -ComputerName $comp -ScriptBlock {get-item -Path "C:\ProgramData\Microsoft\Windows Defender\platform\\*\MpCmdRun.exe" | Sort-Object -Property LastWriteTime -Descending |Select-Object -ExpandProperty fullname -First 1}
invoke-Command -ComputerName $comp -ScriptBlock {Start-Process -FilePath $MpCmdRun -ArgumentList "-signatureUpdate" -Wait}
Below is the error:
Cannot validate argument on parameter 'FilePath'. The argument is null
or empty. Provide an argument that is not null or empty, and then try
the command again.
+ CategoryInfo : InvalidData: (:) [Start-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartProcessCommand

Issue while executing get-acl for remote servers

I am having the below code to get the data from remote servers. thanks to #Santiago Squarzon
$serverlist = Get-Content -Path "C:\ServerList.txt"
# Collect results here
$result = Invoke-Command -ComputerName $serverlist -ScriptBlock {
$paths_list = $env:Path -Split [System.IO.Path]::PathSeparator
foreach($sys_Path in $paths_list)
{
$Permissions = (Get-Acl -Path $sys_Path).Access
foreach($acl in $Permissions)
{
if(-not $acl.IdentityReference)
{
continue
}
[pscustomobject]#{
ComputerName = $env:ComputerName
SystemFolderPath = $sys_Path
IdenityReference = $acl.IdentityReference.Value
FileSystemRights = $acl.FileSystemRights
}
}
}
} -HideComputerName
$result | Export-Csv -Path "C:\status_report.csv" -NoTypeInformation
But I am getting below error while executing it
Cannot validate argument on parameter 'Path'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [Get-Acl], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetAclCommand
+ PSComputerName
Please let me know on this.
Might adding the following check before $Permissions = (Get-Acl -Path $sys_Path).Access would resolve the issue:
if (($sys_Path -eq $null) -or ($sys_Path -eq '') ) {
continue
}

Check/read registry key value on remote computer with local admin credential

How to check registry key value on computer which is not in domain??
I think that I must use local admin credential for this but I dont know how
I tried this:
$user = "admin"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$computer = "computer"
$domain=$computer
$username = $domain + "\" + $user
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$key = '\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters'
$valuename = 'DiskSpaceThreshold'
$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential
$value = $wmi.GetStringValue($HKEY_Local_Machine,$key,$valuename).svalue
$wmi
$value
But the result:
Get-Wmiobject : Could not get objects from namespace root\default. Serwer RPC jest niedostępny. (Wyjątek od HRESULT: 0x800706BA) At line:12 char:8
+ $wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Comp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : INVALID_NAMESPACE_IDENTIFIER,Microsoft.PowerShell.Commands.GetWmiObjectCommand You cannot call a method on a null-valued expression. At line:13 char:1
+ $value = $wmi.GetStringValue($HKEY_Local_Machine,$key,$valuename).sva ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH : ReturnValue : 6 uValue : PSComputerName :
So I tried something else
# file with computer name
$computers = Get-Content F:\IT\!Set_NTP_Time\ReadRegistry\servers.txt | ?{$_ -notmatch "^#"};
#Registry Hives
[long]$HIVE_HKROOT = 2147483648
[long]$HIVE_HKCU = 2147483649
[long]$HIVE_HKLM = 2147483650
[long]$HIVE_HKU = 2147483651
[long]$HIVE_HKCC = 2147483653
[long]$HIVE_HKDD = 2147483654
# registry
$HKLM = 2147483650
$main = "Localmachine"
$keyPath = "System\CurrentControlSet\Services\W32Time"
$keyName = "Start"
#$computer ='.'
$reg = [WMIClass]"ROOT\DEFAULT:StdRegProv"
$Key = "W32Time"
#$Value = "HistoryBufferSize"
#$results = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
#"Current History Buffer Size: {0}" -f $results.uValue
<#
Param($computer)
$HKEY_Local_Machine = 2147483650
$reg = [WMIClass]"\\$computer\ROOT\DEFAULT:StdRegProv"
$Key = "SOFTWARE\Wow6432Node\Symantec\Symantec Endpoint Protection\CurrentVersion\SharedDefs"
$ValueName = "DEFWATCH_10"
$results = $reg.GetStringValue($HKEY_LOCAL_MACHINE, $Key, $ValueName)
write $results.sValue
#>
# credentials
$user = "admin"
$user1 = "admin1"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
# Start processing
foreach($computer in $computers) {
$domain=$computer
$username = $domain + "\" + $user
$username1 = $domain + "\" + $user1
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$Credential1 = New-Object System.Management.Automation.PSCredential -ArgumentList $username1,$password
try {
if (($computer -eq "comp1") -or ($computer -eq "comp2") -or ($computer -eq "name_of_computer") -or ($computer -eq "other_computer")) {
#$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential1
#$value = $wmi.GetStringValue($HKLM,$keyPath,$keyName).svalue
#Write-Host -ForegroundColor DarkYellow $computer $value
#$value = Invoke-Command -Scriptblock {Get-Item $HKLM,$keyPath,$keyName} -Computername $computer -Credential $Credential1
$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Credential1 | Where-Object {$_.Name -eq "StdRegProv"}
#$HKLM = 2147483650
#$value = $reg.GetStringValue($HKLM,$keyPath,$keyName).sValue
$value = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
Write-Host -ForegroundColor DarkYellow $computer $reg $value
} else {
#$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential
#$value = $wmi.GetStringValue($HKLM,$keyPath,$keyName).svalue
#Write-Host -ForegroundColor DarkYellow $computer $value
#$value = Invoke-Command -Scriptblock {Get-Item $HKLM,$keyPath,$keyName} -Computername $computer -Credential $Credential
$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Credential | Where-Object {$_.Name -eq "StdRegProv"}
#$HKLM = 2147483650
#$value = $reg.GetStringValue($HKLM,$keyPath,$keyName).sValue
$value = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
Write-Host -ForegroundColor DarkYellow $computer $reg $value
}
<#
if($value -eq 2)
{
Write-Host -ForegroundColor DarkYellow $computer "YES"
} else {
Write-Host -ForegroundColor Red $computer "NO"
}
#>
} catch {
Write-Host -ForegroundColor Red "$computer access denied.$_";
}
}
Result for this script
comp1 \COMP1\ROOT\default:StdRegProv System.Management.ManagementBaseObject
comp2 \COMP2\ROOT\default:StdRegProv System.Management.ManagementBaseObject
comp3 \COMP3\ROOT\default:StdRegProv System.Management.ManagementBaseObject
Personally, as I am used to use powershell remoting to gather information from remote machines, I would proceed like this:
Establish remote PS session
Run script on remote machine
Profit
So in your case, something like (If you are retrieving a value named DiskSpaceThreshold inside of HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters)
$user = "admin"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$computer = "computer"
$domain=$computer
$username = $domain + "\" + $user
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$session = New-PSSession $computer -Credential $Credential
$r = Invoke-Command -Session $session -ScriptBlock { Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters -Name "DiskSpaceThreshold" }
Remove-PSSession $session
Write-Host $r.DiskSpaceThreshold
The effect of trying to run the script from P-L user post
New-PSSession : [computer] Connecting to remote server computer failed with the following error message : WinRM cannot process the
request. The following error with errorcode 0x80090311 occurred while using Kerberos authentication: There are currently no
logon servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTT
PS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see
the about_Remote_Troubleshooting Help topic.
At line:9 char:12
+ $session = New-PSSession $computer -Credential $Credential
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTran
sportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is
not null or empty, and then try the command again.
At line:10 char:30
+ $r = Invoke-Command -Session $session -ScriptBlock { Get-ItemProperty -Path HKLM ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
Remove-PSSession : Cannot validate argument on parameter 'Id'. The argument is null. Provide a valid value for the argument,
and then try running the command again.
At line:11 char:18
+ Remove-PSSession $session
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Remove-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RemovePSSessionCommand
The username and password are good.

PowerShell - Error in path while Set-FsrmQuota

I'm trying to make a script that changes the quota of a specific directory on a remote server. For that I'm using the following code ($Quota and $chosen_username enter as parameters):
$prefix_path = "C:\Shares\Users\";
$path = $prefix_path + $chosen_username;
if($Quota){
invoke-command -computername $servername {Set-FsrmQuota -path $path -Size $Quota+"GB"}
}
if((invoke-command -computername $servername {Get-FsrmQuota -path $path} | select #{n='QuotaSize'; e={$_.Size / 1gb -as [int]}}).QuotaSize -eq $Quota){
return "Success."
} else {
return "Failed."
}
And it is giving me this error:
Cannot bind argument to parameter 'Path' because it is an empty string.
+ CategoryInfo : InvalidData: (:) [Set-FsrmQuota], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Set-FsrmQuota
+ PSComputerName : ServerName
I've done debug and the value of $path is correct.
When using invoke-command on a remote computer, the local variables are unknown for the remote host, so you have to use either:
the using prefix for PS >= 3
invoke-command -computername $servername {Set-FsrmQuota -path $using:path -Size $using:Quota+"GB"}
the argumentlist parameter for PS < 3
invoke-command -computername $servername {Set-FsrmQuota -path $args[0] -Size $args[1]+"GB"} -argumentlist $path,$quota

Setting File Owner to user in a non-trusted domain via PowerShell

I am trying to set the owner of a file to a SID from another another domain.
This domain is Non-Trusted so the following won't work.
PS > (Get-Acl .).SetOwner([System.Security.Principal.NTAccount]'TESTWORLD\barry')
Exception calling "SetOwner" with "1" argument(s): "Some or all identity references could not be translated."
At line:1 char:1
+ (Get-Acl .).SetOwner([System.Security.Principal.NTAccount]'TESTWORLD\barry')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : IdentityNotMappedException
I am able to get the SID for the user from the other domain like so:
$c = Get-Credentials TESTWORLD.INVALID\AdminUser
$dc = Get-ADDomainController -Discover -DomainName TESTWORLD.INVALID -Service PrimaryDC | %{$_.HostName}
$sid = Get-ADUser -Filter {Name -eq "barry"} -Server $dc -Credential $c | %{$_.SID}
I then want to set this SID to be the owner of that file. How is that possible?
If DCOM traffic is allowed to the remote computer, try the following. You'll need to set $Path to the local path for the remote system. If you're using alternate credentials, provide a Credential value in the $OptionalCred hash table:
Try this:
$Path = "C:\Folder"
$OwnerSID = # SID string goes here #
$Computer = $env:ComputerName
$OptionalCred = #{
# Don't use this running against local machine
#Credential = Get-Credential TESTWORLD.INVALID\AdminUser
}
$EscapedPath = [regex]::Escape($Path)
$FileSecuritySetting = Get-WmiObject Win32_LogicalFileSecuritySetting -Filter "Path='$EscapedPath'" -ComputerName $Computer #OptionalCred
$Win32SD = $FileSecuritySetting | Invoke-WmiMethod -Name GetSecurityDescriptor | select -ExpandProperty Descriptor
$NewOwner = ([wmiclass]"Win32_Trustee").PSBase.CreateInstance()
$NewOwner.SIDString = $OwnerSID
$Win32SD.Owner = $NewOwner
Invoke-WmiMethod -Path $FileSecuritySetting.__PATH -Name SetSecurityDescriptor -ArgumentList $Win32SD #OptionalCred