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
Related
$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.
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
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
I have this code which deletes User Profiles off a remote machine. The removal of profiles work just fine but, the Aesthetic of doing so doesn't. What do i mean?
I'm passing the user display names to an index and making a selection out of it, and that works fine in regards to assigning the proper names to the appropriate Index Number its associated to in C:\users.
The next line of code is it grabbing the selections i made, and running through them displaying the same name i did for the index, and then it goes off to delete the CIM instance.
So my question is, why is it not passing the subexpression $userinfo1 that is already made and not putting it into the next block of code, for example, the following works as in grabbing the proper Display Name and assigning it to the proper Number:
$menu = (get-childitem "\\$cn\c$\users" | sort LastWriteTime -Descending).Name
$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
$userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name ", "" 2>&1 | Out-String -Stream
if ($userinfo.Length -lt 4) {
"$user - NO DISPLAY NAME in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 2) {
"$user - account not in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 0){
$userinfo # output
}
}
}
}
Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"
Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White
for ($i=0; $i -lt $userinfo1.Count; $i++) {
Write-Host "$($i): $($userinfo1[$i])"
} #END LIST OF POSSIBLE NAMES
Write-Host ""
Write-Host "For multiple users, seperate using a SPACE(1 2 3)"
$selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"
$selection = $selection -split " "
but, the next block doesn't associate the display name (that was captured in $userinfo1) with the number i select and it just continues to display the first display name with the rest of the profiles its reiterating through:
foreach($Profile in $menu[$selection]){
Write-Host "Deleting user: $(,$userinfo1[$selection]) `
ID:$Profile "}
Hopefully this makes sense, and if anyone can point me in the right direction id greatly appreciate it!
Heres the rest of the script, please feel free to use it as it does work for deleting the actual profile off the system and not just the files.
#Deletes a profile properly off remote machine. WARNING: DOES NOT BACK UP DATA! Use at your own peril. Delprofile
$cn = Read-Host -Prompt "Enter Computer Name"
$ping = Test-Connection -ComputerName $cn -Count 1 -Quiet
If($ping -eq $false){ Write-Host "Computer seems to be offline, please check name spelling." -ForegroundColor DarkYellow; Write-Host ""; &PFL-Delete } else {
$menu = (get-childitem "\\$cn\c$\users" | sort LastWriteTime -Descending).Name
$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
$userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name ", "" 2>&1 | Out-String -Stream
if ($userinfo.Length -lt 4) {
"$user - NO DISPLAY NAME in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 2) {
"$user - account not in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 0){
$userinfo # output
}
}
}
}
Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"
Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White
for ($i=0; $i -lt $userinfo1.Count; $i++) {
Write-Host "$($i): $($userinfo1[$i])"
} #END LIST OF POSSIBLE NAMES
Write-Host ""
Write-Host "For multiple users, seperate using a SPACE(1 2 3)"
$selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"
$selection = $selection -split " "
foreach($Profile in $menu[$selection]){
Write-Host "Deleting user: $(,$userinfo1[$selection]) `
ID:$Profile "
$del = Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile }
If($del -eq $null){Write-Warning "No CIM instance found on system, profile has been deleted but files persist. Delete manually!"} else{
Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile } | Remove-CimInstance -WhatIf
Write-Host "user profile has been deleted" -ForegroundColor Red
Write-Host ""}
}
}
#CountPs $cn
12/31/2020 - EDIT:
Here is the finished result:
Function Delete-PFL{
#Deletes a profile properly off remote machine. WARNING: DOES NOT BACK UP DATA! Use at your own peril. Delprofile
$cn = Read-Host -Prompt "Enter Computer Name"
$ping = Test-Connection -ComputerName $cn -Count 1 -Quiet
If($ping -eq $false){ Write-Host "Computer seems to be offline, please check name spelling." -ForegroundColor DarkYellow; Write-Host ""; &Delete-PFL } else {
$menu = (get-childitem "\\$cn\c$\users" | sort LastWriteTime -Descending).Name
$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
$userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name ", "" 2>&1 | Out-String -Stream
if ($userinfo.Length -lt 4) {
"$user - NO DISPLAY NAME in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 2) {
"$user - ACCOUNT NOT in ADUC" # output
}
else {
if ($LASTEXITCODE -eq 0){
$userinfo # output
}
}
}
}
Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"
Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White
for ($i=0; $i -lt $userinfo1.Count; $i++) {
Write-Host "$($i): $($userinfo1[$i])"
} #END LIST OF POSSIBLE NAMES
Write-Host ""
Write-Host "For multiple users, seperate using a SPACE(1 2 3)"
$selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"
$selection = $selection -split " "
foreach($index in $selection) {
$Profile = $menu[$index]
Write-Host "Deleting user: $($userinfo1[$index]) `
ID:$Profile "
$del = Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile }
If($del -eq $null){Write-Warning "No CIM instance found on system, profile has been deleted but files persist."
Write-Host "Attempting to delete files, please wait. . ."
Remove-Item -Path "\\$cn\c$\users\$Profile" -Force -WhatIf
Write-Host ""
Start-Sleep -Seconds 2
Write-Host "Checking if Files are still there. . ."
$TestPath = Test-Path -Path "\\$cn\c$\users\$Profile"
If($TestPath -eq $false){ Write-Host "Profile Files have been deleted. `
Continuing. . . ." -ForegroundColor Green
}
} else{
Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile } | Remove-CimInstance -WhatIf
Write-Host "user profile has been deleted" -ForegroundColor Red
Write-Host ""
}
}
}
#CountPs $cn
}
Remember to remove the -whatif parameter. Enjoy!
$selection is an array of indices, so in your foreach loop you must refer to the single index at hand, not to $selection as a whole, to get the desired display output.
The conceptually clearest approach is probably to iterate over the indices contained in $selection:
foreach($index in $selection) {
$Profile = $menu[$index]
Write-Host "Deleting user: $($userinfo1[$index]) `
EDIPI:$Profile "
# ...
}
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.