Troubleshooting if in powershell - powershell

I am in a very strange powershell behavior.
I have an If, elseif, else.
The If works, The else if works, but the else never happened.
What could it be?
This is the script:
$result = Get-AMTHardwareAsset $Computer -credential $VProCredential -textoutput
if ($result.Contains("Unauthorized") -eq $true)
{
Add-Results "$Computer`tHardwareAssets-Unauthorized"
}
elseif ($result.Contains("Could not connect") -eq $true)
{
Add-Results "$Computer`tHardwareAssets-CannotConect"
}
else
{
Add-Results "TESTING"
}

Changing the script to hardcode $result to "Fubar", and substituting Write-Host for Add-Results:
$result = 'Fubar'; #Get-AMTHardwareAsset $Computer -credential $VProCredential -textoutput
if ($result.Contains("Unauthorized") -eq $true)
{
#Add-Results "$Computer`tHardwareAssets-Unauthorized"
Write-Host "$Computer`tHardwareAssets-Unauthorized"
}
elseif ($result.Contains("Could not connect") -eq $true)
{
#Add-Results "$Computer`tHardwareAssets-CannotConect"
Write-Host "$Computer`tHardwareAssets-CannotConect"
}
else
{
#Add-Results "TESTING"
Write-Host "TESTING"
}
and I get "TESTNG".
Some context you have not included applies, without it the only answer you will get is: it looks OK

Related

Value is False and the condition is -eq $true in if statement and it pass

I'm newbie with powershell. I am always learning about, and I started last Friday. So forgive me if it's obvious!
I don't why the first if statement pass whereas the condition is not respected.
I'm trying to check if a program is running on my computer. If yes, it's telling me "Programme is running" ! And when it's not running anymore, it write that is not running.
There is my code :
if (isPrgmRunning -eq $true) {
isPrgmRunning #Return false, why the last if statement pass ???
write-output "Programme is running"
$isRunning = $true
while($isRunning) {
write-output "While the programme keep running"
if(CheckInternetConnection) {
if(isPrgmRunning -eq $false) {
isPrgmRunning #Check again value, and it's false
Write-Output "If it's not running anymore"
$isRunning = $false
}
}
}
}
I don't understand why it's not running and the first if pass...
There is all the scrpit :
$global:previousStatus=$null
# Function to check if the computer is connected to the internet
Function CheckInternetConnection {
$currentStatus = Test-Connection -ComputerName "www.google.com" -Count 1 -Quiet
If ($currentStatus -ne $global:previousStatus) {
If ($currentStatus) {
ShowMessageBox "Connected"
}
Else {
ShowMessageBox "Disconnected"
}
$global:previousStatus = $currentStatus
}
return $currentStatus
}
# Function to display a message box
Function ShowMessageBox {
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
[System.Windows.Forms.MessageBox]::Show($args[0], "Internet Connection Status")
}
# Function to check if the "Minecraft" program is running can be replace by any other
Function isPrgmRunning {
try {
$process = Get-Process -Name "Minecraft" -ErrorAction Stop #This is an exemple of programme :)
if ($process -ne $null) {
write-output "Prgm run"
return $true
}
} catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
write-output "Prgm not run"
return $false
}
}
# Main function
function Main {
while($true){
if (CheckInternetConnection) {
write-output "Connected"
if (isPrgmRunning -eq $true) {
isPrgmRunning #Return false, why the last if statement pass ???
write-output "Programme is running"
$isRunning = $true
while($isRunning) {
write-output "While the programme keep running"
if(CheckInternetConnection) {
if(isPrgmRunning -eq $false) {
isPrgmRunning #Check again value, and it's false
Write-Output "If it's not running anymore"
$isRunning = $false
}
}
}
}
}
Start-Sleep -Seconds 1
}
}
Main
Thank you for any help on my script ! I'll hear all advice and solution that you can send me !
[Edit]: Problem solved. It was on isPrgmRunning. I don't know why but instead of this :
$process = Get-Process -Name "Minecraft" -ErrorAction Stop
I've take this on educba.com/powershell-boolean/ :
Get-Process | where{$_.Name -eq "Wrong process"} -ErrorAction Ignore
So we get this :
Function isPrgmRunning {
$process = Get-Process | where{$_.Name -eq "Minecraft"} -ErrorAction Ignore #Still with Minecraft but it can be "Teams" or something else
if($process){
return $true
}
else{
return $false
}
}
Evaluate the function, at the moment you're just checking if it exists, Try it this way:
$checkinternetconnection = $true
Function isPrgmRunning {
try {
$process = Get-Process -Name "Teams" -ErrorAction Stop #This is an exemple of programme :)
if ($process -ne $null) {
write-output "Prgm run"
return $true
}
} catch [Microsoft.PowerShell.Commands.ProcessCommandException] {
write-output "Prgm not run"
return $false
}
}
function Main {
while($true){
if ($CheckInternetConnection) {
write-output "Connected"
if (isPrgmRunning) {
isPrgmRunning #Return false, why the last if statement pass ???
write-output "Programme is running"
$isRunning = $true
while($isRunning) {
write-output "While the programme keep running"
if($CheckInternetConnection) {
if(!(isPrgmRunning)) {
isPrgmRunning #Check again value, and it's false
Write-Output "If it's not running anymore"
$isRunning = $false
}
}
}
}
}
Start-Sleep -Seconds 1
}
}
main

How I can pass multiple array in value in PowerShell function

Below function I want to pass multiple value in array. When I'm passing more than one value I am getting an error.
function CheckProcess([String[]]$sEnterComputerNameHere, [String[]]$sEnterProccessNameHere) {
#Write-Host " $sEnterComputerNameHere hello"
#($sEnterComputerNameHere) | ForEach-Object {
# Calling Aarray
#($sEnterProccessNameHere) | ForEach-Object {
if (Get-Process -ComputerName $sEnterComputerNameHere | where {$_.ProcessName -eq $sEnterProccessNameHere}) {
Write-Output "$_ is running"
} else {
Write-Output "$_ is not running"
}
}
}
}
$script:sEnterProccessNameHere = #("VPNUI") # Pass the process agreement here
$script:sEnterComputerNameHere = #("hostname") # Pass the process agreement here
CheckProcess $sEnterComputerNameHere $sEnterProccessNameHere
Give it a try with this one:
Function CheckProcess([String[]]$sEnterComputerNameHere,[String[]]$sEnterProccessNameHere)
{ #Write-host " $sEnterComputerNameHere"
#($sEnterComputerNameHere) | Foreach-Object {
$computer = $_
Write-Host $computer
#($sEnterProccessNameHere) | Foreach-Object {
$process = $_
Write-Host $process
try{
$x = get-process -computername $computer #Save all processes in a variable
If ($x.ProcessName -contains $process) #use contains instead of equals
{
Write-Output "$process is running"
}
else
{
Write-Output "$process is not running"
}
}
catch
{
Write-Host "Computer $computer not found" -ForegroundColor Yellow
}
}
}
}
$script:sEnterProccessNameHere = #("VPNUI","Notepad++","SMSS")
$script:sEnterComputerNameHere = #("remotecomputer1","remotecomputer2")
CheckProcess -sEnterComputerNameHere $sEnterComputerNameHere -sEnterProccessNameHere $sEnterProccessNameHere
In general, it would be great if you write the error you get in your question. That helps others to help you.
If I work with arrays and | Foreach, I always write the $_in a new variable. That helps if I have another | Foreach (like you had) to know for sure, with which object I'm working with..
EDIT: I changed the script, so it uses "-contains" instead of "-eq" and I added a try/catch block, so if the other computer is not found, it gives you a message.. It works on my network
EDIT2: Do you have access to the other computers? If you run get-process -computername "name of remote computer" do you get the processes?

Powershell NSlookup on DC's Forward and Reverse

$topDC1="10.254.90.17"
$topDC2="10.225.224.17"
$topDC3="10.110.33.32"
$topDC4="10.88.100.10"
$DomainName="office.adroot.company.net"
TRY{
$hostname = [System.Net.DNS]::GetHostByName($topDC1).HostName.toupper()
$ipaddress = [System.Net.Dns]::GetHostAddresses($DomainName) | select IPAddressToString -ExpandProperty IPAddressToString
# I want the below to loop foreach ip in the object, ns it against all 4 topDC's, then output each result :(
$NS1 = nslookup $ipaddress[0] $topDC1
Write-host $NS1
}
Catch{
write-host "error"
}
Here is my dirty code so far (just to keep it simple)
I am trying to automate this:
NSLOOKUP office.adroot.company.net
put the results into an object
for each ip in results, do an NSLOOKUP against our top level DC's.
find which DC's haven't been cleaned up after decommission (still in dns)
$DCList="10.254.90.17","10.225.224.17","10.110.33.32","10.88.100.10"
$DomainName="office.adroot.blorg.net","pcd.blorg.ca","blorg.ca","percom.adroot.blorg.net", "blorg.blorg.net","ibg.blorg.net","sacmcm.adroot.blorg.net","sysdev.adroot.blorg.net","adroot.blorg.net"
TRY{
foreach ($DomainNameItem in $DomainName){
Write-Host ""
Write-Host ""
Write-Host "Looking UP result"$DomainNameItem -foreground yellow
Write-Host ""
$hostname = [System.Net.DNS]::GetHostByName($DCListItem).HostName.toupper()
$ipaddress = [System.Net.Dns]::GetHostAddresses($DomainNameItem).IPAddressToString
foreach ($ip in $ipaddress){
Write-Host ""
Write-Host "Looking UP result"$ip -foreground green
foreach ($topdns in $DCList){
$RESULTS = nslookup $ip $topdns
Write-host $RESULTS
}
}
}
}
Catch{
write-host "error"
}
Write-Host ""
Write-Host ""
pause
Got it! This will save me tonnes of work determining if a DNS cleanup is necessary. Thanks guys, I'm learning just how great Powershell can be :)
Try this:
$topDomainControllers = #("10.254.90.17", "10.225.224.17", "10.110.33.32", "10.88.100.10")
$DomainName="office.adroot.company.net"
try {
$hostname = [System.Net.Dns]::GetHostByName($topDC1).HostName.ToUpper()
$ipAddresses = [System.Net.Dns]::GetHostAddresses($DomainName) |
select -ExpandProperty IPAddressToString
foreach ($ipAddress in $ipAddresses) {
$nslookupResult = nslookup $ipAddress
$foundIp = $nslookupResult[1] -match "^\D*(\d+\.\d+\.\d+\.\d+)$"
if ($foundIp -eq $false) {
continue
}
$domainController = $Matches[1]
if ($topDomainControllers.Contains($domainController)) {
Write-Output -Verbose "Found domain controller match for $domainController"
break
} else {
Write-Output -Verbose "No match found for domain controller $domainController"
}
}
} catch {
Write-Output "An error has occured: $_"
}

Using RunAs in PowerShell

I have the following PowerShell script to run a quick HitmanPro scan on computers. I have deployed this script through GFI RMM and while it works, I need to pass it domain administrator information.
$HitmanParameters = "/scanonly /quick /noinstall /quiet"
$AgentPath = (${env:ProgramFiles(x86)}, ${env:ProgramFiles} -ne $null)[0]
if (Test-Path "$AgentPath\Advanced Monitoring Agent") {
$AgentPath="$AgentPath\Advanced Monitoring Agent"
} elseif (Test-Path "$AgentPath\Advanced Monitoring Agent GP") {
$AgentPath="$AgentPath\Advanced Monitoring Agent GP"
} else {
Write-Host "Agent Path Not Found"
}
if (-not (Test-Path "$AgentPath\HitmanPro")) {
Write-Host "Creating Hitman Folder"
[system.io.directory]::CreateDirectory("$AgentPath\HitmanPro")
}
$HitmanParameters = "$HitmanParameters /log=""$AgentPath\HitmanPro\results.txt"""
if (-not (Test-Path "$AgentPath\HitmanPro\HitmanPro.exe")) {
Write-Host "HitmanPro Not found"
if ($(Get-WmiObject -Query "SELECT * FROM Win32_Processor WHERE AddressWidth='64'")) {
$HMPURL = "http://dl.surfright.nl/HitmanPro_x64.exe"
} else {
$HMPURL = "http://dl.surfright.nl/HitmanPro.exe"
}
Write-Host "Downloading $HMPURL ..."
$webClient = New-Object System.Net.WebClient
$webClient.DownloadFile($HMPURL,"$AgentPath\HitmanPro\HitmanPro.exe")
if (Test-Path "$AgentPath\HitmanPro\HitmanPro.exe") {
Write-Host "Download Complete!"
} else {
Write-Host "Error Downloading Hitman Pro"
}
}
if (Test-Path "$AgentPath\HitmanPro\HitmanPro.exe") {
Write-Host "Running HitmanPro Scan..."
Write-Host "HitmanPro.exe $HitmanParameters"
Start-Process -FilePath "$AgentPath\HitmanPro\HitmanPro.exe" -ArgumentList "$HitmanParameters" -NoNewWindow -Wait
If (Test-Path "$AgentPath\HitmanPro\results.txt") {
$data = Get-Content -Encoding Unicode "$AgentPath\HitmanPro\results.txt"
remove-item "$AgentPath\HitmanPro\results.txt"
foreach ($line in $data) {
If($line.contains("Threats")) {
$Infections = [int] $line.Split(":")[1]
If($Infections -eq 0) {
Write-Host "No Infections Found"
$data
exit 0
break
} Else {
Write-Host "Infections Found!"
$data
exit 1000
break
}
} #If Line contains Threats
} #ForEach
} Else {
Write-Host "No Logfile Found"!
} #LogFile Found
} Else {
Write-Host "HitmanPro Still Not Found!"
}#HitmanPro Found

powershell Foreach-Object usage

I have script:
$servers = "server01", "s02", "s03"
foreach ($server in $servers) {
$server = (New-Object System.Net.NetworkInformation.Ping).send($servers)
if ($server.Status -eq "Success") {
Write-Host "$server is OK"
}
}
Error message:
An exception occured during a Ping request.
I need to ping each server in $servers array and display status. I think, that Foreach statement is not properly used, but I'm unable to find out where is the problem. Thank you for your advice
You should not be modifying the value of $server within the foreach loop. Declare a new variable (e.g. $result). Also, Ping.Send takes the individual server name, not an array of server names as an argument. The following code should work.
Finally, you will need to trap the PingException that will be thrown if the host is unreachable, or your script will print out a big red error along with the expected results.
$servers = "server1", "server2"
foreach ($server in $servers) {
& {
trap [System.Net.NetworkInformation.PingException] { continue; }
$result = (New-Object System.Net.NetworkInformation.Ping).send($server)
if ($result.Status -eq "Success") {
Write-Host "$server is OK"
}
else {
Write-Host "$server is NOT OK"
}
}
}