Flushdns and registerdns on multiple machine by powershell - powershell

Simple question but not able to find answer on google at the moment. My powershell version is 2. I want to flush and registerdns on multiple machines.
ipconfig /flushDns
ipconfig /registerdns
I can't use invoke command and psremoting is not enabled on machines.
Any advise how to flushdns & registerdns.

It's pretty easy with Invoke-wmimethod
Create a list of your computers in a file named servers.txt, then create a script like this :
$listofservers = Get-Content .\servers.txt
foreach ($servers in $listofservers) {
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /flushdns") -ComputerName $servers
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /registerdns") -ComputerName $servers
}
By default you'll not get the output of the command, but you'll only get information if the command sucessfully ran on remote computer through this value :
ReturnValue
If this value equal to 0 that means the command was sucessfully executed on the remote server.
If you want to get the command output, you can achieve it but adding output redirection to txt file :
$listofservers = Get-Content .\servers.txt
foreach ($servers in $listofservers) {
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /flushdns > c:\flushdnsresult.txt") -ComputerName $servers
Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /registerdns > c:\registerdnsresult.txt") -ComputerName $servers
}
Then you'll find a txt file on your remote server containing the result output of cmd command.

If you upgrade your powershell version from 2 (highly recommended - I have a powershell & dotnet update script to do this also) you can use:
# Get Windows servers on Domain
####################
$serversraw=Get-ADComputer -Filter {(OperatingSystem -like "*windows*")}
# Filter responsive
####################
$serversup = $serversraw.name | where {Test-Connection $_ -quiet -count 1}
# Flush DNS & reregister
####################
Clear-DnsClientCache -cimsession $serversup
Register-DnsClientCache -cimsession $serversup

Related

VSCode Running PowerShell script VS each command separately produces different results

Starting to manage servers with PowerShell scripts...
I installed VSCODE + PowerShell extension in my laptop.
I set my WSMAN Trusted list to *
And ran the following script (below, for example with F5 key) that suppose to stop a service in the remote machine:
$computers = "IP ADDRESS"
[string] $domainAdminUserName = "USERNAME"
[string] $domainAdminPlainPassword = "PASSWORD"
$securePassword = $domainAdminPlainPassword | ConvertTo-SecureString -AsPlainText -Force
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $domainAdminUserName, $securePasswordEnter-PSSession -Computer $computers -Credential $credentials
$svcSQL = Get-WmiObject -Class Win32_Service -Computer $computers -Credential $credentials -Filter "Name='MSSQLSERVER'"
$svcSQLAgent = Get-WmiObject -Class Win32_Service -Computer $computers -Credential $credentials -Filter "Name='SQLSERVERAGENT'"
$svcOLAP = Get-WmiObject -Class Win32_Service -Computer $computers -Credential $credentials -Filter "Name='MSSQLServerOLAPService'"
Invoke-Command -Computer $computers -Credential $credentials -ScriptBlock {Get-WmiObject -Class Win32_Service | Where-Object {$_.name -eq $svcSQL} | Stop-Service -Force}
Invoke-Command -Computer $computers -Credential $credentials -ScriptBlock {Get-WmiObject -Class Win32_Service | Where-Object {$_.name -eq $svcOLAP} | Stop-Service}
Exit-PSSession
The services weren't stop
Then, I went to the PowerShell Integrated Console and execute the following commands:
PS> Enter-PSSession -Computer "IP ADDRESS" -Credential "DOMAIN ADMIN USER"
PS> PASSWORD: ******
PS [IP ADDRESS]> Get-Service -Name "MSSQLSERVER"
PS [IP ADDRESS]> PowerShell found the service
PS [IP ADDRESS]> Stop-Service -Name "MSSQLSERVER"
The service was stopped successfully
How can I fix the problem in order to run the script and get the expected result?
Note:
PC: My pc (WIN 10 is in one domain (Home)
VM: My remote lab machine (WIN 2016 is in another domain (Work)
PC: To get remote access to my lab I need to use VPN app
PC: My WSMan Trusted List = *
VM: WinRM is running in my remote lab (GPO: Windows Remote Management (WS-Management (Startup Mode = Automatic)
VM: port 5985 is open, 5986 not
PC & VM: Set-ExecutionPolicy Unrestricted in client and server wasn't help
I'm just learning but had a similar issue that was resolved when I added this:
PS> Set-ExecutionPolicy Unrestricted
Visual studio code terminal, how to run a command with administrator rights?
Finally problem solved: l add the domain name as a suffix in the DNS suffixes list in the Network adapter > IPv4 properties

How to Stop-Process by command line parameters?

I'm trying to automate some stuff and I need to be able to Stop-Process an application started via dotnet path\to\myProgram.dll.
I've tried Stop-Process -Name myProgram -PassThru but it says it can't find any process like that.
Just doing Stop-Process -Name dotnet -PassThru seems a bit spray'n'pray as there are several DotNet programs running and I want to stop a specific one.
How do I find the correct process to give to Stop-Process?
You can get the process running with specific commandline and stop it.
an Example below:
$Process = Get-CimInstance -ClassName Win32_PRocess -Filter "CommandLine='C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'"
or
$Process = Get-CimInstance -ClassName Win32_PRocess -Filter "CommandLine LIKE '%powershell.exe'"
then
$Process | Invoke-WmiMethod -Name Terminate
Identify the command line used by the specific dotnet process and filter it with that cmdline.

Powershell using Invoke-Command and Get-Childitem not delivering content

I am using Powershell 4.0 on a remote computer (rem_comp) to access another one (loc_comp; Powershell 2.0 installed here) in order to get the number of files listed without folders:
$var1 = 'H:\scripts'
Invoke-Command -Computername loc_comp -scriptblock {(Get-Childitem $var1 -recurse | Where-Object {!$_.PSIsContainer}).count}
However when using $var1 inside -scriptblock, it does not deliver anything (neither any error message).
When using
$var1 = 'H:\scripts'
Invoke-Command -Computername loc_comp -scriptblock {(Get-Childitem $ -recurse | Where-Object {!$_.PSIsContainer}).count}
it works!
Note: Changing var1 from ' to " does not help.
Running the command without Invoke-Command locally faces the same problem.
How to fix this?
To complement CmdrTchort's helpful answer:
PS v3 introduced the special using: scope, which allows direct use of local variables in script blocks sent to remote machines (e.g., $using:var1).
This should work for you, because the machine you're running Invoke-Command on has v4.
$var1 = 'H:\scripts'
Invoke-Command -Computername loc_comp -scriptblock `
{ (Get-Childitem $using:var1 -recurse | Where-Object {!$_.PSIsContainer}).count }
Note that using: only works when Invoke-Command actually targets a remote machine.
When you're using Invoke-command and a script-block , the scriptblock cannot access your params from the outer scope (scoping rules).
You can however, define the params and pass them along with the -Argumentlist
Example:
Invoke-Command -ComputerName "localhost" {param($Param1=$False, $Param2=$False) Write-host "$param1 $param2" } -ArgumentList $False,$True
The following should work for your example:
Invoke-Command -Computername loc_comp -scriptblock {param($var1)(Get-Childitem $var1 -recurse | Where-Object {!$_.PSIsContainer}).count} -ArgumentList $var1

Get IIS Bindings from many webservers using powershell remoting, invoke command and module webadministration

Right now I made a small script to see my actual webbindings on a server.
Import-Module WebAdministration;
$today = Get-Date -format M.d.yyyy
$machine = hostname
function IISRport
{
Get-ChildItem -path IIS:\Sites | out-file "\\server01\d$\_utils\PowerShell Scripts\IISexport\IISExport$machine$today.txt"
}
IISReport
This wil outfile my IIS bindings to txt which works brilliant.
I now need to invoke that command to several other servers and save the output file on one server. since the machine name will be diffrent I expect as many outputs as servers.
I tried for example the following :
icm -comp server02 {get-childitem -path IIS:\Sites}
But than the imported Module webadministration is not working, since I only loaded on one server. So I tried to load that remotely using :
icm -comp server02 {import-module webadministration}
without success.
How to achieve that?
This will get the data from all machines defined in $machines and output to \\server01\d$_utils\PowerShell Scripts\IISexport\.
$today = Get-Date -format M.d.yyyy
$machines = #("server01","server02")
foreach($machine in $machines) {
icm -comp $machine { param($machine,$today)
import-module webadministration;
Get-ChildItem -path IIS:\Sites |
out-file "\\server01\d$\_utils\PowerShell Scripts\IISexport\IISExport$machine$today.txt"
} -ArgumentList $machine,$today
}
You can of course change the output path( and import list of machines from a file,AD or some other source).

Restarting an app pool using powershell Exception

I am trying to restart an application pool remotely using powershell.
net use $ToPath $pass /USER:$usr
$appPool = get-wmiobject -computername $ToServerName -namespace "root\MicrosoftIISv2" -class "IIsApplicationPool" | Where-Object {$_.Name -eq "W3SVC/APPPOOLS/$appPoolName"} -Authentication PacketPrivacy
#(Get-WmiObject -Query "SELECT * FROM IIsApplicationPool WHERE Name = 'W3SVC/AppPools/$appPoolName'" -Namespace 'root\MicrosoftIISv2').Recycle()
$appPool.Recycle()
net use $ToPath /delete
I basically use the same command that I use to move files remotely, where I set up a net user. I get a Get-WMI exception
I wanted to make sure that this question was answered for those that come after me. It turns out that I was piping the -Authentication PacketPrivacy parameter to the wrong command