I want multiple data fetching from excel sheet. I am getting error is Index was outside the bounds of the array.
$Data = Read-Host "Enter the count of Datastore"
$ds = "-sm-"
$Range1 = $Worksheetx1.Range("B1","B1048570")
$Search1 = $Range1.find($ds)
$r = $Search1.row
for ($i=1; $i -le $Data; $i++)
{
$Datastore = #()
$Datastore[$i] = $Worksheetx1.Cells.Item($r, 2).Value2
$r = $r+1
}
$Total_Datastore = $Datastore1 + $Datastore2 + $Datastore3 + $Datastore4
$Total_Datastore
The problem resides in this code:
for ($i=1; $i -le $Data; $i++)
{
$Datastore = #()
$Datastore[$i] = $Worksheetx1.Cells.Item($r, 2).Value2
$r = $r+1
}
You're creating an empty array $Datastore = #(), and try to store data in the second index ($i=1, array index starts at zero, therefore index two). This causes an IndexOutOfRangeException.
Also $Total_Datastore = $Datastore1 + $Datastore2 + $Datastore3 + $Datastore4 doesn't make sense, since $Datastore1 (2,3 and 4) aren't defined anywhere.
Try:
# Only integers are allowed
$Data = [int] (Read-Host "Enter the count of Datastore")
$ds = "-sm-"
$Range1 = $Worksheetx1.Range("B1","B1048570")
$Search1 = $Range1.find($ds)
$r = $Search1.row
$Datastore = #()
for ($i=1; $i -le $Data; $i++) {
# Todo: Check if $r is in a valid range or not !!!
$Datastore += $Worksheetx1.Cells.Item($r, 2).Value2
$r = $r+1
}
$Datastore
Related
My code builds two PSCustomObjects. Both objects can be $null, either Object can be $null. I test for that like this
$ADResult = #()
if ([string]::IsNullOrWhiteSpace($ADGroups)) {
Write-Warning "No AD Groups"
$ADResult = [PSCustomObject]#{
ADGroups = ""
ADGroupsdistinguishedName = ""
}
}
Else {
foreach ($group in $ADGroups) { do stuff }
The problem is when both objects are $null. When I put the objects together for a report. I get the error "Cannot index into a null array."
[int]$max = $ADResult.count
if ([int]$GResult.count -gt $max) { [int]$max = $GResult.count }
$Result = #()
for ( $i = 0; $i -lt $max; $i++) {
$Result += [PSCustomObject]#{
PrimaryEmail = $email
Title = $UserInfo.title
Department = $UserInfo.Department
Manager = $Manager
EmailBackup = $ENV:Backup
AccountDisabled = $ENV:ADDisabled
GoogleRemoved = $ENV:RemoveGoogle
ADGroupName = $ADResult.ADGroups[$i]
ADGroupNameDistinguishedName = $ADResult.ADGroupsdistinguishedName[$i]
GoogleGroup = $GResult.GoogleGroups[$i]
Role = $GResult.role[$i]
DateOfSeparation = (Get-Date).ToString("yyyy_MM_dd")
UnixID = $unix
UserDistinguishedName = $UserInfo.distinguishedName
UserOU = $UserInfo.Ou
PrimaryGroup = $UserInfo.primaryGroup.Split('=').Split(',')[1]
}
}
How can I overcome this better?
I want the other information like ou and related if both objects are $null
Change the value of the properties in your "empty" placeholder object from an empty string to a empty array:
$ADResult = [PSCustomObject]#{
ADGroups = #()
ADGroupsdistinguishedName = #()
}
I am trying to add a new key(1) to a hashtable, but powershell throws the error as "Key in dictionary: '1' Key being added:'1' error", same issue comes when I add 2 as a key but no issues with key '3' in a hashtable.
Here is my code to which does adding key to a hashtable.
$esxarray = #('10.91.91.XX8', '10.91.91.XX9')
foreach ($i in $esxarray) {
Connect-VIServer -Server $i
}
$podnumbers = #(1, 3)
$podInfo = $null
$PodHASHTABLE = #{}
$buffer = 0
foreach ($pd in $podnumbers) {
$podinfo = #()
for ($i = 0; $i -lt $pd; $i = $i + 1) {
$pod = Read-Host -Prompt "Assign the pod numbers for", $esxarray[$buffer]
Write-Output `n
$podinfo += $pod
}
$podSet = #{ $pd = #($podinfo) }
$podInfObj = New-Object psobject –Property $podSet
$PodHASHTABLE += $podSet
$buffer = $buffer + 1
}
Here is the error I got after executing the script.
Item has already been added. Key in dictionary: '1' Key being added: '1'
+ $PodHASHTABLE += $podSet
Suggestions?
Can you please help me converting the below C# to PowerShell
byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + saltBytes.Length];
Below is the full code what I am trying to do here.
I am trying to generate a hash code here
Function CalculateHashWithSalt($input = "Password#123", $salt="qLTf99m__JGu", $algorithmName = "SHA512")
{
$pass = [System.Text.Encoding]::UTF8
$input = "Password123"
$data1 = $pass.GetBytes($input)
$saltbytes = [System.Text.Encoding]::UTF8
$saltbytes=$saltbytes.GetBytes($salt)
$plainTextWithSaltBytes=#()
$plainTextWithSaltBytes = $data1.Length + $saltbytes.Length
for ($i = 0; $i -lt $data1.Length; $i++)
{
$plainTextWithSaltBytes[$i] = $data1[$i]
}
for ($i = 0; $i -lt $saltbytes.Length; $i++)
{
$plainTextWithSaltBytes[$pass.Length + $i] = $saltbytes[$i];
}
[System.Byte[]]::new($hashBytes)
$hashBytes = $algorithmName.ComputeHash($plainTextWithSaltBytes);
$Encrypted = [System.Convert]::FromBase64String($hashBytes)
}
Trying to convert the below c# code :
C# code link
From https://blogs.msdn.microsoft.com/luc/2011/01/21/powershell-getting-the-hash-value-for-a-string/
I have this function in my personal scripts with a parameter for which algo to use.
function Hash($textToHash)
{
$hasher = new-object System.Security.Cryptography.SHA256Managed
$toHash = [System.Text.Encoding]::UTF8.GetBytes($textToHash)
$hashByteArray = $hasher.ComputeHash($toHash)
foreach($byte in $hashByteArray)
{
$res += $byte.ToString()
}
return $res;
}
I have a PowerShell script to pull data from a database, but some of the fields contain commas and that is resulting in breaking up the fields because the StreamReader splits it up into fields by comma. How can I change the delimiter of how the data is split into it's fields?
$ConnectionString = "Data Source=server1; Database=Development; Trusted_Connection=True;";
$streamWriter = New-Object System.IO.StreamWriter ".\output.csv"
$sqlConn = New-Object System.Data.SqlClient.SqlConnection $ConnectionString
$sqlCmd = New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.Connection = $sqlConn
$sqlCmd.CommandText = "SELECT * FROM Development.dbo.All_Opportunities WITH(NOLOCK)"
$sqlConn.Open();
$reader = $sqlCmd.ExecuteReader();
# Initialze the array the hold the values
$array = #()
for ( $i = 0 ; $i -lt $reader.FieldCount; $i++ )
{ $array += #($i) }
# Write Header
$streamWriter.Write($reader.GetName(0))
for ( $i = 1; $i -lt $reader.FieldCount; $i ++)
{ $streamWriter.Write($("," + $reader.GetName($i))) }
$streamWriter.WriteLine("") # Close the header line
while ($reader.Read())
{
# get the values;
$fieldCount = $reader.GetValues($array);
# add quotes if the values have a comma or double quote
for ($i = 0; $i -lt $array.Length; $i++)
{
if ($array[$i] -match "`"|\S")
{
$array[$i] = '"' + $array[$i].Replace("`"", "`"`"").ToString() + '"';
}
}
$newRow = [string]::Join(",", $array);
$streamWriter.WriteLine($newRow)
}
$reader.Close();
$sqlConn.Close();
$streamWriter.Close();
Have you read this post to see if it helps your effort. It's for a text fiel, but could open you creativity to what is possible.
'stackoverflow.com/questions/14954437/streamreader-with-tab-delimited-text-file'
FYI, there is no delimiter type called 'field'
Otherwise, for those columns that have a comma as part of the value, a common approach is either to double quote the value or escape it.
I have a CheckedListBox in Powershell. When i select some checkbox the text result is empty.
When i select a second checkbox the first checkbox result text is displayed.
I use the following code for the CheckedListBox:
# Code
$ListView = New-Object System.Windows.Forms.CheckedListBox
$ListView.Location = New-Object System.Drawing.Size(10,40)
$ListView.Size = New-Object System.Drawing.Size(533,325)
$ListView.CheckOnClick = $True
$ListView.Add_ItemCheck({
for ($i = 0; $i - ($ListView.Items.Count-1); $i++)
{
if ($ListView.GetItemChecked($i))
{
$s = $s + $ListView.Items[$i].ToString();
}
}
Write-host $s
})
GetItemChecked($i) will only return the correct result for the item check that raised the event after the event handler has run.
You can inspect the event arguments for the new value of the item:
$ListView.Add_ItemCheck({
param($sender,$e)
$s = ""
for ($i = 0; $i -le ($ListView.Items.Count-1); $i++)
{
# Check if $i is the index of the item we just (un)checked
if($e.Index -eq $i)
{
# Inspect the new checked-state value
if($e.NewValue -eq 'Checked')
{
$s += $ListView.Items[$i]
}
}
elseif ($ListView.GetItemChecked($i))
{
# Item is already checked
$s += $ListView.Items[$i]
}
}
Write-host $s
})