Problem summary:
I'm attempting to check for WMF4 on all servers in a particular OU in our domain. However, I'm getting RPC errors for most servers, despite having GPOs in place to enable WinRM to work. I am running the below code from the Domain Controller.
Things I've checked or tried:
Telnet from DC to target server on port 135 and 5985. Works fine, so
firewall(s) should not be an issue.
Checked that the following services are running on the target server:
WinRM
Remote Registry
Remote Procedure Call
Set WinRM trusted hosts on target server to "*" (just as a test)
One item of interest - There is one server where I don't get an RPC error and it's the only one in the OU that's in the same /24 subnet as the DC. Seems like a curious coincidence.
What have I missed?
Thanks.
Here is my Powershell code:
Import-Module ActiveDirectory
$searchOU = "<removed>"
$2008servers=(Get-ADComputer -Filter {OperatingSystemVersion -like "6.0*" -or OperatingSystemVersion -like "6.1*"} -SearchBase $searchOU)
$2012servers=(Get-ADComputer -Filter {OperatingSystemVersion -like "6.2*"} -SearchBase $searchOU)
ForEach ($2008server in $2008servers) {
$server = $2008server.Name
try {
if (Get-HotFix -id KB2819745 -ComputerName $server -ErrorAction Stop) {
Add-Content "WMF4 is present on $server" -Path "C:\Users\`$peterb\Desktop\WMF4-Present.log"
}
}
catch {
if ($Error[0].Exception.Message.Contains("The RPC server is unavailable")) {
$ErrorMessage = $_.Exception.Message
Add-Content "$ErrorMessage on $server" -Path "C:\Users\`$peterb\Desktop\RPCUnavailable.log"
} else {
if ($Error[0].Exception.Message.Contains("Cannot find the requested hotfix")) {
Add-Content "WMF4 is missing on $server" -Path "C:\Users\`$peterb\Desktop\Missing-WMF4.log"
} else {
Add-Content "$ErrorMessage on $server" -Path "C:\Users\`$peterb\Desktop\OtherErrors.log"
}
}
}
}
ForEach ($2012server in $2012servers) {
$server = $2012server.Name
try {
if (Get-HotFix -id KB2799888 -ComputerName $server -ErrorAction Stop) {
Add-Content "WMF4 is present on $server" -Path "C:\Users\`$peterb\Desktop\WMF4-Present.log"
}
}
catch{
if ($Error[0].Exception.Message.Contains("The RPC server is unavailable")) {
$ErrorMessage = $_.Exception.Message
Add-Content "$ErrorMessage on $server" -Path "C:\Users\`$peterb\Desktop\RPCUnavailable.log"
} else {
Add-Content "WMF4 is missing on $server" -Path "C:\Users\`$peterb\Desktop\Missing-WMF4.log"
}
}
}
I usually get RPC errors in PS when WMI is either blocked by the firewall or when the service is not running.
If I'm not mistaking get-hotfix uses WMI instead of WinRM to remote to a machine.
Starting the WMI service and creating the firewall rules to allow WMI should solve the RPC errors.
Related
New to Powershell, My goal is to go through a list of remote Computers and check to see if certain services are running on them and starting the services if they are not. what would be the best approach in creating a variable for the services on said servers?
Server1.txt - 'ServiceA ServiceB ServiceC'
Server2.txt - 'ServiceD ServiceE ServiceF'
Server3.txt - 'ServiceG ServiceH'
$services = get-content .\Server1.txt
$services | ForEach {
try {
Write-Host "Attempting to start '$($.DisplayName)'"
Start-Service -Name $.Name -ErrorAction STOP
Write-Host "SUCCESS: '$($.DisplayName)' has been started"
} catch {
Write-output "FAILED to start $($.DisplayName)"
}
}
Thank you.
In your input, you have mentioned one text file for each server which is not advisable. Also there is no computer name in your Start-service Command. Please find my input sample below.
server1-serviceA,ServiceB,ServiceC
server2-serviceD,ServiceE,ServiceF
server3-serviceG,ServiceH,ServiceI
And here is the powershell script, since you have mentioned different services for each server there is a need for using split function.
$textFile = Get-Content C:\temp\servers.txt
foreach ($line in $textFile) {
$computerName = $line.split("-")[0] #Getting computername by using Split
$serviceNames = $line.split("-")[1] #Getting Service names by using split
foreach ($serviceName in $serviceNames.split(",")) {
# Again using split to handle multiple service names
try {
Write-Host " Trying to start $serviceName in $computerName"
Get-Service -ComputerName $computerName -Name $serviceName | Start-Service -ErrorAction Stop
Write-Host "SUCCESS: $serviceName has been started"
}
catch {
Write-Host "Failed to start $serviceName in $computerName"
}
}
}
I haven't tested the script for starting the service, but the loop works properly for multiple servers and their respective services. Thanks!
took up coding a small card game in PowerShell to familiarize myself with the software for work and it grew with more things I wanted to add. I thought about doing Multiplayer and stumbled across SSH. have been fiddling around with it for a while and it got me doubting myself a bit that it is even possible to do a multiplayer "game" in PowerShell. I have tried looking for anything related to multiplayer games in PowerShell and found little to none.
so here is my question.
Im setting up an ability to either Host/Join a game in the multiplayer section. selecting host checks if you have OpenSSH installed. installs it if you don't. sets a firewall exception. then pulls your user and IP together and gives that to the host to give to others to join off.
then with that ip the joiners enter it and get connected to the host and their files get shared.
problems I am facing:
Can only connect in LAN though this method. if port forwarding is required to be done in the router and it cant be scripted in PowerShell then that cant be done because the user cant be expected to do it.
When connected through SSH the script stops. this is due to the SSH opening a new command prompt that needs to be put back into PowerShell. how do I overcome this?
When transferring files Data between the computers starts. I need to make a check every interval for updates in the data to see if the other players have done anything. like finished their turn and its now mine. how would I make a check like that?
I'm very new to PowerShell and I understand that its intended purpose is not to make games. this is all for the sake of me learning its abilities in a fun way. if it cant be done it cant be done. and I know I'm asking allot right now. I just need some pointers cause I have no-one else to talk to about this cause no-one understands PowerShell where I work. Thank you all in advance
Here is the code I have so far regarding the SSH. keep in mind I'm not the best at all in this
new-Item -Path 'C:\Program Files' -Name "CardZdata" -ItemType directory
$path = 'C:\Program Files\CardZdata'
$hostippath = ($path + '\' + 'hostip' + '.xml')
#Main Menu
clear
Write-Output 'Gamemode Selection'
Write-Output '-------------------'
Write-Output 'Singleplayer [s]'
Write-Output 'Multiplayer SSH [m]'
Write-output 'Multiplayer LAN [l]'
$gamemode = read-host
if ($gamemode -eq 's')
{
clear
Write-Output 'Gamemode Selection'
Write-Output '-------------------'
Write-Output 'Blackjack [b]'
Write-Output 'Poker [p]'
}
elseif ($gamemode -eq 'm')
{
clear
$test = Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'
if ($test.State -eq "NotPresent")
{
Write-Output 'SSH (Client) is not installed on your PC. it is needed to connect to the server.'
Write-Output 'do you wish to install it? [y/n]'
$SSHchoice = Read-Host
if ($SSHchoice = 'y')
{
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
}
else
{
Write-Output 'Sorry, you cant play Multiplayer without SSH.'
break
}
$test = Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'
if ($test.State -eq "NotPresent")
{
Write-Output "Error - Installation Failed"
break
}
}
clear
Write-Output 'Multiplayer SSH connects you to games hosted by others. or you can host them yourself.'
Write-Output 'Uninstall SHH client [u] !Warning!- You wont be able to connect to Multiplayer servers'
Write-Output ''
Write-Output 'Gamemode Selection'
Write-Output '-------------------'
Write-Output 'Host [h]'
Write-Output 'Join [j]'
$hj = Read-Host
if ($hj -eq 'h')
{
$test = Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Server*'
if ($test.State -eq "NotPresent")
{
Write-Output 'SSH (Server) is not installed on your PC. it is needed to connect to the server.'
Write-Output 'do you wish to install it? [y/n]'
$SSHchoice = Read-Host
if ($SSHchoice = 'y')
{
# Install the OpenSSH Client
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
}
$test = Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Server*'
if ($test.State -eq "NotPresent")
{
Write-Output "Error - Installation Failed"
break
}
else
{
Write-Output 'Sorry, you cant Host Multiplayer without the SSH Server.'
break
}
}
#StartMultiplayer
Write-Output '!Starting Multiplayer Server On Local Host!'
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
$test = Get-NetFirewallRule -Name sshd
if ($test.Name -ne "sshd")
{
Write-Output 'Setting Port'
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
}
Restart-Service sshd
Write-Output 'Server Set Up Successfully!'
$userip = (Get-NetIPAddress -AddressFamily IPv4 -SuffixOrigin Dhcp).IPAddress
Write-Output 'Give this to users:'
$hostip = ($env:UserName + "#" + $userip)
$hostip
$hostip | export-clixml $hostippath -force
Read-Host
}
if ($hj -eq 'j')
{
Write-Output 'Join Server'
Write-Output '-------------------'
Write-Output 'Server list [s] - WorkInProgress'
Write-Output 'Direct Connect [d]'
$sd = Read-Host
if ($sd -eq 's')
{
Write-Output 'why?'
Read-Host
}
if ($sd -eq 'd')
{
Write-Output 'Enter a code that is given by the Host'
Write-Output 'Example: [username#ipaddress]'
$hostip = read-host
$hostip | export-clixml $hostippath -force
}
}
Read-Host
}
elseif ($gamemode -eq 'l')
{
clear
Write-Output 'Gamemode Selection'
Write-Output '-------------------'
}
Here is the main area:
#StartMultiplayer
Write-Output '!Starting Multiplayer Server On Local Host!'
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
$test = Get-NetFirewallRule -Name sshd
if ($test.Name -ne "sshd")
{
Write-Output 'Setting Port'
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
}
Restart-Service sshd
Write-Output 'Server Set Up Successfully!'
$userip = (Get-NetIPAddress -AddressFamily IPv4 -SuffixOrigin Dhcp).IPAddress
Write-Output 'Give this to users:'
$hostip = ($env:UserName + "#" + $userip)
$hostip
$hostip | export-clixml $hostippath -force
Read-Host
I am working on developing PowerShell script to automate a task on a remote server by using Invoke-Command with WinRM.
The script will take the server IP, test WinRM and "Get-Credential" cmdlet to establish session and use Invoke-Command to run another script on remote server. I have made significant progress of what I want to achieve, however, I am having trouble on how to setup the code so that when I press the "Cancel" or "X" button on Get-Credential prompt it should abort the script and return to the regular PowerShell command line prompt.
Below is what I have so far, I have erased the comments and description of the code to keep the number of words less in here.
function SS
{
Add-Type -AssemblyName System.Windows.Forms
$BInput = [System.Windows.Forms.MessageBox]::Show('Do you want to proceed?', 'Confirmation',[System.Windows.Forms.MessageBoxButtons]::YesNo)
switch ($BInput)
{
"Yes" {
while ($true)
{
$server=Read-Host "Enter Server IP Address"
set-item -Path WSMan:\localhost\Client\TrustedHosts -Value "$server" -Force
if(Test-WSMan -ComputerName $server -ErrorAction SilentlyContinue)
{
Write-Host "$server is accessible, enter credentials to connect"
while ($true)
{
$creden=Get-Credential -Message "Please enter the server credentials that you want to connect"
$serversession = New-Pssession -ComputerName $server -Credential $creden -ErrorAction SilentlyContinue
if(-not($serversession))
{
write-warning "Credentials are not valild, please try again"
}
else
{
write-host "$server is connected, starting the workflow ......"
Invoke-Command -Session $serversession -FilePath "C:\Temp\XXX.ps1"
}
}
Break
}
else
{
write-host "Windows Remote Management (WinRM) protocol is not running, please check service and confirm."
}
}
Get-Pssession | Remove-PSSession
}
"No" {
Break
}
}
}
I understand I have to apply the changes / logic after this line
$creden=Get-Credential -Message "Please enter the server credentials that you want to connect"
But can't seem to find it yet. I looked online and have taken different approaches but no success so far. I would like to have opinions or recommendations on how to tackle this, appreciate your help.
Thanks
What i'm seeing is that you may be thinking too much into it. A simple if statement should do the trick, try:
$creden=Get-Credential -Message "Please enter the server credentials that you want to connect"
if(!$creden){break}
Continuing from my comment.
Try this refactor of your use case.
Point of note: Note fully tested since I do not have an environment at this time to test.
Function Start-WorkFlow
{
<#
.Synopsis
Execute a workflow
.DESCRIPTION
Sets up a WinRM session to a remote host to execute the defined workflow
.EXAMPLE
Start-WorkFlow
.EXAMPLE
swf
.INPUTS
Remote host IPAddress
Remove host credentials
.OUTPUTS
Resutls of teh workflow
.NOTES
V 0.0.1 - Prototype script. Clean-Up before production use
.COMPONENT
Stand-alone script
.ROLE
Administrative actions
.FUNCTIONALITY
Implemetned error logic for each code block
Restrict the user input to only be a proper IPAddress
Validate TCPIP state
Validate WSman state
Establish a new session
Process workflow
Exit session
#>
[cmdletbinding(SupportsShouldProcess)]
[Alias('swf')]
Param
(
)
If ((Read-Host -Prompt 'Do you want to proceed: [Yes/No]') -eq 'No' )
{Break}
Else
{
Do {$RemoteServerIPAddress = (Read-Host -Prompt 'Enter Server IP Address')}
Until ($RemoteServerIPAddress -match "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
Get-ChildItem -Path 'WSMan:\localhost\Client\TrustedHosts'
Try
{
(Test-Connection -ComputerName $RemoteServerIPAddress -Count 1 -ErrorAction Stop).IPV4Address
# Set-Item -Path 'WSMan:\localhost\Client\TrustedHosts' -Value $RemoteServerIPAddress -Force
Get-ChildItem -Path 'WSMan:\localhost\Client\TrustedHosts'
Try
{
Test-WSMan -ComputerName $RemoteServerIPAddress -ErrorAction Stop
"$RemoteServerIPAddress is accessible, enter credentials to connect"
Do
{
$Creds = $null
$CredMesssage = 'Please enter the remote server credentials that you want to connect.'
$CredMesssage = "$CredMesssage If credentials are not valid, you will be prompted to re-enter them."
$Creds = Get-Credential -Message $CredMesssage
if(-Not $creds)
{
Write-Warning -Message 'Credential request cancelled.'
Start-Sleep -Seconds 3
Exit
}
$NewPSSessionSplat = #{
ComputerName = $RemoteServerIPAddress
Credential = $Creds
Name = 'RemoteSessionName'
ErrorAction = 'Stop'
}
New-PSSession $NewPSSessionSplat
}
Until (Get-PSSession -Name 'RemoteSessionName')
"$RemoteServerIPAddress is connected, starting the workflow ......"
Invoke-Command -Session $RemoteServerSession -FilePath 'C:\Temp\XXX.ps1'
}
Catch
{
Write-Warning -Message 'Session connection results:'
$PSitem.Exception.Message
}
Finally
{
Get-PSSession |
Remove-PSSession -ErrorAction SilentlyContinue
}
}
Catch
{
Write-Warning -Message "
The remote server $RemoteServerIPAddress is not available
Exiting the session."
Start-Sleep -Seconds 3
Exit
}
}
}
Start-WorkFlow
Can anyone figure out a clever way to grab the Hostname of a VM while it's still Off using PowerShell?
I only know how to grab the VM's Hostname while the VM is still On.
PS: I want the hostname/DNSName of the VM (not to be confused with the VM Name); which aren't the same thing.
You could try
get-vm |select-object -ExpandProperty network* |select-object -ExpandProperty ipaddresses |Resolve-DnsName
to grab the VM's IP address and do a reverse DNS lookup on it.
Bit late to the show here, but I took Greyula-Reyula's quite efficient answer and turned it into a function that gives more feedback on why you may be getting no output from it. I'm relatively new to this level of scripting, so I'm sure there's a more efficient way to do this, but I'm a fan of "verbosity" and try to make my scripts as easy-to-follow for myself as possible in case I want to mess with them again later. :)
Function Get-HVComputerName
{
[CmdletBinding()]
param(
[Alias("ServerName")][Parameter()]
$HVHostName = $env:COMPUTERNAME,
[Alias("ComputerName")][Parameter()]
[string[]]$VMName
)
#VMWare.VimAutomation.Core also has a "Get-VM" cmdlet,
#so unload that module if it's present first
If (Get-Module -Name VMware*) { Remove-Module -Name VMware* -Verbose:$false }
If (!(Get-Module -Name Hyper-V)) { Import-Module -Name Hyper-V -Verbose:$false }
$VMs = Get-VM -ComputerName $HVHostName -Name "*$VMName*"
If ($VMs)
{
$DNSNameArr = #()
If ($VMs.Count -gt 1)
{
Write-Host "`nFound the following VMs on Hyper-V server $HVHostName with name like `"`*$VMName`*`":" -ForegroundColor Green
$VMs.Name | Out-Default
Write-Host ""
}
ForEach ($VM in $VMs)
{
$Name = $VM.Name
If ($VerbosePreference -eq "Continue")
{
Write-Host ""
}
Write-Verbose "VM: $Name found on server $HVHostName"
If ($VM.State -ne "Running")
{
Write-Verbose "VM: $Name is not in a 'running' state. No IP address will be present.`n"
Continue
}
$VMNetAdapters = $VM | Select-Object -ExpandProperty NetworkAdapters
If ($VMNetAdapters)
{
Write-Verbose "VM $Name - Found the following network adapter(s)"
If ($VerbosePreference -eq "Continue")
{
$VMNetAdapters | Out-Default
}
ForEach ($NetAdapter in $VMNetAdapters)
{
$AdapterName = $NetAdapter.Name
$IPAddresses = $NetAdapter | Select-Object -ExpandProperty IPAddresses
If ($IPAddresses)
{
Write-Verbose "VM: $Name - Adapter: `"$AdapterName`" - Found the following IP address(es) on network adapter"
If ($VerbosePreference -eq "Continue")
{
$IPAddresses | Out-Default
}
ForEach ($IP in $IPAddresses)
{
$DNSName = $IP | Resolve-DnsName -Verbose:$false -ErrorAction SilentlyContinue
If ($DNSName)
{
$DNSFound = $true
$VMDNS = [PSCustomObject]#{
VMName = $Name
IP = $IP
DNSName = $DNSName.NameHost
}
$DNSNameArr += $VMDNS
}
Else
{
Write-Warning "VM: $Name - Adapter: `"$AdapterName`" - IP: $IP - No DNS name found"
Continue
}
}
If (!($DNSFound))
{
Write-Warning "VM: $Name - No DNS entries found for any associated IP addresses"
}
Else
{
$DNSFound = $false
}
}
Else
{
Write-Warning "VM: $Name - Adapter: `"$AdapterName`" - No IP address assigned to adapter"
Continue
}
}
}
Else
{
Write-Warning "VM: $Name - No Network adapters found"
Continue
}
}
If ($DNSNameArr)
{
If ($VerbosePreference -eq "Continue")
{
Write-Host ""
}
Return $DNSNameArr
}
Else
{
Write-Warning "No DNS names found for VM(s) with name like $VMName on server $HVHostName"
}
}
Else
{
Write-Warning "No VM found on server $HVHostName with name like $VMName"
}
} #End function Get-HVComputerName
I've recently created a little script that allows me to get the disk size and free space of 2 servers at each school site when I provide the script with the schools 4 digit site code.
First it pulls the information on the sites from a .csv file, and then uses that information to put together a string for the DC FQDN hostname, and the .10 server.
Then it requests the password for my elevated access account used to get the information on the disks.
I am having an issue where when the script creates the script block and then uses Invoke-Command and sends the script block to the servers, and provides back the PowerShell object with the information.
The error provided is as per below:
[{ServerName}] Connecting to remote server {ServerName} 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 HTTPS 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.
+ CategoryInfo : OpenError: ({ServerName}:String) [], PSRemotingTransportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionStateBroken
Things I've tried:
Resetting my password
Altering the Authentication type to Basic
Getting others to try the same thing - some have the same issue, others do not
Other users on my workstations also have the same issue
I re-imaged my workstation and it worked for a bit, but then stopped again as it appeared to stop after the device installed software updates, so I'm in the middle of uninstalling those updates, however two of them won't allow me to uninstall, I assume they're forced installs by Microsoft and required to be installed (The uninstall button disappears when selected) - KB4019472 and KB4049065.
Device is running Windows 10 1607 v14393.1944, PowerShell v5.1.
There is a one-way trust between the domain I am in and the domains the DC1 and MS10 (.10) are in, the domains trust us, but we don't trust the domains.
The account I use is local admin on the device via a nested AD Group, across all domains.
I'm not very understanding of Kerberos, so any help would be amazing.
The script is below:
Note: I've had to remove some parts, so I've filled the area with what would be there (i.e. {String} where there would just be standard text, and {FQDNServerName} where there would be a FQDN server name written as text, or {Region} where I would have had the region written as text}).
$csvSchoolsLoc = "{FQDNServerName}\SharedReports$\SchoolsExport.csv"
$Schools = Import-Csv $csvSchoolsLoc -Delimiter "`t" -Header LocCode,SchoolName,SchoolAddress,SchoolPhoneNumber,SchoolFaxNumber,SchoolOfficerInCharge,DistrictCode,DistrictNumeric,RegionCode,RegionNumeric,LSD,WANLinkType,RouterName,RouterIP,RouterStatus,OneSchemaGraphUrl,OneSchemaSiteUrl,SCCMSiteID,SiteAdminNetwork,ProxyServerIP,PrimaryDcName,PrimaryDcIP,PrimaryDcOS,PrimaryDcVersion,PrimaryDcPatch,Style
#Gets the users credentials for their GBN ZZ account - this is used throughout the script for authentication
$username = "{Region}\zz-$env:USERNAME"
$mycreds = Get-Credential -UserName $username -Message "Enter your password for {region}\zz-$env:USERNAME"
Clear-Host
Write-Host "What is the schools 4 digit site code?" -ForegroundColor Magenta
$Global:SiteCode = Read-Host
Function Main {
Clear-Host
$SchoolName = $schools | Where-Object {$_.LocCode -eq $SiteCode} | ForEach-Object SchoolName
$Region = $schools | Where-Object {$_.LocCode -eq $SiteCode} | ForEach-Object RegionCode
Write-Host "Getting details for: " -ForegroundColor Gray -NoNewline; Write-Host "$SchoolName - $SiteCode - ($Region)"-ForegroundColor Yellow
$DC1 = "{String}$($Region)$($SiteCode)001.$region.{String}.{String}.{String}"
$MS10 = "{String}$($Region)$($SiteCode)010.$region.{String}.{String}.{String}"
if (Test-Connection -ComputerName $DC1 -Count 2 -Delay 1 -Quiet) {
$DC1Run = $true
} else {
$DC1Run = $false
}
if (Test-Connection -ComputerName $MS10 -Count 2 -Delay 1 -Quiet) {
$MS10Run = $true
} else {
$MS10Run = $false
}
$ScriptBlock = {
$DiskCTotal = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='C:'" -Impersonation 3 | ForEach-Object {$_.size / 1GB}
$DiskCFree = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='C:'" -Impersonation 3 | ForEach-Object {$_.freespace / 1GB}
$DiskZTotal = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='Z:'" -Impersonation 3 | ForEach-Object {$_.size / 1GB}
$DiskZFree = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='Z:'" -Impersonation 3 | ForEach-Object {$_.freespace / 1GB}
return #{
'ZFreeSpace' = $DiskZFree
'CFreeSpace' = $DiskCFree
'ZTotalSize' = $DiskZTotal
'CTotalSize' = $DiskCTotal
}
}
if (($DC1Run -eq $true) -and ($MS10Run -eq $true)) {
$ServerDC1 = Invoke-Command -ComputerName $DC1 -Credential $mycreds -ScriptBlock $ScriptBlock
$ServerMS10 = Invoke-Command -ComputerName $MS10 -Credential $mycreds -ScriptBlock $ScriptBlock
#Clear-Host
Write-Host -ForegroundColor Yellow "$SchoolName - $SiteCode - ($Region)"
Write-Host -ForegroundColor Cyan "Server $DC1 - Domain Controller"
Write-Host "$([math]::round($ServerDC1.CFreeSpace,2)) GB free on C Drive (Total Size $([math]::round($ServerDC1.CTotalSize,2)) GB)"
Write-Host "$([math]::round($ServerDC1.ZFreeSpace,2)) GB free on Z Drive (Total Size $([math]::round($ServerDC1.ZTotalSize,2)) GB)"
Write-Host ""
Write-Host -ForegroundColor Cyan "Server $MS10 - Distribution Point"
Write-Host "$([math]::round($ServerMS10.CFreeSpace,2)) GB free on C Drive (Total Size $([math]::round($ServerMS10.CTotalSize,2)) GB)"
Write-Host "$([math]::round($ServerMS10.ZFreeSpace,2)) GB free on Z Drive (Total Size $([math]::round($ServerMS10.ZTotalSize,2)) GB)"
} else {
#Clear-Host
Write-Host -ForegroundColor Yellow "$SchoolName - $SiteCode - ($Region)"
Write-Host -ForegroundColor Cyan "Server $DC1 - Domain Controller"
if ($DC1Run) {
Write-Host "DC1 connection status is running" -ForegroundColor Green
} else {
Write-Host "DC1 connection status is down" -ForegroundColor Red
}
Write-Host ""
Write-Host -ForegroundColor Cyan "Server $MS10 - Distribution Point"
if ($MS10Run) {
Write-Host "MS10 connection status is running" -ForegroundColor Green
} else {
Write-Host "MS10 connection status is down" -ForegroundColor Red
if ($DC1Run -eq $true) {
$RDP = Read-Host -Prompt "Would you like to RDP to $DC1 'Y'"
if ($RDP -eq "Y") {
Start-Process -FilePath "$env:windir\System32\mstsc.exe" -ArgumentList "/v:$DC1" -Wait -WindowStyle Maximized
}
}
}
}
Write-Host ""
Write-Host "What is the next schools 4 digit site code? -or- Press Enter to retry the above site again" -ForegroundColor Magenta
$Entry = Read-Host
if ($Entry -eq "") {
# Do nothing
} else {
$Global:SiteCode = $Entry
}
}
$x = 0
do {
Main
} until ($x -gt 0)
EDIT: The uninstall of the software updates did not fix the issue, so unless it's something to do with those 2 updates that I can't uninstall it doesn't appear to be Software Updates.
It turns out that the domains I am trying to reach were not in my TrustedHosts config for WinRM.
By using the following command, I was able to add the domains (of which I have numerous) to the TrustedHosts using the '*' wildcard.
NOTE: I have replaced part of the domain with {String} where it would normally have part of the domain name for confidentiality reasons.
winrm set winrm/config/client #{TrustedHosts="<local>,*.{string}.edu.au"}