Array removed after function? - arrays

I am making a script that goes into all servers we're hosting and gets all members of a specific group and the domain name, and then exports it to a file. I'm saving the users and the domain names into two arrays AA (user array) and DA (domain array) AA stands for användararray, and "användare" is users in swedish so it makes sense to me.
I noticed that the export step didn't work, no users or domain names were exported, so I tried to print them in the function. But it doesn't print anything, so I tried to print it in a different location (didn't work). After some experimenting I came to the conlusion that the only place the arrays actually contains any information is inside the foreach loop where I save the users that I find??!
Here is the code
unction GetData([int]$p) {
Write-Host("B")
for ($row = 1; $row -le $UsernamesArray.Length; $row++)
{
if($CloudArray[$row] -eq 1)
{
.
$secstr = New-Object -TypeName System.Security.SecureString
$PasswordsArray[$row].ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $UsernamesArray[$row], $secstr
$output = Invoke-Command -computername $AddressArray[$row] -credential $cred -ScriptBlock {
Import-Module Activedirectory
foreach ($Anvandare in (Get-ADGroupMember fjärrskrivbordsanvändare))
{
$AA = #($Anvandare.Name)
$DA = gc env:UserDomain
#$DA + ";" + $Anvandare.Name
$DA + ";" + $AA
}
}
$output
}
}
$DA
$AA
}
function Export {
Write-Host("C")
$filsökväg = "C:\Users\322sien\Desktop\Coolkids.csv"
$ColForetag = "Företag"
$ColAnvandare = "Användare"
$Emptyline = "`n"
$delimiter = ";"
for ($p = 1; $p -le $DomainArray.Length; $p++) {
$ColForetag + $delimiter + $ColAnvandare | Out-File $filsökväg
$DA + $delimiter + $AA | Out-File $filsökväg -Append
}
}
ReadInfo
GetData
Export
Can anyone help me with this? I've sat down with this all day and i cant find a solution.

Your variables $DA and $AA are bound to GetData function, so they live only there. You could make them available inside your script by changing it's scope.
Change this:
$AA = #($Anvandare.Name)
$DA = gc env:UserDomain
To this:
$script:AA = #($Anvandare.Name)
$script:DA = gc env:UserDomain
So they will now be available for other functions inside the script.
Also I found the ways to improve your script, hope you can see the logic:
function GetData([int]$p) {
Write-Host("B")
for ($row = 1; $row -le $UsernamesArray.Length; $row++)
{
if($CloudArray[$row] -eq 1)
{
.
$secstr = New-Object -TypeName System.Security.SecureString
$PasswordsArray[$row].ToCharArray() | ForEach-Object {$secstr.AppendChar($_)}
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $UsernamesArray[$row], $secstr
[array]$output = Invoke-Command -computername $AddressArray[$row] -credential $cred -ScriptBlock {
Import-Module Activedirectory
$array = #()
foreach ($Anvandare in (Get-ADGroupMember fjärrskrivbordsanvändare))
{
$object = New-Object PSObject
$object | Add-Member -MemberType NoteProperty -Name AA -Value #($Anvandare.Name)
$object | Add-Member -MemberType NoteProperty -Name DA -Value (gc env:UserDomain)
$object | Add-Member -MemberType NoteProperty -Name Something -Value $DA + ";" + $AA
$array += $object
}
Write-Output $array
}
Write-Output $output
}
}
}
Your function will now output some data.

Related

Need Help Understanding Runspaces with WPF

I'm new to any sort of programming at all and I've been working on this tool, but I've finally hit a wall. I've read every article, post, and watched every video I could find but runspaces just aren't making sense to me. All I'm trying to do is get the auto search function to run on separate thread to keep the main window from locking up. I've been stuck on this for so long now that I considered ditching Powershell to start learning Python, but I'd rather understand this than quit. I think I even understand how to set the function to run on a separate runspace but the specific part that I don't understand is how to run the UI in it's own runspace and have the two communicate. I've even tried using some boilerplate with a syncHash table but I could never get it working. I'd really appreciate any help before I go insane.
All Files:
https://mega.nz/folder/251yHaBJ#bHYNYdNfAmia5mEhE5IOKQ
Powershell script in question:
#Xaml import
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$xamlFile = "MainWindow.xaml"
$inputXAML = Get-Content -Path $xamlFile -Raw
$inputXAML = $inputXAML -replace 'mc:Ignorable="d"','' -replace "x:N","N" -replace '^<Win.*','<Window'
[XML]$XAML = $inputXAML
$reader = New-Object System.Xml.XmlNodeReader $XAML
try {
$psform = [Windows.Markup.XamlReader]::Load($reader)
}
catch {
Write-Host $_.Exception
throw
}
$xaml.SelectNodes("//*[#Name]") | ForEach-Object {
try {
Set-Variable -Name "var_$($_.Name)" -Value $psform.FindName($_.Name) -ErrorAction Stop
}
catch {
throw
}
}
#Functions
function autoSearch {
$Drives = Get-PSDrive -PSProvider "FileSystem"
$a1 = foreach ($Drive in $Drives) {Get-ChildItem -Path $Drive.Root -Recurse -ErrorAction SilentlyContinue -Directory -Filter "Steam"}
$a2 = Get-ChildItem (Join-Path $a1.FullName "userdata") -ErrorAction SilentlyContinue -Directory
$a3 = Get-ChildItem (Join-Path $a2.FullName "*") -ErrorAction SilentlyContinue -Directory -Filter "1446780"
if ($a3) {
$var_saveR.Foreground = "Green"
$var_saveR.Content = "Found"
$timer = New-Object System.Windows.Forms.Timer -Property #{
Enabled = $true
Interval = 3000
}
$timer.add_Tick({$var_saveR.Content = ""})
$var_loc1.Content = $a3
$filePath = "Config.txt"
$lineNumber = "1"
$fileContent = Get-Content $filePath
$fileContent[$lineNumber-1] = $a3.FullName + "\*"
$fileContent | Set-Content $filePath -Force
}
else {
$var_saveR.Foreground = "Red"
$var_saveR.Content = "Not Found"
$timer = New-Object System.Windows.Forms.Timer -Property #{
Enabled = $true
Interval = 7000
}
$timer.add_Tick({$var_saveR.Content = ""})
}
}
function manualSave {
Add-Type -AssemblyName System.Windows.Forms
$browser = New-Object System.Windows.Forms.FolderBrowserDialog
$browser.ShowDialog()
$var_loc1.Content = $browser.SelectedPath
$filePath = "Config.txt"
$lineNumber = "1"
$fileContent = Get-Content $filePath
$fileContent[$lineNumber-1] = $var_loc1.Content + "\*"
$fileContent | Set-Content $filePath -Force
}
function manualBack {
Add-Type -AssemblyName System.Windows.Forms
$browser = New-Object System.Windows.Forms.FolderBrowserDialog
$browser.ShowDialog()
$var_loc2.Content = $browser.SelectedPath
$filePath = "Config.txt"
$lineNumber = "2"
$fileContent = Get-Content $filePath
$fileContent[$lineNumber-1] = $var_loc2.Content + "\*"
$fileContent | Set-Content $filePath -Force
}
function backup {
$file = "Config.txt"
$a1 = Get-Content $file
$a1[0]
$a1[1]
Copy-Item $a1[0] ($a1[1] -replace '\\\*','') -Recurse
$var_backupStatus.Foreground = "Green"
$var_backupStatus.Content = "Done"
$timer = New-Object System.Windows.Forms.Timer -Property #{
Enabled = $true
Interval = 5000
}
$timer.add_Tick({$var_backupStatus.Content = ""})
}
function restore {
$file = "Config.txt"
$a1 = Get-Content $file
$a1[0]
$a1[1]
Copy-Item $a1[1] ($a1[0] -replace '\\\*','') -Recurse #-Confirm
$var_restoreStatus.Foreground = "Green"
$var_restoreStatus.Content = "Done"
$timer = New-Object System.Windows.Forms.Timer -Property #{
Enabled = $true
Interval = 5000
}
$timer.add_Tick({$var_restoreStatus.Content = ""})
}
#UI
$var_aSearchButton.Add_Click({autoSearch})
$var_mSetButton1.Add_Click({manualSave})
$var_mSetButton2.Add_Click({manualBack})
$var_backupButton.Add_Click({backup})
$var_restoreButton.Add_Click({restore})
$var_loc1.Content = (Get-Content "Config.txt" -TotalCount 1) -replace '\\\*',''
$var_loc2.Content = (Get-Content "Config.txt" -TotalCount 2)[-1] -replace '\\\*',''
$psform.ShowDialog() | Out-Null

Powershell Invoke-Sqlcmd : Conversion failed when converting date and/or time from character string

I am trying to import a datetime from PowerShell into a SQL Table. It's the only thing stored in that table.
When I run this code: (The value stored in the variable is: 11/19/2020 09:51:40.3244656)
$location = 'path'
Set-Location $location
$c = Get-ChildItem 'path' | Sort { $_.LastWriteTime } | select -last 1 | foreach { $a = $_; $b = Get-Acl $_.FullName; Add-Member -InputObject $b -Name "LastWriteTime" -MemberType NoteProperty -Value $a.LastWriteTime; $b }
$c.LastWriteTime
$date = $c.LastWriteTime
Function Get-Datetime([datetime]$Date = $date ) {
$DT = Get-Date -Date $Date
[string]$DateTime2 = $DT.Month.ToString() + '/'
[string]$DateTime2 += $DT.Day.ToString() + '/'
[string]$DateTime2 += $DT.Year.ToString() + ' '
[string]$DateTime2 += $DT.TimeOfDay.ToString()
return $DateTime2
}
$finaldate = Get-Datetime
#$dateFormatted = $date -format
Invoke-Sqlcmd -ServerInstance "Server" -Database "db" -query "Update [server].[schema].[table] Set [columnName] = '$finaldate'"
I get this error:
Powershell Invoke-Sqlcmd : Conversion failed when converting date and/or time from character string.
How can I get the Powershell command to update the table?
Thank you for your help.
#NekoMusume helped me get to the answer to this specific question. After adding this line, (modified from #NekoMusume's comment): Thanks #NekoMusume! (If you want to answer, I'll mark it for you.)
$finaldate = Get-Date $finaldate -Format "yyyy/MM/dd HH:mm"
The code worked. Final Working code
$location = 'path'
Set-Location $location
$c = Get-ChildItem 'path' | Sort { $_.LastWriteTime } | select -last 1 | foreach { $a = $_; $b = Get-Acl $_.FullName; Add-Member -InputObject $b -Name "LastWriteTime" -MemberType NoteProperty -Value $a.LastWriteTime; $b }
$c.LastWriteTime
$date = $c.LastWriteTime
Function Get-Datetime([datetime]$Date = $date ) {
$DT = Get-Date -Date $Date
[string]$DateTime2 = $DT.Month.ToString() + '/'
[string]$DateTime2 += $DT.Day.ToString() + '/'
[string]$DateTime2 += $DT.Year.ToString() + ' '
[string]$DateTime2 += $DT.TimeOfDay.ToString()
return $DateTime2
}
$finaldate = Get-Datetime
$finaldate = Get-Date $finaldate -Format "yyyy/MM/dd HH:mm"
#$dateFormatted = $date -format
Invoke-Sqlcmd -ServerInstance "Server" -Database "db" -query "Update [server].[schema].[table] Set [columnName] = '$finaldate'"

Powershell error. WriteToServer. column does not allow DBNull.Value

I am using following powershell script to collect server storage information from multiple servers and into the one of the SQL server table.
I am getting an error while executing following powershell script
Error:-
Exception calling "WriteToServer" with "1" argument(s): "Column
'server_name' does not allow DBNull.Value.
Table has only one column with all server names in it. Powershell script grabs server name from database table and collect server storage information. It works for few servers however it fails for few server with above error.
Table
CREATE TABLE [dbo].[server_space_lku](
[server_name] [varchar](50) NOT NULL,
CONSTRAINT [PK_server_lku] PRIMARY KEY CLUSTERED)
I am using following powershell script. How can I fix the issue?
param($destServer, $destDb)
function Get-SqlData
{
param([string]$serverName=$(throw 'serverName is required.'), [string]$databaseName=$(throw 'databaseName is required.'),
[string]$query=$(throw 'query is required.'))
Write-Verbose "Get-SqlData serverName:$serverName databaseName:$databaseName query:$query"
$connString = "Server=$serverName;Database=$databaseName;Integrated Security=SSPI;"
$da = New-Object "System.Data.SqlClient.SqlDataAdapter" ($query,$connString)
$dt = New-Object "System.Data.DataTable"
[void]$da.fill($dt)
$dt
} #Get-SqlData
function Get-Vol
{
param($computerName)
Get-WmiObject -computername "$ComputerName" Win32_Volume -filter "DriveType=3 AND SystemVolume = $false" |
foreach { add-member -in $_ -membertype noteproperty UsageDT $((Get-Date).ToString("yyyy-MM-dd"))
add-member -in $_ -membertype noteproperty SizeGB $([math]::round(($_.Capacity/1GB),2))
add-member -in $_ -membertype noteproperty FreeGB $([math]::round(($_.FreeSpace/1GB),2))
add-member -in $_ -membertype noteproperty PercentFree $([math]::round((([float]$_.FreeSpace/[float]$_.Capacity) * 100),2)) -passThru} |
select UsageDT, SystemName, Name, Label, SizeGB, FreeGB, PercentFree
}# Get-Vol
function Out-DataTable
{
param($Properties="*")
Begin
{
$dt = new-object Data.datatable
$First = $true
}
Process
{
$DR = $DT.NewRow()
foreach ($item in $_ | Get-Member -type *Property $Properties ) {
$name = $item.Name
if ($first) {
$Col = new-object Data.DataColumn
$Col.ColumnName = $name
$DT.Columns.Add($Col)
}
$DR.Item($name) = $_.$name
}
$DT.Rows.Add($DR)
$First = $false
}
End
{
return #(,($dt))
}
}# Out-DataTable
function Write-DataTableToDatabase
{
param($destServer,$destDb,$destTbl,$dt)
$connectionString = "Data Source=$destServer;Integrated Security=true;Initial Catalog=$destdb;"
$bulkCopy = new-object ("Data.SqlClient.SqlBulkCopy") $connectionString
$bulkCopy.DestinationTableName = "$destTbl"
$bulkCopy.WriteToServer($dt)
}# Write-DataTableToDatabase
Get-SqlData $destServer $destDb "SELECT server_name FROM server_space_lku" |
foreach {
#Get just the server name portion if instance name is included
$computerName = $_.server_name -replace "\\.*|,.*"
$dt = Get-Vol $computerName | Out-DataTable
Write-DataTableToDatabase $destServer $destDb 'vol_space' $dt
}

Start-Job -ScriptBlock: Retrieving an array that is compiled inside the ScriptBlock

I have a Foreach loop inside a ScriptBlock that builds an array.
I cannot figure out how to retrieve the array from the Job once it's finished.
Here is my current code.
$HSMissingEmail = New-Object System.Collections.ArrayList
$HSDataObjects = New-Object System.Collections.ArrayList
$HSMissingEmail = Start-Job -Name HSMissingEmailStatus -ScriptBlock {
param($HSDataObjects, $HSMissingEmail);
foreach ($HSDO in $HSDataObjects) {
$HSDO = $HSDO | Select-Object Name, Location, Telephone, EmailAddress, Comments;
if ($HSDO | Where-Object {$_.EmailAddress -like ""}) {
$HSMissingEmail.Add($HSDO)
}
}
} -HSDataObjects $HSDataObjects -HSMissingEmail $HSMissingEmail | Receive-Job -Name HSMissingEmailStatus
I've also tried the following but it didn't do anything either.
$HSMissingEmail = New-Object System.Collections.ArrayList
$HSDataObjects = New-Object System.Collections.ArrayList
$ScriptBlock =
{
param($HSDataObjects,$HSMissingEmail)
foreach ($HSDO in $HSDataObjects)
{
$HSDO = $HSDO | Select-Object Name, Location, Telephone, EmailAddress, Comments
if ($HSDO | Where-Object {$_.emailaddress -like ""})
{
$HSMissingEmail.Add($HSDO)
}
}
}
Start-Job -Name HSMissingEmailStatus -ScriptBlock $ScriptBlock -HSDataObjects $HSDataObjects -HSMissingEmail $HSMissingEmail
ProgressBar ([REF]$HSMissingEmailStatus)
$HSMissingEmail = Receive-Job -Name HSMissingEmailStatus
Get-job -Name HSMissingEmailStatus | Remove-Job
I have tried many different ways to form the ScriptBlock but none are returning anything to $HSMissingEmail.
Also the second block of code doesn't get the passed data until I make the ScriptBlock all one line, which I'm unsure if this is a default behavior.
How can I retrieve the array?
You need to write the array out to standard out.
$HSMissingEmail = New-Object System.Collections.ArrayList
$HSDataObjects = New-Object System.Collections.ArrayList
$HSMissingEmail = Start-Job -Name HSMissingEmailStatus -ScriptBlock {
param($HSDataObjects, $HSMissingEmail);
foreach ($HSDO in $HSDataObjects) {
$HSDO = $HSDO | Select-Object Name, Location, Telephone, EmailAddress, Comments;
if ($HSDO | Where-Object {$_.EmailAddress -like ""}) {
$HSMissingEmail.Add($HSDO)
}
}
$HSMissingEmail # Drops it out as a result of the script block
} -HSDataObjects $HSDataObjects -HSMissingEmail $HSMissingEmail
Receive-Job -Name HSMissingEmailStatus -Wait # At the appropriate time, or keep cycling until you get it all
As far as the single-line/multiline bit, it might be a problem with not explicitly typing the variable as [ScriptBlock], but I'd have to check.

Powershell Group Array

I have a custom array
$myresults = #()
$w3svcID = $result.ReturnValue -replace "IISWebServer=", ""
$w3svcID = $w3svcID -replace "'", ""
$vdirName = $w3svcID = "/ROOT";
$vdirs = gwmi -namespace "root\MicrosoftIISv2" -class "IISWebVirtualDirSetting"
foreach($vdir in $vdirs)
{
$vPool = $vdir.Apppoolid
$vName = $vdir.Name
$robj = New-Object System.Object
$robj | Add-Member -type NoteProperty -name Path -value $vName
$robj | Add-Member -type NoteProperty -name Pool -value $vPool
$myresults += $robj
}
$myresults | group-object Pool
I'd like to be able to Group the data in the form of a list where the group values (Path) is under the group-by values (Pool); like so:
DefaultAppPool
W3SVC\
W3VSC\1\ROOT\
MyAppPool
W3SVC\1\ROOT\MyVirtual\
Give this a try:
Get-WmiObject IISWebVirtualDirSetting -Namespace root\MicrosoftIISv2 |
Group-Object AppPoolId | Foreach-Object{
$_.Name
$_.Group | Foreach-Object { "`t$($_.Name)" }
}

Resources