Details of VM and cluster - powershell

I have a command t get the cluster details from list of VM'.
ForEach ($VM in Get-Content C:\Temp\servers.txt)
{
Get-Cluster (Get-VM $vm).ComputerName
}
and the output of the script shows only cluster details of VM as below
Name
----
dhypervcl001
dhypervcl001
dhypervcl001
Can anyone tell me , how I can get an out put in below format i.e servername and clustername
server1, dhypervcl001
server2, dhypervcl0011
server3, dhypervcl012

Using string.Format:
ForEach ($VM in Get-Content C:\Temp\servers.txt)
{
"{0},{1}" -f $vm, (Get-Cluster (Get-VM $vm).ComputerName)
}
Or PSCustomObject:
ForEach ($VM in Get-Content C:\Temp\servers.txt)
{
$Row = "" | Select Server,Cluster
$Row.Server = $VM
$Row.Cluster = (Get-Cluster (Get-VM $vm).ComputerName)
$Row
}

Related

Powershell IIS Audit Scripting

I'm in the early stages of learning powershell, and I'm trying to put together a script that remotely gathers information from our IIS servers, but I'm encountering several issues.
The first one is that the IP Address and OU columns remain empty in the output file.
The second one is that I'm not able to format the Administrator group column to have 1 group per line, or delimited by commas.
This is the current version of the code:
$computers = Get-Content "C:\servers.txt"
#Running the invoke-command on remote machine to run the iisreset
$output = foreach ($computer in $computers)
{
Write-Host "Details from server $computer..."
try{
Invoke-command -ComputerName $computer -ErrorAction Stop -ScriptBlock{
# Ensure to import the WebAdministration and AD module
Import-Module WebAdministration
Import-Module ActiveDirectory
$webapps = Get-WebApplication
$list = #()
foreach ($webapp in get-childitem IIS:\AppPools\)
{
$name = "IIS:\AppPools\" + $webapp.name
$item = #{}
$item.server = $env:computername
$item.WebAppName = $webapp.name
$item.Version = (Get-ItemProperty $name managedRuntimeVersion).Value
$item.State = (Get-WebAppPoolState -Name $webapp.name).Value
$item.UserIdentityType = $webapp.processModel.identityType
$item.Username = $webapp.processModel.userName
$item.Password = $webapp.processModel.password
$item.OU = (Get-ADComputer $_ | select DistinguishedNAme)
$item.IPAddress = (Get-NetIPAddress -AddressFamily IPv4)
$item.Administrators = (Get-LocalGroupMember -Group "Administrators")
$obj = New-Object PSObject -Property $item
$list += $obj
}
$list | select -Property "Server","WebAppName", "Version", "State", "UserIdentityType", "Username", "Password", "OU", "Ip Address", "Administrators"
}
} catch {
Add-Content .\failedservers.txt -Force -Value $computer
}
}
$output | Export-Csv -Path .\output.csv
#Stop-Transcript
I'd really appreciate any input on how to get it to work properly or improve on the code itself.
Thanks in advance!
For the OU property, you'll want to reference $env:COMPUTERNAME instead of $_:
$item.OU = (Get-ADComputer $env:COMPUTERNAME |Select -Expand DistinguishedName)
For the IPAddress and Administrators fields you'll want to use -join to create comma-separated lists of the relevant values:
$item.IPAddress = (Get-NetIPAddress -AddressFamily IPv4).IPAddress -join ','
$item.Administrators = (Get-LocalGroupMember -Group "Administrators").Name -join ','

Azure powershell command to get the uptime for all vms

I am trying to generate a report where can I see uptime for all my VMs using PowerShell.
We are using AzureRmVM-(Resource manager) for those VMs.
At the moment I have found something like this:
ForEach ($vm in $vmsList) { $vm.Name + " - " + $vm.ResourceGroupName }
get-vm | where {$_.state -eq 'running'} | sort Uptime | select Name,Uptime,#{N="MemoryMB";E={$_.MemoryAssigned/1MB}},Status
How can I do that using powershell - rm(Resource manager)?
Collect all running VMs of your Subscription:
$AllVMs = Get-AzVM -Status | Where-Object { $_.PowerState -Like 'VM running' }
Then interate through each VM, catch the Audit Log, search for the VM start and calculate the Time difference to the current Time.
# Create Custom Object
$UptimeReport = #()
# Walk through each VM
foreach ($VM in $AllVMs) {
# Get Subscription Information
$ctx = Get-AzContext
Write-Host "Check: '$($VM.Name)' in Subscription '$($ctx.Subscription.Name)'"
# Get the Activity Log of the VM
$VMAzLog = Get-AzLog -ResourceId $VM.Id `
| Where-Object { $_.OperationName.LocalizedValue -Like 'Start Virtual Machine' } `
| Sort-Object EventTimestamp -Descending `
| Select-Object -First 1
$BootTime = $VMAzLog.EventTimestamp
if ($BootTime) {
$Uptime = '{0}:{1:D2}:{2:D2}' -f (24 * $TimeSpan.Days + $TimeSpan.Hours), $TimeSpan.Minutes, $TimeSpan.Seconds
}
else {
$Uptime = "n/a"
}
if ($BootTime) {
$TimeSpan = New-TimeSpan -Start $($VMAzLog.EventTimestamp) -End (Get-Date)
$UptimeReport += [PSCustomObject]#{
VM = $VM.Name
SubscriptionId = $ctx.Subscription.id
Uptime = $Uptime
}
}
}
Finally, print the Result:
# Print Result
return $UptimeReport | Sort-Object -Property VM | ft * -AutoSize

hashtable filter / select

I was working tonight to re-write an existing server health check script to store its values in a hashtable, and that part is working fine. However, I want the results to go to a CSV file, and that file only to be populated with servers where I've tagged them as requiring action. Currently those are generating event ID 7011, or failing a ping test by Test-Connection.
Here's the code:
$CheckServer = #{}
$Servers = (Get-Content $Dir\Test.txt)
foreach ($Server in $Servers) {
$CheckServer.EventID7011 = Get-Eventlog -LogName System -ComputerName $Server -Newest 1 |
Where-Object {$_.EventId -eq 7011} | select Message
if ($CheckServer.EventID -ne $Null) {
$CheckServer.Server = "$Server"
$CheckServer.ActionReq = "Yes"
}
$CheckServer.Ping = Test-Connection -ComputerName $Server -Count 1 -Quiet
if (! $CheckServer.Ping) {
$CheckServer.Server = "$Server"
$CheckServer.ActionReq ="Yes"
$CheckServer.Ping = "Offline"
} else {
$CheckServer.Server = "$Server"
$CheckServer.ActionReq = "No"
$CheckServer.Ping = "Online"
}
New-Object -TypeName PSObject -Property $CheckServer |
Export-Csv "ScanResults.csv" -NoTypeInformation -Append
}
I need the correct code at the end, as it stands, the script works fine for collecting/storing the data in the hashtable array $CheckServer, but I'd like to only select those servers that require action. So, if I'm scanning 100 servers, and 2 of them are in a ping fail state, I want only those selected and sent to Export-Csv.
If you want only servers that don't respond to Test-Connection in the output anyway it would be much simpler to just use a Where-Object filter on the server list:
Get-Content "$Dir\Test.txt" |
Where-Object { -not (Test-Connection -Computer $_ -Count 1 -Quiet) } |
Select-Object #{n='Server';e={$_}}, #{n='ActionReq';e={'Yes'}},
#{n='Ping';e={'Offline'}} |
Export-Csv 'ScanResults.csv' -NoType -Append
You need to store the objects into a list before you can filter and export them. See the lines with comments in your code:
$CheckServer = #{}
$serverObjects = #() # create a list of server objects
$Servers = (get-content $Dir\Test.txt)
ForEach ($Server in $Servers) {
$CheckServer.EventID7011 = get-eventlog -LogName System -ComputerName
$Server -newest 1 | where-object {$_.eventID -eq 7011} |select message
If ($CheckServer.EventID -ne $Null) {
$CheckServer.Server="$Server"
$CheckServer.ActionReq = "Yes"}
$CheckServer.Ping = Test-Connection -ComputerName $Server -count 1 -quiet
if (! $CheckServer.Ping) {
$CheckServer.Server="$Server"
$CheckServer.ActionReq ="Yes"
$CheckServer.Ping= "Offline"}
Else {
$CheckServer.Server="$Server"
$CheckServer.ActionReq ="No"
$CheckServer.Ping= "Online"}
# Add the server object to the list
$serverObjects += New-Object -TypeName PSObject -Property $CheckServer
}
}
# now filter it:
$serverObjects | where ActionReq -eq "Yes" | Export-Csv -Path "...."

Powershell - Get server name and IP from text list

I am using the following suggestion provided in this link:
Experts-Exchange
I am trying to take a server (host name) list and save the host name and IP address in a .csv file.
Using the following Powershell code, I do see the host name but the same IP address, for every server, in the results pane.
$servers = get-content "C:\TEMP\servers.txt"
$serversAndIps = "C:\TEMP\List_of_servers_with_ips.csv"
$results =#()
foreach ($server in $servers) {
$results =#()
$result = "" | Select ServerName , ipaddress
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses) {
"{0},{1}" -f $server, $a.IPAddressToString
}
$result.servername = $server
$results += $result
}
$results | export-csv -NoTypeInformation $serversandips
When I open the .csv file, I get this:
"ServerName","ipaddress"
"Server_name_1","System.Net.IPAddress[]"
If I run this PowerShell script, I can get the host name and the correct IP address in the results pane. I just need to know how to transfer the results to a .csv file.
$servers = get-content "C:\TEMP\servers.txt"
foreach ($server in $servers) {
$addresses = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses) {
"{0},{1}" -f $server, $a.IPAddressToString
}
}
Any suggestions?
Looks like some simple typos at work.
$result was being reset inside the in the loop
$addresses inside the loop wasn't assigned.
$result.ipaddress was not assigned to $a.IPAddressToString for the output object.
Try this:
$servers = get-content "X:\servers.txt"
$serversAndIps ="X:\test.csv"
$results = #()
foreach ($server in $servers)
{
$result = "" | Select ServerName , ipaddress
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
$addresses = [System.Net.Dns]::GetHostAddresses($server)
foreach($a in $addresses)
{
"{0},{1}" -f $server, $a.IPAddressToString
$result.ipaddress = [System.Net.Dns]::GetHostAddresses($server)
}
$result.servername = $server
$result.ipaddress = $a.IPAddressToString
$results += $result
}
$results | export-csv -NoTypeInformation $serversandips

Powershell Script - Services Running eq OK or list Services Not Running

I have this script which checks multiple servers for particular services running.
I need assistance or pointers on how to get it to not pull back running / not running response. I need to get it to be "If all queried services are running = OK, if not list service not running"
Is this doable?
Script:
$Check1 = Get-service -Computername server1 -Name *service1* | ConvertTo-Html Name,Status -Fragment
$Check2 = Get-Service -Computername server2 -name *service2* | ConvertTo-Html Name,Status
$Check3 = Get-Service -Computername server3 -name *service3* | ConvertTo-Html Name,Status
$Check4 = Get-Service -ComputerName UKVAULT01 -Name *service4* | ConvertTo-Html Name,Status
ConvertTo-HTML -Body "<b>Check1</b> $Check1 <br> <b>Check2</b> $Check2 <br> <b>Check3</b> $Check3<br> <b>Check4</b> $Check4" -Title "Service Checks" | Out-File c:\StatusReport.html
Encapsulate the checks in a function like this:
function Check-Service{$server, $name) {
$check = Get-Service $server -Name $name | ? { $_.Status -ne "Running" }
if ( $check -eq $null ) { $check = "OK" }
$check | ConvertTo-Html -Fragment
}
$Check1 = Check-Service server1 *service1*
$Check2 = Check-Service server2 *service2*
...