Powershell Menu - powershell

I am looking to have this menu that I have been frankensteining and learning powershell while doing so, I am a systems admin I and trying to learn PS and more networking to grow in career. Any edits and advice is much appreciated I just bought a ps book and youtubing a lot!
Function Menu {
Clear-Host
Do
{
Clear-Host
Write-Host -Object 'Please choose an option'
Write-Host -Object '**********************'
Write-Host -Object 'Scripts to run' -ForegroundColor Yellow
Write-Host -Object '**********************'
Write-Host -Object '1. Ping PC '
Write-Host -Object ''
Write-Host -Object '2. Restart ELP Desktops '
Write-Host -Object ''
Write-Host -Object '3. Restart NOVI Desktops '
Write-Host -Object ''
Write-Host -Object '4. Check PC Storage '
Write-Host -Object ''
Write-Host -Object 'Q. Quit'
Write-Host -Object $errout
$Menu = Read-Host -Prompt '(0-4 or Q to Quit)'
switch ($Menu)
{
1 {
$Computer = Read-Host Please Enter Host name
Get-WMIObject Win32_NetworkAdapterConfiguration -Computername $Computer | `
Where-Object {$_.IPEnabled -match "True"} | `
Select-Object -property DNSHostName,ServiceName,#{N="DNSServerSearchOrder";
E={"$($_.DNSServerSearchOrder)"}},
#{N='IPAddress';E={$_.IPAddress}},
#{N='DefaultIPGateway';E={$_.DefaultIPGateway}} | FT
pause
}
2
{
restart-computer -ComputerName ######## -force
}
3
{
restart-computer -ComputerName ######## -force
}
4
{
# Ask for computer name
$Computer = Read-Host "Please Enter Host name"
Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter DriveType=3 | Select-
Object DeviceID, FreeSpace, Size |pause
}
Q
{
Exit
}
default
{
$errout = 'Invalid option please try again........Try 0-4 or Q only'
}
}
}
until ($Menu -eq 'q')
}
# Launch The Menu
Menu

Related

How to store the username in a csv file before and after the change using Powershell - ($BeforeAccountChange - Works) $AfterChangeAccount - Does NOT

$complist = Get-Content "c:\scripts\computers.txt"
foreach($computer in $complist){
Write-Host "Checking on $computer" -ForegroundColor yellow
Write-host ""
$pingtest = Test-Connection -ComputerName $computer -Quiet -Count 1 -ErrorAction SilentlyContinue
if($pingtest){
Write-Host($computer + " is online") -ForegroundColor Green
Invoke-Command -Computername $computer {
Get-Service | Where-Object {$_.Name -eq "ontapavc"}
$service = Get-WmiObject win32_service -filter "name='ontapavc'"
$BeforeChangeAccount=$service.StartName
Write-Host ""
Write-Host "Logon Credentials for " -ForegroundColor cyan -NoNewline;Write-Host $service.DisplayName -NoNewline; Write-Host " prior to Script Change: "-ForegroundColor cyan -NoNewline;Write-Host $service.StartName
Write-Host ""
Write-Host "Setting default logon Credentials" -ForegroundColor yellow
SC.exe CONFIG "ontapavc" obj= Home\Tester password= "Testing"
$AfterChangeAccount=$service.StartName
Write-Host ""
Write-Host "Setting Recovery Options" -ForegroundColor yellow
SC.exe failure "ontapavc" reset= 60000 actions= restart/60000/restart/60000/reboot/60000
Write-Host ""
Write-Host "Stopping service " -ForegroundColor yellow -NoNewline; Write-Host $service.name
Get-Service | Where-Object {$_.Name -eq "ontapavc"} | Stop-Service -PassThru
Write-Host ""
Write-Host "Restarting service " -ForegroundColor yellow -NoNewline; Write-Host $service.name
Get-Service | Where-Object {$_.Name -eq "ontapavc"} | Start-Service -PassThru
Write-Host ""
Write-Host ""
Write-Host ""
}
Write-Host "Logon Credentials for " -ForegroundColor cyan -NoNewline;Write-Host $servicename -NoNewline; Write-Host " after Change:"-ForegroundColor cyan -NoNewline;Write-Host $afterchangeaccount
$Sample = Get-WmiObject -Query "select * from win32_service where name='ontapavc'" -ComputerName $computer | Select-Object #{Name = 'Time'; Expression = {(Get-Date -format s)}}, PSComputerName, Name,DisplayName, ServiceName, Status, #{Name = 'Username Prior to Change'; Expression = { ($BeforeChangeAccount = $service.StartName)}}, #{Name = 'Username After Change'; Expression = { ($AfterChangeAccount = $service.StartName)}}
$Sample | Export-Csv -Path c:\Temp\ServiceList_-$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation
}else{
Write-Host $computer "is not reachable" -ForegroundColor red
Write-host ""
}
}
The 2 variables mentioned live in a remote scope. Therefore, you need to bring them out of your Invoke-Command to be referenced in your local scope.
$complist = Get-Content "c:\scripts\computers.txt"
foreach($computer in $complist){
Write-Host "Checking on $computer" -ForegroundColor yellow
Write-host ""
$pingtest = Test-Connection -ComputerName $computer -Quiet -Count 1 -ErrorAction SilentlyContinue
if ($pingtest) {
Write-Host($computer + " is online") -ForegroundColor Green
Invoke-Command -Computername $computer {
Get-Service | Where-Object {$_.Name -eq "ontapavc"} | Write-Host
$service = Get-WmiObject win32_service -filter "name='ontapavc'"
$BeforeChangeAccount=$service.StartName
Write-Host ""
Write-Host "Logon Credentials for " -ForegroundColor cyan -NoNewline;Write-Host $service.DisplayName -NoNewline; Write-Host " prior to Script Change: "-ForegroundColor cyan -NoNewline;Write-Host $service.StartName
Write-Host ""
Write-Host "Setting default logon Credentials" -ForegroundColor yellow
SC.exe CONFIG "ontapavc" obj= Home\Tester password= "Testing"
$AfterChangeAccount=$service.StartName
Write-Host ""
Write-Host "Setting Recovery Options" -ForegroundColor yellow
SC.exe failure "ontapavc" reset= 60000 actions= restart/60000/restart/60000/reboot/60000
Write-Host ""
Write-Host "Stopping service " -ForegroundColor yellow -NoNewline; Write-Host $service.name
Get-Service | Where-Object {$_.Name -eq "ontapavc"} | Stop-Service -PassThru | Write-Host
Write-Host ""
Write-Host "Restarting service " -ForegroundColor yellow -NoNewline; Write-Host $service.name
Get-Service | Where-Object {$_.Name -eq "ontapavc"} | Start-Service -PassThru | Write-Host
Write-Host ""
Write-Host ""
Write-Host ""
[PSCustomObject]#{
Before = $BeforeChangeAccount
After = $AfterChangeAccount
}
} | Set-Variable changes
Write-Host "Logon Credentials for " -ForegroundColor cyan -NoNewline;Write-Host $servicename -NoNewline; Write-Host " after Change:"-ForegroundColor cyan -NoNewline;Write-Host $afterchangeaccount
$Sample = Get-WmiObject -Query "select * from win32_service where name='ontapavc'" -ComputerName $computer | Select-Object #{Name = 'Time'; Expression = {(Get-Date -format s)}}, PSComputerName, Name,DisplayName, ServiceName, Status, #{Name = 'Username Prior to Change'; Expression = { $changes.Before}}, #{Name = 'Username After Change'; Expression = { $changes.After}}
$Sample | Export-Csv -Path c:\Temp\ServiceList_-$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation
}else{
Write-Host $computer "is not reachable" -ForegroundColor red
Write-host ""
}
}
By not polluting the pipeline, you should be able to create a pscustomobject to hold the two outputs you're looking for.
[PSCustomObject]#{
Before = $BeforeChangeAccount
After = $AfterChangeAccount
}
Now you can save to a variable to reference later on in your calculated properties since $changes now holds a before and after property.

Get-WmiObject delay outcome when check C disk storage

Get-WmiObject delay outcome when check C disk storage.
When I input my computer name and type '1' to check the C disk storage, the first time won't return the outcome, and I need to type '1' again it will return both the first and second outcome.
However, if I test the function or the line Get-WMIObject separately, it works perfect.
Anyone have any idea what's going on here?
$ComputerNumber = (read-host "Provide computer number").trim()
function Show-Storage{
Get-WmiObject -Class win32_logicaldisk -Filter "DeviceID='C:'" -ComputerName $ComputerNumber|select PSComputerName,DeviceID,#{n='size(GB)';e={$_.size/1gb -as [int]}},#{n='Free(GB)';e={$_.freespace/1gb -as [int]}}
}
function Show-Menu
{
param (
[string]$Title = 'Computer Info'
)
Write-Host "================ $Title ================"
Write-Host ""
Write-Host "1: Press '1' to get Current Computer Usage"
Write-Host "2: Press '2' to delete Local User Profile"
Write-Host "Q: Press 'Q' to quit."
}
$a=1
While ($a -eq 1)
{
write-host ""
Show-Menu
write-host ""
if ($ComputerNumber -ne $null){
write-host "Selected Computer '$ComputerNumber'"
}
else{write-host "No Computer selected"}
$selection = Read-Host "Please make a selection"
switch($selection)
{
'1'{
write-host ""
Show-Storage
write-host ""
}
'2'{
delete-profile
}
'Q'{$a=0}
}
}
I just found another interesting thing, if I leave the line $result, the result will come before the "WMI end", but if I remove that line, the result will still comes after "WMI end"
Write-Host "WMI Start"
$result = Get-WmiObject -query "SELECT * FROM Win32_logicalDisk WHERE DeviceID = 'C:'" -ComputerName $PC
$result
$result |select PSComputerName,DeviceID,#{n='size(GB)';e={$_.size/1gb -as [int]}},#{n='Free(GB)';e={$_.freespace/1gb -as [int]}}
Write-Host "WMI End"
enter image description here
Found solution finally, use | Out-Host can fix this issue.
Reference:
Get-WMIObject returning multiple responses in a script, only one when run alone

Adding new options causes issues

I have been able to create and frankenstein a menu to help me as IT support and am still learning powershell to read and write it proficiently but am confused why if I put more options I run into issues mainly at the end.
Function Menu
{
Clear-Host
Do
{
Clear-Host
Write-Host -Object 'Please choose an option'
Write-Host -Object '**********************'
Write-Host -Object 'Scripts to run' -ForegroundColor Yellow
Write-Host -Object '**********************'
Write-Host -Object '1. Ping PC '
Write-Host -Object ''
Write-Host -Object '2. Restart ELP Desktops '
Write-Host -Object ''
Write-Host -Object '3. Restart NOVI Desktops '
Write-Host -Object ''
Write-Host -Object '4. Check PC Storage '
Write-Host -Object ''
Write-Host -Object '5. Check all user adpw exp'
Write-Host -Object ''
Write-Host -Object 'Q. Quit'
Write-Host -Object $errout
$Menu = Read-Host -Prompt '(0-5 or Q to Quit)'
switch ($Menu)
{
1
{
$Computer = Read-Host Please Enter Host name
Get-WMIObject Win32_NetworkAdapterConfiguration -Computername $Computer | `
Where-Object {$_.IPEnabled -match "True"} | `
Select-Object -property DNSHostName,ServiceName,#{N="DNSServerSearchOrder";
E={"$($_.DNSServerSearchOrder)"}},
#{N='IPAddress';E={$_.IPAddress}},
#{N='DefaultIPGateway';E={$_.DefaultIPGateway}} | FT
pause
}
2
{
restart-computer -ComputerName ##### -force
}
3
{
restart-computer -ComputerName ####-force
}
4
{
Invoke-Command -ComputerName (Read-Host -Prompt "Please Enter Host name") {Get-PSDrive | Where {$_.Free -gt 0}}
pause
}
5
{
get-aduser -filter * -properties passwordlastset, passwordneverexpires |ft Name, passwordlastset, Passwordneverexpires
pause
}
Q
{
Exit
}
default
{
$errout = 'Invalid option please try again........Try 0-5 or Q only'
}
}
}
until ($Menu -eq 'q')
}
# Launch The Menu
Menu

If/Else Help in Powershell

Running an IF/Else statement and if "false" I want it to run a search for the current NVIDIA driver and tell me the current version then stop the script. Tried a couple different things to no avail. Currently it is continuing the script and running the "Get-WmiObject" out of order in a subsequent function.
Function Namespace_Check
{ Write-Host "Checking available namepace" -ForegroundColor Green
if ((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV'){return}
else { return (Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like "*nvidia*"})}
Write-Host "If Stopped, install latest NVIDIA driver from SWE"
Write-Host "Complete" -ForegroundColor Green
}
Here is the whole script, if there needs to be other changes to the logic
Function Namespace_Check
{ Write-Host "Checking available namepace" -ForegroundColor Green
Write-Host "Complete" -ForegroundColor Green
if ((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV'){return}
else {
exit (Get-WmiObject Win32_PnPSignedDriver| select devicename, driverversion | where {$_.devicename -like "*nvidia*"})
Write-Warning "Install latest NVIDIA driver from SWE"
Write-Host
}
}
Function InstallSWE
{
Write-Host "Installing SWE Icon..." -ForegroundColor Green
$ps = new-object System.Diagnostics.Process
$ps.StartInfo.FileName = "\\nt-iss-1\setools\xsetup.exe"
$ps.StartInfo.Arguments = " -Silent -NoPrompt -NoBanner"
Write-Host " Execute Software Express"
[Void]$ps.start()
$ps.WaitForExit()
Write-Host "Complete" -ForegroundColor Green
}
Function CheckNVIDIADriver
{
Write-Host "Checking NVIDIA Drivers..." -ForegroundColor Green
$productName = Get-WmiObject -namespace "root\cimv2\nv" -Class Gpu | Select -ExpandProperty productName
$driverVersion = Get-Wmiobject -namespace "root\cimv2\nv" -class System | Select -ExpandProperty verDisplayDriver | Select -ExpandProperty strValue
Write-Host " Product Name : $productName"
Write-Host " Video Driver Version: $driverVersion"
Write-Host "Complete" -ForegroundColor Green
}
Function SetNVIDIA3DGlobalPreset
{
Write-Host "Setting NVIDIA 3D Global Preset..." -ForegroundColor Green
$global3DPreset = "Dassault Systemes CATIA - compatible"
$profileManager = Get-WmiObject -namespace "root\cimv2\nv" -Class ProfileManager
"Change Global 3D Preset to $global3DPreset"
[void](Invoke-WmiMethod -Path $profileManager.__PATH -Name setCurrentProfile3D -ArgumentList $global3DPreset, $null)
Write-Host "Complete" -ForegroundColor Green
}
Function SetScreenSaver
{
Write-Host "Setting Screen Saver..." -ForegroundColor Green
$regkeypath = "HKCU:\Control Panel\Desktop"
$screensaver = "C:\Windows\SysWOW64\CORPOR~1.SCR"
Write-Host " Change Screen Saver to Corporate Screen Saver"
Set-ItemProperty -Path $regkeypath -Name "SCRNSAVE.EXE" -Value $screensaver
Write-Host "Complete" -ForegroundColor Green
}
Function ChangePowerSettings
{
Write-Host "Changing Power Settings..." -ForegroundColor Green
Write-Host " Disable Monitor Timeout"
powercfg -x -monitor-timeout-ac 10
powercfg -x -monitor-timeout-dc 10
Write-Host " Disable Disk Timeout"
powercfg -x -disk-timeout-ac 0
powercfg -x -disk-timeout-dc 0
Write-Host " Disable Standby Timeout"
powercfg -x -standby-timeout-ac 0
powercfg -x -standby-timeout-dc 0
Write-Host " Disable Hibernate and Hybrid Sleep"
powercfg -x -hibernate-timeout-ac 0
powercfg -x -hibernate-timeout-dc 0
powercfg -h off
Write-Host "Complete" -ForegroundColor Green
}
Function ChangeVirtualMemory
{
Write-Host "Changing Virtual Memory Settings..." -ForegroundColor Green
$mem = [Math]::Round((Get-WmiObject -Class Win32_ComputerSystem |Select -ExpandProperty TotalPhysicalMemory) / [Math]::pow(1024, 3))
$initialSize = 2048 * $mem
$maximumSize = 2 * $initialSize
Write-Host " Disable Automatic Managed Page File"
$System = Get-WmiObject Win32_ComputerSystem -EnableAllPrivileges
$System.AutomaticManagedPagefile = $False
[Void]$System.Put()
Write-Host " Set Page File Size (Initial Size: $initialSize MB / Maximum Size: $maximumSize MB)"
$PageFile = Get-WmiObject -class Win32_PageFileSetting
$PageFile.InitialSize = $initialSize
$PageFile.MaximumSize = $maximumSize
[Void]$PageFile.Put()
Write-Host "Complete" -ForegroundColor Green
}
Function EnableRDP
{
Write-Host "Enabling Remote Desktop and User..." -ForegroundColor Green
$computername = $(gc env:computername)
$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting -Namespace root\CIMV2\TerminalServices
Write-Host " Enable Remote Desktop"
$result = $RDP.SetAllowTsConnections(1, 1)
Try
{
$user ="CAxILABRemoteUsers"
$domain ='NW'
$objUser = [ADSI]("WinNT://$domain/$user")
$objGroup = [ADSI]("WinNT://$computername/Remote Desktop Users")
Write-Host " Add Remote Desktop User $domain\$user"
$objGroup.PSBase.Invoke('Add',$objUser.PSBase.Path)
}
Catch
{
}
Write-Host "Complete" -ForegroundColor Green
}
Function CheckAdministrator
{
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
# Filename: CAxILab_Final_Config.ps1
$pshost = get-host
$pswindow = $pshost.ui.rawui
$newsize = $pswindow.buffersize
$newsize.height = 999
$pswindow.buffersize = $newsize
$newsize = $pswindow.windowsize
#$newsize.height = 60
#$pswindow.windowsize = $newsize
$host.ui.RawUI.ForegroundColor = "White"
$isAdmin = CheckAdministrator
if ($isAdmin)
{
Namespace_Check
Write-Host
InstallSWE
Write-Host
CheckNVIDIADriver
Write-Host
SetNVIDIA3DGlobalPreset
Write-Host
SetScreenSaver
Write-Host
ChangePowerSettings
Write-Host
ChangeVirtualMemory
Write-Host
EnableRDP
Write-Host
}
else
{
Write-Warning "Administrator rights is required to run this script"
Write-Host
}
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# end of script
If you want the script stopped completely when the namespace is not found, change the function Namespace_Check into something like this:
Function Namespace_Check {
Write-Host "Checking available namepace" -ForegroundColor Green
if (!((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV')) {
# if we got here, the namespace is not found
# output the current version, then stop the script
$driver = Get-WmiObject Win32_PnPSignedDriver|
Select-Object devicename, driverversion |
Where-Object {$_.devicename -like "*nvidia*"}
Write-Host "If Stopped, install latest NVIDIA driver from SWE"
if ($driver) {
Write-Host "Current driver(s)" -ForegroundColor Yellow
$driver | Format-Table -AutoSize
}
else {
Write-Warning "No nvidia drivers found"
}
Write-Host "Script Complete" -ForegroundColor Green
# stop the script
exit
}
}
In your version you are trying to write to console after you have exited the function using a return statement. These lines will therefore never be executed.
Edit
Alternatively, you can have the function Namespace_Check return a value of $true of $false like this:
Function Namespace_Check {
Write-Host "Checking available namepace" -ForegroundColor Green
if (!((Get-CimInstance -namespace "root\cimv2" -ClassName __NAMESPACE).Name -match 'NV')) {
# if we got here, the namespace is not found
# output the current version, then stop the script
$driver = Get-WmiObject Win32_PnPSignedDriver|
Select-Object devicename, driverversion |
Where-Object {$_.devicename -like "*nvidia*"}
Write-Host "If Stopped, install latest NVIDIA driver from SWE"
if ($driver) {
Write-Host "Current driver(s)" -ForegroundColor Yellow
$driver | Format-Table -AutoSize
}
else {
Write-Warning "No nvidia drivers found"
}
Write-Host "Script Complete" -ForegroundColor Green
return $false
}
return $true
}
and in the main part of your script do
if ($isAdmin) {
if (Namespace_Check) {
Write-Host
InstallSWE
Write-Host
CheckNVIDIADriver
Write-Host
SetNVIDIA3DGlobalPreset
Write-Host
SetScreenSaver
Write-Host
ChangePowerSettings
Write-Host
ChangeVirtualMemory
Write-Host
EnableRDP
Write-Host
}
}
else {
Write-Warning "Administrator rights is required to run this script"
Write-Host
}
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# end of script
This will make the script end gracefully instead of when using the exit statement.

Get-Service in a Powershell Script

A basic question - but why in a Powershell Script does Get-Service not print the list to the output?
Write-Host "Enumerating installed Services..." -ForegroundColor Green
Get-Service | Sort-Object status,displayname
Now in the script it gives no output at all.
But if I opened a powershell prompt and typed it manually it works fine.
Full Script:
param([string] $server)
$serverSystem = Get-WmiObject -computername $env:computername Win32_ComputerSystem
$serverCPUDetail = Get-WmiObject -ComputerName $env:computername Win32_Processor
switch ($ComputerSystem.DomainRole){
0 {$ComputerRole = "Standalone Workstation"}
1 {$ComputerRole = "Member Workstation"}
2 {$ComputerRole = "Standalone Server"}
3 {$ComputerRole = "Member Server"}
4 {$ComputerRole = "Domain Controller"}
5 {$ComputerRole = "Domain Controller"}
default {$ComputerRole = "No role available" }
}
$serverOS = Get-WmiObject -class Win32_OperatingSystem -ComputerName $env:computername
Write-Host "Enumerating System information..." -ForegroundColor Green
" "
Start-Sleep -s 1
Write-Host "Hostname:" ($env:computername)
Write-Host "Domain:" ($serverSystem.Domain)
Write-Host "Role:" ($ComputerRole)
Write-Host "Operating System:" ($serverOS.Caption)
Write-Host "Service Pack:" ($serverOS.CSDVersion)
$lastBootTime = $serverOS.ConvertToDateTime($serverOS.Lastbootuptime)
Write-Host "Last Boot Time:" $lastBootTime
" "
Write-Host "Enumerating Hardware information..." -ForegroundColor Green
" "
Start-Sleep -s 1
Write-Host "Model:" ($serverSystem.Model)
Write-Host "Manufacturer:" ($serverSystem.Manufacturer)
Write-Host "CPU - No. of Processors:" ($serverSystem.NumberOfProcessors)
Write-Host "CPU - No. of Cores:" ($serverCPUDetail.NumberofCores)
Write-Host "CPU - No. of Processors, Logical:" ($serverCPUDetail.NumberOfLogicalProcessors)
Write-Host "Memory in GB:" ([math]::round($serverSystem.TotalPhysicalMemory/1024/1024/1024,0))
" "
Write-Host "Enumerating Disk Information..." -ForegroundColor Green
Start-Sleep -s 1
Foreach ($s in $env:computername) {
Get-WmiObject -Class win32_volume -cn $s |
Select-Object #{LABEL='Comptuer';EXPRESSION={$s}},DriveLetter, Label,#{LABEL='Free Space (GB)';EXPRESSION={"{0:N2}" -f ($_.freespace/1GB)}}
}
" "
Write-Host "Enumerating Network Information..." -ForegroundColor Green
" "
Start-Sleep -s 1
ForEach($NIC in $env:computername) {
$intIndex = 1
$NICInfo = Get-WmiObject -ComputerName $env:computername Win32_NetworkAdapterConfiguration | Where-Object {$_.IPAddress -ne $null}
$caption = $NICInfo.Description
$ipAddress = $NICInfo.IPAddress
$ipSubnet = $NICInfo.IpSubnet
$ipGateWay = $NICInfo.DefaultIPGateway
$macAddress = $NICInfo.MACAddress
Write-Host "Network Card": $intIndex
Write-Host "Interface Name: $caption"
Write-Host "IP Addresses: $ipAddress"
Write-Host "Subnet Mask: $ipSubnet"
Write-Host "Default Gateway: $ipGateway"
Write-Host "MAC: $macAddress"
$intIndex += 1
}
" "
# Write-Host "Enumerating Software Installations..." -ForegroundColor Green
# " "
# Get-WmiObject -Class Win32_Product | Select-Object -property Name
Write-Host "Enumerating installed Services..." -ForegroundColor Green
Get-Service | Sort-Object status,displayname
The code that you posted is fine. It's something else that you are not showing that does not work.
Try this:
$script = #"
Write-Host "Enumerating installed Services..." -ForegroundColor Green
Get-Service | Sort-Object status,displayname
"#
$script | Set-Content ./test.ps1
./test.ps1
The above writes your two lines in a script file and then executes the script. As you would expect it produces desired output.
Update 1
Having seen the input, I can now reproduce the problem. Basically if you run this:
$a= Get-WmiObject -Class win32_volume -cn $s |
Select-Object #{LABEL='Comptuer';EXPRESSION={$s}},DriveLetter, Label,#{LABEL='Free Space (GB)';EXPRESSION={"{0:N2}" -f ($_.freespace/1GB)}}
$b = Get-Service | Sort-Object status,displayname
$a
$b
you will see that it does not quite work. What happening here is that by default Write-Output is used to process the results. Write-Output writes stuff in the success pipeline, and powershell does unwrapping of the arrays. Then, I'm guessing the output system can't cope with the fact that output from get-service and select-object are of different types (and because of unwrapping they end up in the same array).
If you change the last line of your script to
Get-Service | Sort-Object status,displayname | ft
it will work. However note, that if you are going to pass around the results of your script, you better format it (ft) at the very end right before displaying. Basically, once you piped it to ft there is rarely a good reason to pass it anywhere else but for output (display or file).
Update 2
This article explains, that powershell uses the first object in the stream to determine how to format all of them. This explains the behaviour that we are observing.