Variable being passed in as null - Powershell - powershell

So I have an issue that has been bugging me for a few hours now.
I have two functions, Write-Log, and LogProfileRemoval. In Write-Log, I pass in the two arguments as shown here.
LogProfileRemoval('$LogEventDetail', 100000)
But when I check the variables of LogProfileRemoval they are shown like this
$LogEventDetail = '$LogEventDetail' 100000
$LogMethod = $null
I am aware that I have quotes around the variable $LogEventDetail, that was part of my testing to figure this out. Really that variable could be anything and it still concats those two variables into one and leaves the 2nd parameter as a null value.
What am I doing wrong here.
Thanks
function LogProfileRemoval($LogEventDetail, $LogMethod)
{
Switch ($LogMethod)
{
'EventLog' {LogToEventLog($LogEvent)}
}
}
function Write-Log($logDetail, $logEvent=2)
{
$LogEventDetail = New-Object EventLog -Property #{EventTimeStamp=(Get-Date);EventType=$logEvent;EventDetail=$logDetail}
$LogMethod = 1
LogProfileRemoval('$LogEventDetail', 100000)
}

So by not following best practices, was the issue. Weird becuase I have always wrote my powershell scripts like this. Always been a not fan of the Param way of doing it. I changed it to best practice way (sorta) and it worked great.
I would like to know why it didn't work though but overall It just goes to show me to quick being lazy and do it the right way.
Code working shown below
function LogProfileRemoval
{
param(
$LogEventDetail,
$LogMethod
)
Switch ($LogMethod)
{
'EventLog' {LogToEventLog($LogEvent)}
}
}
function Write-Log($logDetail,$logEvent=2)
{
$LogEventDetail = New-Object EventLog -Property #{EventTimeStamp=(Get-Date);EventType=$logEvent;EventDetail=$logDetail}
$LogMethod = 1
LogProfileRemoval -LogEventDetail $LogEventDetail -LogMethod 'EventLog'
}

Related

Is there a "function-like-thing" that can act as a template?

I have a code like this that is repeated multiple times in each of my conditional statements/cases. i have 3 conditions...for now, and everything works perfectly, but im mulling reformatting the script for easier reading.
One of the ways ive thought is to make a function, but the problem is that, i have a while loop that is intended for a specific scenario in each conditional statement that dequeues from a Queue containing some column names from a file.
so based on the code below that i want to put in some sort of template, i cant think of how this could work because as you can see, $tb stands for $table, which is what im opening prior to the conditional statements in my code.
if i were to include everything regarding the server connection and table in a function, that means when i pass the "function" containing the code to the while loops, it will be creating/instantiating the table every iteration, which wont make sense and wont work anyways.
so i am thinking of using something like annotations, something like a template which wont expect to return anything or need reasonable arguments like a function otherwise would. The question is, does something like that exist?
This is the code that is the same across all my while loops that i would like to "store" somewhere and just pass it to them:
$dqHeader = $csvFileHeadersQueue.Dequeue()
$column = New-Object Microsoft.SqlServer.Management.Smo.Column($tb, $dqHeader, $DataType1)
if ($dqHeader -in $PrimaryKeys)
{
# We require a primary key.
$column.Nullable = $false
#$column.Identity = $true #not needed with VarChar
#$column.IdentitySeed = 1 #not needed with VarChar
$tb.Columns.Add($column)
$primaryKey = New-Object Microsoft.SqlServer.Management.Smo.Index($tb, "PK_$csvFileBaseName")
$primaryKey.IndexType = [Microsoft.SqlServer.Management.Smo.IndexType]::ClusteredIndex
$primaryKey.IndexKeyType = [Microsoft.SqlServer.Management.Smo.IndexKeyType]::DriPrimaryKey #Referential Integrity to prevent data inconsistency. Changes in primary keys must be updated in foreign keys.
$primaryKey.IndexedColumns.Add((New-Object Microsoft.SqlServer.Management.Smo.IndexedColumn($primaryKey, $dqHeader)))
$tb.Indexes.Add($primaryKey)
}
else
{
$tb.Columns.Add($column)
}
think of it like a puzzle piece that would fit right in when requested to do so in the while loops to complete that "puzzle"
As per comment:
you can share a (hardcoded) [ScriptBlock] ($template = {code in post goes here}) with a While loop (or function) and invoke it with e.g. Invoke-Command $template or the call operator: &$template. Dynamically modifying an expression and using commands like Invoke-Expression or [ScriptBlock]::Create() is not a good idea due to risk of malicious code injections (see: #1454).
You might even add parameters to your shared [ScriptBlock], like:
$Template = {
[CmdletBinding()]Param ($DataType)
$column = New-Object Microsoft.SqlServer.Management.Smo.Column($tb, $dqHeader, $DataType)
...
}
ForEach ($MyDataType in #('MyDataType')) {
Invoke-Command $Template -ArgumentList $MyDataType
}
But the counter-question remains: Why not just creating a "helper" function?:
Function template($DataType) {
$column = New-Object Microsoft.SqlServer.Management.Smo.Column($tb, $dqHeader, $DataType)
...
}
ForEach ($MyDataType in #('MyDataType')) {
template $MyDataType
}

Why weird assignment from variable inside Powershell switch statement?

I'm a beginner at Powershell and am struggling to understand some syntax from some code I found on Github. I've read the docs on Powershell assignment, and on switch statements, and can't understand what is going on with the = $Yes and = $No in this code snippet:
Switch ($Prompt3) {
Yes {
Stop-EdgePDF
Write-Output "Edge will no longer take over as the default PDF viewer."; = $Yes
}
No {
= $No
}
}
I haven't been able to find any references to this kind of syntax, and it doesn't seem to do anything in the script. So why is it there?
UPDATE: This issue has been resolved.
Looks to me like the variable name that was getting the assignment was deleted in a change back in August.
$PublishSettings = $Yes
Was changed to:
= $Yes
And:
$PublishSettings = $No
Was changed to:
= $No
Looks like poor search and replace.
I've created an issue for the problem at GitHub.
There are many characters that are valid in a function (or variable) name; this includes the = symbol. What you're observing is a function or alias.
Examples:
# standard function
function =
{
return $args
}
# accessing the function: drive
${Function:=} = {
return $args
}
# defining a new alias
New-Alias -Name = -Value Get-Variable
# using the Alias attribute
function Test-Thing
{
[Alias('=')]
param()
return $args
}

Removing the Add_Click from a WinForm Button in Powershell (remove_Click)

I have got an understanding problem regarding to Powershell Code in order to remove a Click Event from a WinForm button. After several hours... several days of trying, trying to understand and despairing I thought I give it a break and probably you guys can help me. I really have read several Posts regarding this theme. But that did not help me finally. So please let me ask that question again.
I have seen that there is a possibility to use Eventhandlers and this method seems to work quite fine. As my code seems to be correct, because Powershell do not throw out an error, I would like to know why the code line seems not to be affective. I really do not understand why. Because I have found several codes with remove_Click examples, but in my case it seems not to do what I expect. As I really do not understand why I would like you to help me. Please be so kind and try to explain to me why line 30 of my script has no effect or not the desired effect.
Short: What do I want to do? I just want to remove a Click Event from a button. I could add the Event to the button using Add_Click. So I thought Remove_Click would remove the "Click Code" from this Special button. But it does not seem to work. I just want to remove the Click Property from the button if the savefiledialog is closed by using the cancel button.
This is the code:
Add-Type -AssemblyName System.Windows.Forms
function form_status(){
$form_status = New-Object System.Windows.Forms.Form
$form_status.Size = New-Object System.Drawing.Size(800,530)
$form_status.StartPosition = 'CenterScreen'
$form_status.FormBorderStyle = 'FixedToolWindow'
$form_status_button_csv_logfile = New-Object System.Windows.Forms.Button
$form_status_button_csv_logfile.Location = New-Object System.Drawing.Point(1,1)
$form_status_button_csv_logfile.Size = New-Object System.Drawing.Size(50,50)
$form_status.Controls.Add($form_status_button_csv_logfile)
$form_status_button_csv_logfile.Add_Click({Choose-Folder-For-Checksumlog})
$form_status_button_csv_logfile.add_MouseHover({button_mousehover})
$form_status_button_csv_logfile.add_MouseLeave({button_mouseleave})
[System.Windows.Forms.Application]::EnableVisualStyles();
$form_status_result = $form_status.ShowDialog()
}
Function Choose-Folder-For-Checksumlog(){
$SaveChooser = New-Object -Typename System.Windows.Forms.SaveFileDialog
$SaveChooser.InitialDirectory = [Environment]::GetFolderPath("Desktop")
$SaveChooser.Filter = "CSV Logfile (*.csv)|*.csv"
$savechooser.FileName = "testfile.csv"
if($SaveChooser.ShowDialog() -eq [System.Windows.Forms.DialogResult]::CANCEL){
$savechooser.FileName = ""
$form_status_button_csv_logfile.Remove_Click({Choose-Folder-For-Checksumlog})
}
$checksumlog_folder = $SaveChooser.FileName
}
function button_mouseleave(){
$form_status.Cursor=[System.Windows.Forms.Cursors]::Default
}
function button_mousehover(){
$form_status.Cursor=[System.Windows.Forms.Cursors]::Hand
}
form_status
I appreciate any help from you guys. Please be so kind and explain to me what I do wrong. Probably my expectaions are wrong... But I do not understand it at the moment.
With kindest Regards
FernandeZ
$clickexample = {Choose-Folder-For-Checksumlog};
$form_status_button_csv_logfile.add_Click($clickexample);
$form_status_button_csv_logfile.remove_Click($clickexample);
I know that I'm a bit late to the party, but recently I came into the situtation where it was required to remove multiple event handlers from multiple elements (several different-purpose Click handlers on each of six buttons in my case).
While suggestion from #D'Artagnan works, it is still not helpful in case if your scriptblock handler is not stored in variable (or variable is unknown).
For example, this code removes handler from the button:
$ScriptBlock = {Write-Host 'Clicked'}
$MyButtonObject.Add_Click($ScriptBlock)
$MyButtonObject.Remove_Click($ScriptBlock)
But this one does not (I believe, it is because scriptblock is not referenced by variable, therefore it is a different object, which is not registered in event handler, and, as result, cannot be removed):
$MyButtonObject.Add_Click({Write-Host 'Clicked'})
$MyButtonObject.Remove_Click({Write-Host 'Clicked'})
In addition, I wasn't able to find something like .Remove_AllHandlers(), unfortunately.
Thankfully, I've discovered this question and was able to adapt the code given by #Douglas to PowerShell, so with credits to the original author, I'm happy to share the solution with anyone who wonders:
Function Remove-RoutedEventHandlers {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $True)]
[ValidateNotNullorEmpty()]
[System.Windows.UIElement]$Element,
[Parameter(Mandatory = $True)]
[ValidateNotNullorEmpty()]
[System.Windows.RoutedEvent]$RoutedEvent
)
$eventHandlersStoreProperty = $Element.GetType().GetProperty("EventHandlersStore", [System.Reflection.BindingFlags]'Instance, NonPublic')
$eventHandlersStore = $eventHandlersStoreProperty.GetValue($Element, $Null)
If ($eventHandlersStore) {
$getRoutedEventHandlers = $eventHandlersStore.GetType().GetMethod("GetRoutedEventHandlers", [System.Reflection.BindingFlags]'Instance, Public, NonPublic')
$RoutedEventHandlers = [System.Windows.RoutedEventHandlerInfo[]]$getRoutedEventHandlers.Invoke($eventHandlersStore, $RoutedEvent)
ForEach ($RoutedEventHandler in $RoutedEventHandlers) {
$Element.RemoveHandler($RoutedEvent, $RoutedEventHandler.Handler)
}
}
}
To call the function, you must provide the control and required kind of events to be cleared. For example:
Remove-RoutedEventHandlers -Element $MyButtonObject -RoutedEvent $([System.Windows.Controls.Button]::ClickEvent)
Please note that you have to put event in $() to avoid it from being treated as string. Alternatively, you could alter the function to accept string (for example, with value "Click") and re-construct such event on the provided control inside the function like this $RoutedEvent = $Element.GetType()::"${RoutedEvent}Event"
This function enumerates all handlers of the specified type on provided object and removes them.
If I'm not mistaken, if you call $Element.Remove_SomeEvent($ScriptBlockToRemove) in PowerShell, $Element.RemoveHandler($Element.GetType()::SomeEvent, $ScriptBlockToRemove) is being executed under the hood, so in given example this function is equivalent of enumerating all of the scriptblocks (referenced in Handler property of RoutedEventHandlerInfo object) and calling $MyButtonObject.Remove_Click($ScriptBlockToRemove) on each of them

Explicit Return in Powershell

I can write the following code in javascript:
function sum(num1, num2) {
return num1 + num2;
}
and then get a value
var someNum = sum(2,5);
I would like to do the same thing in Powershell, but I read the following guide:
PowerShell also knows the return keyword; however, it follows a
different logic. In general, the purpose of return is to end the
execution of a code section and to give the control back to the parent
block.
If you add a parameter to the return statement, the value will indeed
be returned to the calling subroutine. However, this also applies for
all other statements with an output. This means that any output
produced in the function will be stored in the variable together with
the return parameter.
I want to do this for the sake of having pure functions. However, it seems doing
var someNum = sum(2,5);
is entirely redundant, when I can just call the function above, define someNum inside of it, and it will be available in the global scope.
Am I missing something or is it possible to write pure functions in Powershell that don't return everything inside the function?
A bit tangential, but here is my actual code:
function GetPreviousKeyMD5Hashes() {
$query = "SELECT Name, MD5, executed FROM [AMagicDb].[dbo].cr_Scripts";
$command = New-Object System.Data.SQLClient.SQLCommand;
$command.Connection = $connection;
$command.CommandText = $query;
try {
$reader = $command.ExecuteReader();
while ($reader.Read()) {
$key = $reader.GetString(1)
$previousScripts.Add($key) | Out-Null
}
$reader.Close();
Write-Output "$(Get-Date) Finished querying previous scripts"
}
catch {
$exceptionMessage = $_.Exception.Message;
Write-Output "$(Get-Date) Error running SQL at with exception $exceptionMessage"
}
}
and then:
$previousScripts = New-Object Collections.Generic.HashSet[string];
GetPreviousKeyMD5Hashes;
This code isn't clear to me at all - running GetPreviousKeyMD5Hashes does set $previousScripts, but this is entirely unclear to whoever modifies this after me. My only other alternative (afaik) is to have all this in line, which also isn't readable.
is entirely redundant, when I can just call the function above, define someNum inside of it, and it will be available in the global scope.
No: functions execute in a child scope (unless you dot-source them with .), so variables created or assigned to inside a function are local to it.
Am I missing something or is it possible to write pure functions in Powershell that don't return everything inside the function?
Yes: The implicit output behavior only applies to statements whose output is neither captured - $var = ... - nor redirected - ... > foo.txt
If there are statements that happen to produce output that you'd like to discard, use $null = ... or ... > $null
Note: ... | Out-Null works in principle too, but will generally perform worse, especially in earlier PowerShell versions - thanks, TheIncorrigible1.
If there are status messages that you'd like to write without their becoming part of the output, use Write-Host or, preferably Write-Verbose or, in PSv5+, Write-Information, though note that the latter two require opt-in for their output to be visible in the console.
Do NOT use Write-Output to write status messages, as it writes to the success output stream, whose purpose is to output data ("return values").
See this answer of mine for more information about PowerShell's output streams.
The equivalent of your JavaScript code is therefore:
function sum($num1, $num2) {
Write-Host "Adding $num1 and $num2..." # print status message to host (console)
$num1 + $num2 # perform the addition and implicitly output result
}
PS> $someNum = sum 1 2 # NOTE: arguments are whitespace-separated, without (...)
Adding 1 and 2... # Write-Host output was passed through to console
PS> $someNum # $someNum captured the success output stream of sum()
3
Am I missing something or is it possible to write pure functions in Powershell that don't return everything inside the function?
You can't have your cake and eat it too...
If you have no out put in your function, then it is "pure" like you desire. If you have output, that also becomes part of the return.
You can use [ref] params. See below for example.
function DoStuff([ref]$refObj)
{
Write-Output "DoStuff: Enter"
$refObj.Value += $(1 + 2)
$refObj.Value += "more strings"
Write-Output "DoStuff: Exit"
}
$refRet = #()
$allRet = DoStuff([ref]$refRet)
"allRet"
$allRet
"refRet"
$refRet
"`n`nagain"
$allRet = DoStuff([ref]$refRet)
"allRet"
$allRet
"refRet"
$refRet
Note: Powershell doesn't need semicolons at the end of each statement; only for separating multiple statements on the same line.
Whenever possible, it's a good idea to avoid changing global state within a function. Pass input as parameters, and return the output, so you aren't tied to using the function in only one way. Your sample could look like this:
function sum
{
param($num1,$num2)
return $num1+$num2
}
$somenum=sum 2 5
Now, with Powershell, the return statement isn't needed. The result of every statement that isn't otherwise assigned, captured, redirected, or otherwise used, is just thrown in with the return value. So we could replace the return statement above with simply
$num1+$num2
You're already making use of this in your code with:
$previousScripts.Add($key) | Out-Null
where you are discarding the result of .Add(). Otherwise it would be included in the return value.
Personally, I find using return to explicitly mark the return value makes it easier to read. Powershell's way of putting all if the output in the return caused a lot of trouble for me as I was learning.
So, the only fixes to your code I would make are:
Move $previousScripts = New-Object Collections.Generic.HashSet[string] to inside the function, making it local.
Add return $previousScripts to the end of the function.

How can I quickly find VMs with serial ports in PowerCLI

I have a script that takes about 15 minutes to run, checking various aspects of ~700 VMs. This isn't a problem, but I now want to find devices that have serial ports attached. This is a function I added to check for this:
Function UsbSerialCheck ($vm)
{
$ProbDevices = #()
$devices = $vm.ExtensionData.Config.Hardware.Device
foreach($device in $devices)
{
$devType = $device.GetType().Name
if($devType -eq "VirtualSerialPort")
{
$ProbDevices += $device.DeviceInfo.Label
}
}
$global:USBSerialLookup = [string]::join("/",$ProbDevices)
}
Adding this function adds an hour to the length of time the script runs, which is not acceptable. Is it possible to do this in a more efficient way? All ways I've discovered are variants of this.
Also, I am aware that using global variables in the way shown above is not ideal. I would prefer not to do this; however, I am adding onto an existing script, and using their style/formatting.
Appending to arrays ($arr += $newItem) in a loop doesn't perform well, because it copies all existing elements to a new array. This should provide better performance:
$ProbDevices = $vm.ExtensionData.Config.Hardware.Device `
| ? { $_.GetType().Name -eq 'VirtualSerialPort' } `
| % { $_.DeviceInfo.Label }