VSCode Running PowerShell script VS each command separately produces different results - powershell

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

Related

finding server uptime from another server using powershell

I want to find the server up time of other servers using powershell command from one server. I am using below command to query the other server but could not get the required result.
$lastboottime = (Get-WMIObject -Class Win32_OperatingSystem -ComputerName $server -Credential $altcreds -ErrorAction SilentlyContinue).LastBootUpTime
Write-Host $lastboottime
Can someone share the best way to find the other servers uptime. Is there any way in sqlserver or sqlserver stored procedure
You need to convert it to a valid Datetime object, use the ConvertToDateTime method...
$WMI = (Get-WMIObject -Class Win32_OperatingSystem -ComputerName $server -Credential $altcreds -ErrorAction SilentlyContinue)
[datetime]::Now - ($WMI.ConvertToDateTime($WMI.LastBootUpTime))
If you just need the date:
$WMI.ConvertToDateTime($WMI.LastBootUpTime)

Add-Computer command failing to work with error: RPC Server is Unavailable

Just testing out creating a new PS script for our IT team to use which will remove a computer remotely from the domain and then re-add it using the Add-Computer command.
The 3 lines of code are:
$Hostname = Read-Host "Please enter the computers hostname that you wish to remove and re-add to the domain"
Remove-Computer -ComputerName "$Hostname" -UnjoinDomainCredential "DOMAIN\$env:USERNAME" -PassThru -Verbose - Restart
Add-Computer -ComputerName "$Hostname" -LocalCredential "$Hostname\ukitadmin" -Credential "DOMAIN\$env:USERNAME" -DomainName "DOMAIN" -Force -Verbose -Restart
Just to clear the air. The env:USERNAME command is using the account I've run PS ISE as, so will be my admin account.
Any help would be massively appreciated.
Thanks
Brendan
You restart the computer with the second command, so when the third command tries to run, the computer is unavailable.
you can do this with your code, it should wait for the computer to finish restarting
I removed the -restart from the remove-computer command
$Hostname = Read-Host "Please enter the computers hostname that you wish to remove and re-add to the domain"
Remove-Computer -ComputerName $Hostname -UnjoinDomainCredential "DOMAIN\$env:USERNAME" -PassThru -Verbose
Restart-Computer -ComputerName $Hostname -Wait
Add-Computer -ComputerName $Hostname -LocalCredential "$Hostname\ukitadmin" -Credential "DOMAIN\$env:USERNAME" -DomainName "DOMAIN" -Force -Verbose -Restart

Flushdns and registerdns on multiple machine by 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

Restart-service WinRM remotely without yes/no

How can I Restart-service remotely with WinRM, without a yes/no confirmation on a remote computer in a workgroup?
You can use WMI:
$ServiceName = 'Spooler'
$WMI = Get-WmiObject win32_service -Filter "name='$ServiceName'" -ComputerName $computer
$WMI.StopService()
$WMI.StartService()

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