Get-DnsServerResourceRecord not working on 2016 server - powershell

I have a powershell that utilizes the function Get-DnsServerResourceRecord. I have it working on a couple of different servers for testing, but on the server that I want it to run from I get this error:
Get-DnsServerResourceRecord : The term 'Get-DnsServerResourceRecord'
is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again. At line:2
char:3
+ Get-DnsServerResourceRecord -ComputerName $DNSServer -ZoneNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-DnsServerResourceRecord:String) [], CommandNotF oundException
+ FullyQualifiedErrorId : CommandNotFoundException
All of my googling has told me that since I am running this on a Windows Server 2016 (DataCenter) that this should just work. What am I missing in order for this to run?
How I am actually running it:
$DNSServer = "dnsservername"
$dnsrecord = Get-DnsServerResourceRecord -ComputerName $DNSServer -ZoneName 'db.local' -RRType CName | Where-Object {$_.RecordData.HostNameAlias -like "*" -and $_.HostName -like "*.*"}
$Datatable = New-Object System.Data.DataTable
[void]$Datatable.Columns.Add("CName")
[void]$Datatable.Columns.Add("HostNameAlias")
Foreach ($record in $dnsrecord)
{
[void]$Datatable.Rows.Add($record.HostName, $record.RecordData.HostNameAlias)
}

You need to install DNS server Tools module.
run below powershell command
Install-WindowsFeature rsat-dns-server

(As of 2022)
List Installed Windows Features on Win10 (Powershell)
Get-WindowsOptionalFeature -Online | Where Name -Match "RSAT.*" | Format-Table -Autosize
Install RSAT.DNS.TOOLS
Add-WindowsCapability -Online -Name Rsat.Dns.Tools

Related

Attempting to query all Windows servers to find those that have media loaded in the CD-ROM drive

I'm trying to build a command to query all Windows servers in AD and report if they have media loaded in the CD-ROM drive. I pieced together a command that I thought was correct and now I'm stuck at it reporting and RPC error. Note: The CD-ROM drive does not have the same assigned drive letter on every server.
Command:
$Computers = Get-ADComputer -filter 'operatingsystem -like "server" -and enabled -eq "true"'
foreach($Computer in $Computers){GET-WmiObject –query 'SELECT * from win32_logicaldisk where DriveType = "5"' –computername $Computer | Select Displayname,DeviceID,Size,VolumeName}
I receive the following error when executing it.
GET-WmiObject : The RPC server is unavailable.
At line:2 char:34
... $Computers){GET-WmiObject –query 'SELECT * from win32_logicaldisk whe ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
I've never used the Get-WmiObject command before and I'm in unfamiliar territory. Any assistance would be greatly appreciated.
Thank you
Get-AdComputer doesn't return computer names you can use directly with -ComputerName, try:
–computername $Computer.Name

Powershell Profile Removal - Windows 7

I am running the below script on Windows 10 without problems. So i am attempting to run it on Windows 7. However I get this weird error. The piece before the pipe to Remove-CimInstance works fine. Just something wrong when it hits the pipe
Get-CimInstance -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $pullUser } | Remove-CimInstance
However, i am getting the error below
Remove-CimInstance : The parameter is incorrect.
At line:1 char:104
+ ... LocalPath.split('\')[-1] -eq "useridhere" } | Remove-CimInstance
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Win32_UserProfi...6-100815088...):CimInstance) [Remove-CimInstance], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070057,Microsoft.Management.Infrastructure.CimCmdlets.RemoveCimInstanceCommand
EDIT
So as it turns out, there was an issue with a WMI on the device i was testing on. I originally created this script for Win10 and have been moving backwards to make it work on Windows 7. The premise of the entire script is to create a TASK JOB to delete a user profile on Startup.
For whatever reason, the script in its entirety works fine when running from a Powershell ISE Window with Admin rights, the TASK JOB is set to run as system, however it is failing the most basic of commands (almost as if the cmdlets are not loaded). I will be posting a new question on this if I cannot figure out what the problem is.
Tyr this to see all details of this action.
# Get the stack information and the full error message if any
Trace-Command -Name metadata,parameterbinding,cmdlet -Expression {
Get-CimInstance -Class Win32_UserProfile |
Where-Object {
$_.LocalPath.split('\')[-1] -eq 'TestUser'} |
Remove-CimInstance -Verbose -WhatIf
} -PSHost
$Error[0] |
Select-Object -'*' |
Format-List -Force

Revoke-AzureADUserAllRefreshToken CommandNotRecognized

I'm trying to run the following script to disable AD and O365 accounts that are disabled.
import-module activedirectory
$Corporate = Get-ADUser -Server "myActiveDirectoryDomain" -Filter * -Property Enabled | Where-Object {$_.Enabled -like “false”}
$Corporate | ForEach-Object -Process { Revoke-AzureADUserAllRefreshToken -ObjectId $_.ObjectGUID }
However, when I run my script, I get this errror...
Revoke-AzureADUserAllRefreshToken : The term 'Revoke-AzureADUserAllRefreshToken' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that
the path is correct and try again.
At C:\Users\lpurhr1\Documents\_RHR\PowerShellScripts\RemoveAccessTokenForDisabledAccounts.ps1:37 char:40
+ ... | ForEach-Object -Process { Revoke-AzureADUserAllRefreshToken -Object ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Revoke-AzureADUserAllRefreshToken:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I have no idea why I'm getting this error, and nothing online is really telling me why this should be happening. I can run the Get-ADUser cmdlet just fine, but the Revoke-AzureADUserAllRefreshToken doesn't seem to be recognized. I'm sure there's something I'm not installing. Does anyone know what I'm missing?
The command Revoke-AzureADUserAllRefreshToken belongs to the AzureAD powershell module, you need to install it first.
Install-Module AzureAD
Reference - https://learn.microsoft.com/en-us/powershell/azure/active-directory/install-adv2?view=azureadps-2.0

How can I search for software by filepath and then install it if it's missing using PowerShell

I'm trying to write a PowerShell script that will allow me to search for an old antivirus program on each computer in my domain, and if it has that program, run the Competitor Removal Tool that was given to us by our new AntiVirus software vendor. I also want the script to search for our new AV software, and if it's missing, install it. Both the Competitor Removal Tool and the .exe for the installer are stored on a Domain Controller and accessed via network share. I'm enabling PowerShell remoting in my organization, and I'm hoping that will give me more flexibility. Here's what I have so far:
#Retrieves list of all computers tied to Active Directory
$computers = Get-Content -Path 'C:\Sophos Results\ADComputers.txt'
#Paths to Sophos Installation and the Sophos Competitor Removal Tool
$SophosInstallPath = Get-ChildItem -File \\DC-02\netlogon\SophosInstall\Sophos-Installation.bat
$KasperskyRemove = Get-ChildItem -File \\DC-02\netlogon\SophosInstall\AVRemoveW.exe
#Loops through each AD Computer and tests for proper software installation
ForEach ($computer in $computers)
{
#Variables that store the path to 32-bit and 64-bit versions of Sophos
$Sophos64 = Test-Path "\\$computer\c$\Program Files\Sophos"
$Sophos32 = Test-Path "\\$computer\c$\Program Files (x86)\Sophos"
#Variables that store the path to 32-bit and 64-bit versions of Kaspersky
$Kaspersky64 = Test-Path "\\$computer\c$\Program Files\Kaspersky Lab"
$Kaspersky32 = Test-Path "\\$computer\c$\Program Files (x86)\Kaspersky Lab"
#The following block will run the Sophos Installation batch file, removing any instance of Kaspersky and installing Sophos
If ($Sophos64 -eq $false -or $Sophos32 -eq $false)
{
Start-Process -FilePath $SophosInstallPath -Verbose
Write-Host "Beginning Sophos Installation on $computer"
}
#The following block will remove Kaspersky from a machine if it is present and Sophos is already installed.
Elseif (($Kaspersky64 -eq $true -or $Kaspersky32 -eq $true) -and ($Sophos64 -eq $true -or $Sophos32 -eq $true))
{
Start-Process -FilePath $KasperskyRemove -Verbose
Write-Host "Removing Kaspersky from $computer"
}
#The last block will only be executed if Sophos is installed and Kaspersky isn't, and makes no changes to the machine.
else {Write-Host "$computer has the proper AV software installation"}
}
At the moment, when I run this against a group of test computers, I don't get any errors, and I know that the script is correctly determining whether or not Kaspersky/Sophos is installed, but it won't launch the Competitor Removal Tool or the install file. I know once PowerShell remoting is enabled there will be a better way to do this, I'm just not sure what that way is. Any suggestions? Thanks in advance
Update:
I enabled PS Remoting on my local machine and tried the following:
Invoke-Command -ComputerName localhost -ScriptBlock { *Script from above* }
I got the following errors:
Access is denied
+ CategoryInfo : PermissionDenied: (\\dc-02\net...nstallation.bat:String) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : localhost Cannot find path '\\dc-02\netlogon\SophosInstall\Sophos-Installation.bat' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\dc-02\net...nstallation.bat:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : localhost Access is denied
+ CategoryInfo : PermissionDenied: (\\dc-02\net...l\AVRemoveW.exe:String) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : localhost Cannot find path '\\dc-02\netlogon\SophosInstall\AVRemoveW.exe' because it does not exist.
+ CategoryInfo : ObjectNotFound: (\\dc-02\net...l\AVRemoveW.exe:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
+ PSComputerName : localhost 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
+ PSComputerName : localhost
I'm running PowerShell from my domain admin account so I'm not sure why it would say access denied. Thanks for your help, I'm a bit new to both IT and PowerShell. Two months in on my first job
My last question: When I'm ready to do this on a larger scale, say my test group which has 3 computers (1 with Kaspersky, 1 With Sophos, and 1 with neither) The following should work, yes?:
$computers = Get-Content -Path 'C:\Sophos Results\TestGroup.txt'
Invoke-Command -ComputerName $computers -ScriptBlock { *Original Script here* }
Any preference between Invoke-Command and Enter-PSSession when dealing with multiple computers? In the description of Invoke-Command it says "To run a single command on a remote computer, use the ComputerName parameter. To run a series of related commands that share data, use the New-PSSession cmdlet" So if I do use Invoke-Command (which seems more straightforward to me) Should I save my script and then call it in the scriptblock? And then that leads me to wonder how I would call a script from my local machine on the remote machine? I apologize for so many questions, my head is just spinning the further I get down the rabbit hole here.
Update 7/19/2018:
Running into one more issue, hoping this is the last one. I copied the files from the remote server on to my local machine to get rid of the second hop problem. I will just copy the files from my local machine to all remote machines in the script. Problem is when I copy from local to remote, it only works when I specify the computer name like so :
Copy-Item -Path C:\Temp\AVInstall -Destination '\\Computer1\c$\Temp\AVInstall' -Recurse
If I try and use a computer variable, like below, I get a network path not found error:
Copy-Item -Path C:\Temp\AVInstall -Destination '\\$computer\c$\Temp\AVInstall' -Recurse
Any reason why that might be?
As EBGreen touched on, you are currently running this on the local machine.
You would need to run it on the remote machine either via an interactive PSSession or via invoking the script.
To use Invoke-Command you can place the script to be executed on the remote machine into a scriptblock. This is then invoked on each machine within the string array within the -computername argument.
I can't test this, however I think you may encounter a double-hop problem when trying to retrieve the items $SophosInstallPathand$KasperskyRemove. If this does happen it will most likely manifest along the lines of "access denied". If this occurs the easiest solution would most likely be to copy the items to the machine first, either via copy-item or the more robust robocopy.exe and then remove them once complete.
#Retrieves list of all computers tied to Active Directory
$computers = Get-Content -Path 'C:\Sophos Results\ADComputers.txt'
$scriptblock = {
#Paths to Sophos Installation and the Sophos Competitor Removal Tool
$SophosInstallPath = Get-Item -File "\\DC-02\netlogon\SophosInstall\Sophos-Installation.bat"
$KasperskyRemove = Get-Item -File "\\DC-02\netlogon\SophosInstall\AVRemoveW.exe"
#Variables that store the path to 32-bit and 64-bit versions of Sophos
$Sophos64 = Test-Path "\Program Files\Sophos"
$Sophos32 = Test-Path "\Program Files (x86)\Sophos"
#Variables that store the path to 32-bit and 64-bit versions of Kaspersky
$Kaspersky64 = Test-Path "\Program Files\Kaspersky Lab"
$Kaspersky32 = Test-Path "\Program Files (x86)\Kaspersky Lab"
#The following block will run the Sophos Installation batch file, removing any instance of Kaspersky and installing Sophos
If ($Sophos64 -eq $false -or $Sophos32 -eq $false)
{
Start-Process -FilePath $SophosInstallPath -Verbose
Write-Host "Beginning Sophos Installation on $computer"
}
#The following block will remove Kaspersky from a machine if it is present and Sophos is already installed.
Elseif (($Kaspersky64 -eq $true -or $Kaspersky32 -eq $true) -and ($Sophos64 -eq $true -or $Sophos32 -eq $true))
{
Start-Process -FilePath $KasperskyRemove -Verbose
Write-Host "Removing Kaspersky from $env:computer"
}
#The last block will only be executed if Sophos is installed and Kaspersky isn't, and makes no changes to the machine.
else
{
Write-Host "$env:computer has the proper AV software installation"
}
}
Invoke-Command -ComputerName $computers -ScriptBlock $scriptblock

PowerShell: Get-Service w/ Get-Content, -name and select

I am trying to get the status of a specific service on 2008 R2 servers listed in a text file.
I once was able to successfully run the following:
$servers = Get-Content "C:\scripts\Computers.txt"
Get-Service -ComputerName $servers -Name MrT |
Select Name, MachineName, Status
As shown here:
Now when I run the same script I get the following error:
Get-Service : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again.
At line:3 char:27
+ Get-Service -ComputerName $servers -Name MrT |
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetServiceCommand
Technically to get past this, I could run the following but would rather run against a list of servers.
Get-Service -ComputerName 3b, 4b, 7b -Name MrT | Select Name, MachineName, Status
What am I doing wrong and how did it work once and not work again?
As the error message points it out, the $servers variable probably doesn't contain any items. Check the output by running:
Get-Content "C:\scripts\Computers.txt"