In Powershell it is posible to increase a Variable when a Error ocours.
Per Exemple when I run this command twice the command fails (because the directory already exists) and the Error Variable now icrease to 1.
New-Item C:\TEMP\blabla -type directory -EA continue -EV +err
write-host $err.count
#Output: 1
But now to my Question:
I'd like to increase the $err variable manually but that does not work.
I tried the following:
switch ($LASTEXITCODE) {
0 {
Write-Host "Success" -ForegroundColor Green
break
}
2 {
$err.count++
break
}
default {
$err.count++
break
}
Error:
At C:\windows\mscripts\100_create_website_servicelayer.ps1:33 char:9
+ $err. <<<< count++
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyAssignmentException
$err has a count property just because is of type array.
You can try to add some string to $err in each case:
2 {
$err += "Error"
break
}
default {
$err += "Error"
break
}
Related
I have a PS Script that checks the DNS for our domain server.
The Powershell script runs every 15 minutes and usually is successful. However, occasional it fails at random with the error below but there is nothing consistent about it when it fails.
Exception calling "Open" with "0" argument(s): "A connection was successfully established with the server, but then an
error occurred during the login process. (provider: SSL Provider, error: 0 - An existing connection was forcibly closed
by the remote host.)"
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
If I can't find the cause, I was wondering if there is a way to check for this error and automatically re-run the script?
Thanks in advance.
UPDATE: Code Below
Try
{
# Query DNS server, loop through each domain
Invoke-Command -ComputerName $dc -ScriptBlock `
{
Param($domains, $dnsserver)
$ConnectionString = 'Data Source=MYDB; Initial Catalog=MYCAT; Integrated Security=SECURE'
$Conn = New-Object System.Data.SqlClient.SqlConnection($ConnectionString)
$Conn.Open()
Foreach ($domain in $domains)
{
# Query specific record types
$results = (Resolve-DnsName $domain -Server $dnsserver -Type NS)
$results | Foreach-Object `
{
$name = $_.name
$type = $_.type
$value = $_.NameHost
$Sql = "INSERT INTO B5_DNSCheck([DOMAIN], [TYPE], [VALUE]) VALUES('$domain','$type','$value')"
$Cmd = $Conn.CreateCommand()
$Cmd.CommandText = $Sql
$Cmd.ExecuteNonQuery() | Out-Null
}
$results = (Resolve-DnsName $domain -Server $dnsserver -Type MX)
$results | Foreach-Object `
{
$name = $_.name
$type = $_.type
$value = $_.NameExchange
$Sql = "INSERT INTO B5_DNSCheck([DOMAIN], [TYPE], [VALUE]) VALUES('$domain','$type','$value')"
$Cmd = $Conn.CreateCommand()
$Cmd.CommandText = $Sql
$Cmd.ExecuteNonQuery() | Out-Null
}
}
} -ArgumentList $domains, $dnsserver
Write-Output "Completed DNS check"
}
catch
{
Write-Output "Error with Connection"
Stop-Transcript
Exit 2
}
}
Else
{
Write-Output "Error: Unable to conect to $dnsserver to check DNS at this time"
Stop-Transcript
Exit 2
}
# All done
Stop-Transcript
The answer was #TheMadTechnicians advice.
Adding in $ErrorActionPreference='Stop' and a try/catch worked perfect.
This is my first time using Powershell so please forgive my ignorance.
I have a SQL query that returns back a bunch of order numbers. I want to check another file to see if there is an existing PDF in that file with the same name as the orders numbers returned by the SQL query.
Everything in my code works up until the ForEach loop which returns nothing. Based on my google searches I think I'm pretty close but I'm not sure what I'm doing wrong. Any help would be appreciated.
I've removed the actual file name for obvious reasons, and I do know that the file is correct and other commands do access it so I know that is not my problem at the moment. I've also removed sensitive info from the SQL query.
$statement = "SELECT A, Date FROM XXXX
WHERE STAT = 1 AND Date >= trunc(sysdate)"
$con = New-Object System.Data.OracleClient.OracleConnection($connection_string)
$con.Open()
$cmd = $con.CreateCommand()
$cmd.CommandText = $statement
$result = $cmd.ExecuteReader()
$list = while ($result.Read()) { $result["A"]}
Write-Output $list​
#########Loop through the list above here to check for matching PDF
ForEach ($Order in $list){
Get-ChildItem "\\xxxxxx\" -Filter $Order -File
#########If FALSE - notify that PDF is missing
}
$con.close()
I have also tried the following code, which gets me closer and actually finds the files I'm looking for, but gives the error
" Get-ChildItem : A positional parameter cannot be found that accepts argument
CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand"
ForEach ($Order in $list){
if((Get-ChildItem "\\xxxxx\" + $Order)){
Write-Output
} else { Write-Host "Does not exist."}
I gather from your comment that $list is an array of order numbers.
Next, you want to check if there is a file in a folder having that name, correct?
Then I'd suggest you use Test-Path instead of Get-ChildItem:
$folderToSearch = '\\servername\sharename\folder'
foreach ($Order in $list) {
$fileToCheck = Join-Path -Path $folderToSearch -ChildPath ('{0}.pdf' -f $Order)
if (Test-Path -Path $fileToCheck -PathType Leaf) {
"File found: $fileToCheck"
}
else {
"File $fileToCheck does not exist"
}
}
I'm trying to create a small script, that can easily display some valid information to the standard user in regards of getting IT assistance from ServiceDesk.
Current output
So to improve this i was trying to figure out if i could add spaces to the teamviewer result.
This is an example of the current team viewer ID outcome:
1483547869
But i would like if the outcome could be:
1 483 547 869
This is a small thing but it will make it a lot easier to read for the standard user.
This is my code:
Add-Type -AssemblyName System.Windows.Forms
$ip=get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1}
$ipaddress = $ip.ipaddress[0]
$hostname = [System.Net.Dns]::GetHostName()
$TeamViewerVersions = #('10','11','12','13','14','')
If([IntPtr]::Size -eq 4) {
$RegPath='HKLM:\SOFTWARE\TeamViewer'
} else {
$RegPath='HKLM:\SOFTWARE\Wow6432Node\TeamViewer'
}
$ErrorActionPreference= 'silentlycontinue'
foreach ($TeamViewerVersion in $TeamViewerVersions) {
If ((Get-Item -Path $RegPath$TeamViewerVersion).GetValue('ClientID') -ne $null) {
$TeamViewerID=(Get-Item -Path $RegPath$TeamViewerVersion).GetValue('ClientID')
}
}
$msgBoxInput = [System.Windows.Forms.MessageBox]::Show("Computer Name: $hostname`nIP Address: $ipaddress`nTeamViewer ID: $TeamviewerID`n`nWould you like to open Self Service Portal?", 'Quick Support','YesNo','Information')
If ($msgBoxInput -eq 'Yes' ){
start https://www.google.com/
Else
}
Stop-Process -Id $PID
Here's a really simple solution to format a number:
$TeamViewerDisplayID = $TeamViewerID.toString("### ### ### ###")
This will display 1483547869 as 1 483 547 869. Note: if your number will have 9 characters for example, the above line of code will add a space to the beginning. Example: "483547869" becomes "_483 547 869". So if you want, you can add another if statement there that checks how long the number is and formats it accordingly:
if ($TeamViewerID.length -gt 9) {
$TeamViewerID.toString("### ### ### ###")
} else {
$TeamViewerID.toString("### ### ###")
}
I am trying to create vmkernels for existing ESXi hosts in vCenter using PowerCLI.
$esxiHosts = #("esxi21.v.lab", "esxi22.v.lab", "esxi23.v.lab", "esxi24.v.lab", "esxi25.v.lab")
$vmhosts = Get-VMHost -Name $esxiHosts
foreach ($i in 31..35)
{
$ipa = "192.168.2.$i"
write-host $vmhosts
$esxiHosts | foreach-object {New-VMHostNetworkAdapter $_ -PortGroup ManagementNetwork2 -IP $ipa -subnetmask 255.255.255.0 -VirtualSwitch vSwitch0 -ManagementTrafficEnabled $true}
}
It creates vmkernels for each host, however assigns all of them the same IP address, and then shows the following error as well.
New-VMHostNetworkAdapter : 26 Sep 2019 4:21:17 PM New-VMHostNetworkAdapter An error occurred during host configuration. Operation failed, diagnostics report: A vmkernel
nic for the connection point already exists:
At line:5 char:30
+ ... ach-object {New-VMHostNetworkAdapter $_ -PortGroup ManagementNetwork2 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-VMHostNetworkAdapter], PlatformConfigFault
+ FullyQualifiedErrorId : Client20_VmHostServiceImpl_NewVMHostNetworkAdapter_ViError,VMware.VimAutomation.ViCore.Cmdlets.Commands.Host.NewVMHostNetworkAdapter
My understanding is this is due to the foreach-object running inside the loop, but if I don't do that I cannot iterate the IP addresses using the just the for each loop, or can I ?
One way to go about correcting this issue might be to use a counter variable, since your 4th octet is sequential. Something like the following:
$esxiHosts = #("esxi21.v.lab", "esxi22.v.lab", "esxi23.v.lab", "esxi24.v.lab", "esxi25.v.lab")
$vmhosts = Get-VMHost -Name $esxiHosts
$i = 31
foreach ($vmh in $vmhosts) {
$ipa = "192.168.2.$i"
Write-Host $vmh
New-VMHostNetworkAdapter -VMHost $vmh -PortGroup ManagementNetwork2 -IP $ipa -subnetmask 255.255.255.0 -VirtualSwitch vSwitch0 -ManagementTrafficEnabled $true
$i++
}
I have the script below and for the life of me can not get why it is giving me "You cannot call a method on a null-valued expression." It errors on two spots.
Which computer?: NFDW2206
What is the AssetID?: 00000007
Checking NFDW2206 to see if the Registry Key exists..
You cannot call a method on a null-valued expression.
At \\NFDNT007\Dept\Corporate\IT\Network Services\Documentation\Asset Tag.ps1:11 char:33
+ $regassetid = $regKey.GetValue <<<< ("AssetID")
+ CategoryInfo : InvalidOperation: (GetValue:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The Key does not exist. Writing AssetID.....
You cannot call a method on a null-valued expression.
At \\NFDNT007\Dept\Corporate\IT\Network Services\Documentation\Asset Tag.ps1:18 char:20
+ $regKey.Setvalue <<<< ('AssetID', $AssetID, 'String')
+ CategoryInfo : InvalidOperation: (Setvalue:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The code is below
$Computer = Read-Host "Which computer?"
$AssetID = Read-Host "What is the AssetID?"
if (($Computer -eq "") -or ($AssetID -eq "")) {
Write-Host "Error: A blank parameter was detected" -BackgroundColor Black -ForegroundColor Yellow
} else {
if (Test-Connection -comp $Computer -count 1 -quiet) {
Write-Host "Checking $Computer to see if the Registry Key exists.."
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $Computer)
$regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield")
$regassetid = $regKey.GetValue("AssetID")
if ($regassetid -eq $null) {
Write-Host "The Key does not exist. Writing AssetID....."
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $Computer)
$regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield",$True) ## $True = Write
$regKey.Setvalue('AssetID', $AssetID, 'String')
} else {
$OverWrite = Read-Host "AssetID exists do you wish to continue?"
if (($OverWrite -eq "y") -or ($OverWrite -eq "yes")) {
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $Computer)
$regKey = $reg.OpenSubKey("SOFTWARE\Multek Northfield",$True) ## $True = Write
$regKey.Setvalue("AssetID", $AssetID, "String")
}
}
} else {
Write-Host "Error: $computer is offline..." -BackgroundColor Black -ForegroundColor Yellow
}
}
The docs say that OpenSubKey will return null if the operation fails. It is likely it can't find the key. Is the remote system a 64-bit OS? If so, it could be you're running into a registry virtualization issue. Might need to look under SOFTWARE\WOW6432Node\Multek Northfield