I would like to design a condition which is if the tcp connection result is return "true", will proceed install action and go next function. Otherwise, it will return a warning message, stop to proceed and pass to next function. I don't know how to implement keep to proceed next function if occurs any warning on current function.
Is there anybody can help to fix the issue?
Many Thanks.
function A(){
$printerIPAddress = "192.168.1.100"
$sharedPrinter = "\\SERVERNAME\A"
$checkPrinterExists = Get-Printer -Name $sharedPrinter -ErrorAction SilentlyContinue
if ((Test-NetConnection -ComputerName $printerIPAddress -WarningAction SilentlyContinue).PingSucceeded){
Write-Host "Succeed to connect - $printerIPAddress" -ForegroundColor Black -BackgroundColor Gray
Start-Sleep(2)
}
else {
Write-Warning "Failure to connect - $printerIPAddress"
}
if (-not $checkPrinterExists){
Write-Host "Installing a printer..."
Add-Printer -ConnectionName $sharedPrinter
Write-Host "Succeed to install - A Printer" -ForegroundColor Black -BackgroundColor Gray
}
else{
Write-Warning "Failure to install - A Printer already exist"
}
}
function B(){
$printerIPAddress = "192.168.1.101"
$sharedPrinter = "\\SERVERNAME\B"
$checkPrinterExists = Get-Printer -Name $sharedPrinter -ErrorAction SilentlyContinue
if ((Test-NetConnection -ComputerName $printerIPAddress -WarningAction SilentlyContinue).PingSucceeded){
Write-Host "Succeed to connect - $printerIPAddress" -ForegroundColor Black -BackgroundColor Gray
Start-Sleep(2)
}
else {
Write-Warning "Failure to connect - $printerIPAddress"
}
if (-not $checkPrinterExists){
Write-Host "Installing a printer..."
Add-Printer -ConnectionName $sharedPrinter
Write-Host "Succeed to install - B Printer" -ForegroundColor Black -BackgroundColor Gray
}
else{
Write-Warning "Failure to install - B Printer already exist"
}
}
Write-Host "Running...Please wait..."
A;
B;
I've attempted to simplify your code and also inherently handled the "stop to proceed if Test-NetConnection fails" scenario.
As your main objective is to install the printer, the function will error out if the parameter $sharedPrinter fails the defined ValidateScript criteria.
Function Install-Printer {
[CmdletBinding()]
Param(
[parameter(Mandatory=$true)]
[ValidateScript({$_ -match [IPAddress]$_ })]
[string]
$printerIPAddress,
[parameter(Mandatory=$true)]
[ValidateScript({(Test-Path $_) -and ($Printer = Get-Printer -Name $_)})]
[string]
$sharedPrinter
)
if ((Test-NetConnection -ComputerName $printerIPAddress -WarningAction SilentlyContinue).PingSucceeded) {
Write-Host "Succeed to connect - $printerIPAddress" -ForegroundColor Black -BackgroundColor Gray
Write-Host "Installing a printer..."
Add-Printer -ConnectionName $sharedPrinter
if($?){ # if previous command succeeded
Write-Host "Succeed to install - $($Printer.Name) Printer" -ForegroundColor Black -BackgroundColor Gray
}
else {
Write-Warning "Failure to install - $($Printer.Name) Printer already exist"
}
}
else {
Write-Error "Failure to connect - $printerIPAddress"
}
}
Write-Host "Running...Please wait..."
# Install Printer A
Install-Printer -printerIPAddress "192.168.1.100" -sharedPrinter "\\SERVERNAME\A"
# Install Printer B
Install-Printer -printerIPAddress "192.168.1.101" -sharedPrinter "\\SERVERNAME\B"
Related
Can some one help me on the next code im trying to run..
it seem's to be ok for me but does not delete the Object when i execute-it
Import-Module ActiveDirectory
Clear-Host
$Computer = Read-Host "Type in the Host to Delete"
$rute = Get-ADComputer -Identity:"CN=$Computadora,OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com" -Server:"DCKABI02.kabi.ads.fresenius.com"
if($rute.Contains($Computer)){
Clear-Host
Remove-ADComputer -Identity=$Computadora,OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com" -Server:"DCKABI02.kabi.ads.fresenius.com" -Confirm:$false
#Clear-Host
Write-Host "The Computer Exist and it has been deleted" -ForegroundColor Green
Start-Sleep -Seconds 5
} else{
Clear-Host
Write-Host "The Host does not exist on AD" -ForegroundColor Red
Start-Sleep -Seconds 3
}
try to delete a Active directory object.. expected to work
Your code is not very clear and seems overengineered, $rute.Contains($Computer) will never ever be $true, you probably meant $rute.DistinguishedName.Contains($Computer) which could be $true but .Contains is case-sensitive so it could also be $false.
Your Read-Host statement is assigned to $Computer but then you're using $Computadora. Also, it's unclear why you are hardcoding OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com, I would assume you want to use this OU as your -SearchBase.
Here is how you can approach and will most likely work:
$param = #{
SearchBase = "OU=GDL,OU=ClientComputers,OU=ZAP,OU=MX,DC=kabi,DC=ads,DC=fresenius,DC=com"
LDAPFilter = "(name={0})" -f (Read-Host "Type in the Host to Delete")
Server = "DCKABI02.kabi.ads.fresenius.com"
}
$computer = Get-ADComputer #param
if($computer) {
Clear-Host
$computer | Remove-ADComputer -Server "DCKABI02.kabi.ads.fresenius.com" -Confirm:$false
Write-Host "The Computer Exist and it has been deleted" -ForegroundColor Green
Start-Sleep -Seconds 5
}
else {
Clear-Host
Write-Host "The Host does not exist on AD" -ForegroundColor Red
Start-Sleep -Seconds 3
}
I cannot get PowerShell to run this .txt file, what am I doing wrong? I tried changing the name of the .txt and checked passed scripts and everything seems to be the same but I keep getting an error saying that the ".txt in invalid"
$POSName = "$PSScriptRoot\Bex.txt"
foreach ($POS in (Get-Content $POSName)) {
$Bex = Get-Service -ComputerName $POSName | Where-Object { $_.name -eq "BexServ" }
}
If ($Bex -eq $null) {
# Service does not exist
Write-Host " doesn't exist." -ForegroundColor Red
}
Else {
# Service does exist
Write-Host "The $($Bex.Name) service found." -ForegroundColor Green
If ($Bex.Status -eq "Running") {
# Stop Service
Set-Service -status stopped -ComputerName $POSName -name $Box.Name -ErrorAction Stop
Write-Host "The $($Bex.Name) successfully stopped." -ForegroundColor Green
}
else {
#service already stopped
If ($Bex.Status -eq "Stopped") {
Write-Host "The $($Bex.Name) service already Stopped." -ForegroundColor Green
}
}
}
As commented, you are using the wrong variable in the loop. The code is reading the text file just fine, it is Get-Service that cannot deal with a path to a file in the -ComputerName parameter.
Also, the placing of the if..else should be inside the loop, not after.
Try
$POSName = "$PSScriptRoot\Bex.txt"
foreach ($POS in (Get-Content $POSName)) {
$Bex = Get-Service -ComputerName $POS | Where-Object { $_.name -eq "BexServ" }
If (!$Bex) {
# Service does not exist
Write-Host " doesn't exist." -ForegroundColor Red
}
Else {
# Service does exist
Write-Host "The $($Bex.Name) service found." -ForegroundColor Green
If ($Bex.Status -eq "Running") {
# Stop Service
Set-Service -status stopped -ComputerName $POSName -name $Box.Name -ErrorAction Stop
Write-Host "The $($Bex.Name) successfully stopped." -ForegroundColor Green
}
else {
#service already stopped
If ($Bex.Status -eq "Stopped") {
Write-Host "The $($Bex.Name) service already Stopped." -ForegroundColor Green
}
}
}
}
It might also be a good idea to output the computername ($POS) in the Write-Host lines too
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.
I'm writing a PowerShell 2.0 script to monitor and reconnect network drives that should be mapped. It works...mostly. Once a drive is determined to be disconnected my logon script (ptt.vbs) is run and the drives are remapped. However, after that it continues to see that particular drive letter as disconnected even though it got remapped.
while($true) {
$disconnectedDrives = #()
$mappedDrives = 'J:', 'R:', 'S:', 'W:'
foreach ($drive in $mappedDrives) {
if (-Not (Test-Path $drive)) {
$disconnectedDrives += $drive
}
}
if ($disconnectedDrives) {
Write-Host "$disconnectedDrives not mapped."
Write-Eventlog -LogName 'Windows PowerShell' -Category 3 -source PowerShell -eventID 601 -EntryType Error -message "$disconnectedDrives OFFLINE and not available."
\\dc1\NETLOGON\ptt.vbs
}
Start-Sleep 1
}
Any ideas what I'm doing wrong?
To me the mix of VBS and Powershell is suspicious.
But at least a would take a differnt way. First create a central file whch includes the network drive configuration. For example "\dc1\NETLOGON\ptt.csv" can look like this ...
J;\\srv1\shareA
R;\\srv1\shareB
S;\\srv2\shareA
W;\\srv2\shareB
This is the script ...
$Local:LogicalDiskStatus = New-Object -TypeName 'System.Collections.Generic.Dictionary[string,System.Management.ManagementObject]'
$Local:NetDrvConf_Path = "\\dc1\NETLOGON\ptt.csv"
$Local:NetDrvConf_List = #()
$Local:NetDrvConf_DrvType = [UInt32]4
$Local:WshNetworkObj = New-Object -ComObject WScript.Network
while($true) {
# adding the logical disk status to a list indexed by DeviceID
$LogicalDiskStatus.Clear()
Get-WmiObject -Class "Win32_LogicalDisk" | ForEach-Object { $LogicalDiskStatus.Add((($_.DeviceID) -replace ":"), $_) }
if (!($NetDrvConf_List.Count)) {
Try {
$NetDrvConf_List.Clear()
$NetDrvConf_List = Import-Csv -Path $NetDrvConf_Path -Delimiter ";"
}
Catch [System.Exception] {
$Local:ErrorMsg = ("Cannot load network drive configuration file `"{0}`". Error message: {1}" -f $NetDrvConf_Path, ($_.Exception.Message))
Write-Host $ErrorMsg -ForegroundColor red
Write-Eventlog -LogName "Windows PowerShell" -Category 3 -Source PowerShell -EventId 601 -EntryType Error -Message $ErrorMsg
}
}
$NetDrvConf_List | ForEach-Object {
$Local:Current_DriveLetter = ($_.Drive).ToUpper()
$Local:Current_DriveID = ("{0}:" -f $Current_DriveLetter)
$Local:Current_UNCPath = $_.UNCPath
Write-Host ("Check configuration: {0} {1}" -f $Current_DriveID, $Current_UNCPath)
# drive in use?
if ( ($LogicalDiskStatus.ContainsKey($Current_DriveLetter)) ) {
# drive is a network drive?
if (!(($LogicalDiskStatus.$Current_DriveLetter.DriveType).Equals($NetDrvConf_DrvType))) {
$Local:ErrorMsg = ("Drive `"{0}`" is already in use, but not as a network drive! The current drive type is `"{1}`" not `"4`"." -f $Current_DriveID, ($LogicalDiskStatus.$Current_DriveLetter.DriveType) )
Write-Host $ErrorMsg -ForegroundColor red
Write-Eventlog -LogName "Windows PowerShell" -Category 3 -Source PowerShell -EventId 602 -EntryType Error -Message $ErrorMsg
# drive is NOT to the expected UNC path?
} elseif (!(($LogicalDiskStatus.$Current_DriveLetter.ProviderName).Equals($Current_UNCPath))) {
Try {
Write-Host ("Network drive `"{0}`" unexpectedly connected to `"{1}`". Trying to disconnect." -f $Current_DriveID, ($LogicalDiskStatus.$Current_DriveLetter.ProviderName)) -ForegroundColor yellow
$WshNetworkObj.RemoveNetworkDrive($Current_DriveID, $true, $true)
Write-Host ("=> successfully disconnected.") -ForegroundColor green
}
Catch [System.Exception] {
$Local:ErrorMsg = ("Error disconnecting `"{0}`". Connected to `"{1}`". Error message: {2}" -f $Current_DriveID, $Current_UNCPath, ($_.Exception.InnerException) )
Write-Host $ErrorMsg -ForegroundColor red
Write-Eventlog -LogName "Windows PowerShell" -Category 3 -Source PowerShell -EventId 603 -EntryType Error -Message $ErrorMsg
}
} else {
Write-Host "=> correct connected" -ForegroundColor green
}
}
# drive is unused?
if (!(((Get-PSProvider -PSProvider FileSystem).Drives.Name).Contains($Current_DriveLetter))) {
Try {
Write-Host ("Connecting network drive `"{0}`" to `"{1}`"." -f $Current_DriveID, $Current_UNCPath) -ForegroundColor yellow
$WshNetworkObj.MapNetworkDrive($Current_DriveID, $Current_UNCPath, $true)
Write-Host ("=> successfully connected.") -ForegroundColor green
}
Catch [System.Exception] {
$Local:ErrorMsg = ("Error connecting `"{0}`" to `"{1}`". Error message: {2}" -f $Current_UNCPath, $Current_DriveID, ($_.Exception.InnerException) )
Write-Host $ErrorMsg -ForegroundColor red
Write-Eventlog -LogName "Windows PowerShell" -Category 3 -Source PowerShell -EventId 604 -EntryType Error -Message $ErrorMsg
}
}
}
Start-Sleep -Seconds 1
}
first time using powershell and I can't seem to get the below to work - nothing is displayed - I think the script work but I assume I need something to show the results? Any help please:
$hotfix1 = Get-HotFix -Id KB981872
If($hotfix)
{
$Output = "Hotfix is installed you may proceed"
}
else
{
$Output = "Hotfix is not installed"
}
$hotfix1 = Get-HotFix -Id KB981872
Thanks Shay - I have updated it as:
write-host "This will check if Hotfix KB979808 is installed on this Server." -ForegroundColor
Black -BackgroundColor Cyan
write-host "This is required for Windows Server 2008 R2 DFSR Pre-Seeding Robocopying" -
ForegroundColor Black -BackgroundColor Cyan
Write-Host ""
$hotfix1 = Get-HotFix -Id KB979808 -ErrorAction SilentlyContinue
If($hotfix1 -match "KB979808")
{
Write-Host "Hotfix is installed you may proceed" -foregroundcolor "green"
Write-Host ""
}
else
{
Write-Host "Hotfix is NOT installed - Please ensure you install this hotfix BEFORE"
Write-host "copying any data" -foregroundcolor "red"
Write-Host ""
}
The code doesn't output anything because you assign it to a variable. Remove the assignment. You are also assigning the command output to $hotfix1 but checking against $hotfix in the if statement. In addition, if the hot-fix cannot be found you'll get an error, so add the -ErrorAction parameter to suppress the error:
$hotfix1 = Get-HotFix -Id KB981872 -ErrorAction SilentlyContinue
If($hotfix1)
{
"Hotfix is installed you may proceed"
}
else
{
"Hotfix is not installed"
}
$hotfix1