Does windbg aliases really be expanded when a new block of code is entered? - windbg

"An alias consists of an alias name and an alias equivalent. When you use an alias name as part of a debugger command, the name is automatically replaced by the alias equivalent. This replacement occurs immediately, before the command is parsed or executed." All above is from windbg help document. The following is the content of my windbg script file.
ad /q *
;aS MyVar 0x7b;
.block
{
;aS /x ${/v:MyVar} ${MyVar}+0x1;
.block
{
.printf "MyVar1=0x%x\n",${MyVar};
.block
{
.printf "MyVar2=0x%x\n",${MyVar};
}
.printf "MyVar3=0x%x\n",${MyVar};
}
.block
{
.printf "MyVar4=0x%x\n",${MyVar};
}
}
.block
{
.printf "MyVar5=0x%x\n",${MyVar};
}
al;
The following is the result of executing this script.
0:000> $$><c:\windbg.wds
MyVar1=0x7b
MyVar2=0x7b
MyVar3=0x7b
MyVar4=0x7b
MyVar5=0x7c
Alias Value
------- -------
MyVar 0x7c
I don't know why the first four line result occured,so I come here to ask for help.

From WinDbg aS help:
Note that if the portion of the line after the semicolon requires expansion of the alias, you must enclose that second portion of the line in a new block.
From WinDbg .block help:
When each block is entered, all aliases within the block are evaluated. If you alter the value of an alias at some point within a command block, commands subsequent to that point will not use the new alias value unless they are within a subordinate block.
where subordinate obviously has the meaning of following and not nested.
So yes, you have found another limitation of WinDbg's scripting language. I recommend looking at alternatives such as PyKd or similar.

Related

Always append arguments to command in Powershell

There's a few commands I need to run repetitively in Powershell, with some variable arguments in content and length, but some arguments must always be there. I don't want to forget those arguments, so is there a way to create a function that does this?
I have tried using things like Invoke-Expression, but when I use brackets in a command, Powershell thinks it's a type and tells me my cast is not valid. If I escape the argument list and provide an argument in the form Key=Value, PowerShell parses it into a System.Object[] and the command fails. I figured it might be better not to ask about how to fix that, but how to solve my root problem.
You can consider this a somewhat duplicate of How to always append an ampersand for certain commands? (MacOS / bash) but for PowerShell.
Just write your own version of the command as a Function with mandatory parameters:
Function RunMyCommand {
Param(
[Parameter(Position=0,mandatory=$true)][string]$Argument1,
[Parameter(Position=1,mandatory=$true)][int]$Argument2,
[Parameter(Position=2,mandatory=$true)]$Argument3
)
# Amend this according to the syntax and string manipulation required for your command
ThisIsMyCommand $Argument1 $Argument2 $Argument3
}
RunMyCommand -Argument1 ThisString -Argument2 ThisNumber -Argument3 ThisAnything

Powershell function call changing passed string into int

So I am using the kind of buggy Sapien powershell studio to make a powershell driven GUI application, and I am attempting to perform an ADSI query.
$nameOfDeviceInput is a System.Windows.Forms.TextBox
On one form, I have the following function:
$buttonPerformAction_Click={
if (FindInAD($nameOfDeviceInput.Text).Count -gt 0)
{
$buttonPerformAction.BackColor = 'Red'
$buttonPerformAction.Text = "System already exists in AD with that name. Try another name"
return
}
.....
}
On the "main" form, I have the function FindInAD
function FindInAd($nameOfSystem)
{
Write-Host "seeking system" $nameOfSystem
([adsisearcher]"(CN=$nameOfSystem)").FindAll()
}
FindInAd() is failing because for whatever reason, $nameOfSystem is set to 1, and if I don't explicitly cast it as a string, it gets implicitly cast to Int32 (obviously)
I have tried the following:
Fully qualifying the textbox input by notating the form it belongs to ( $adObjectModifier )
$buttonPerformAction_Click={
if (FindInAD($adObjectModifier.$nameOfDeviceInput.Text).Count -gt 0)
{
$buttonPerformAction.BackColor = 'Red'
$buttonPerformAction.Text = "System already exists in AD with that name. Try another name"
return
}
.....
}
Explicitly casting the $nameOfSystem parameter as a type of [string]
function FindInAd([string]$nameOfSystem)
{
Write-Host "seeking system" $nameOfSystem
([adsisearcher]"(CN=$nameOfSystem)").FindAll()
}
Passing a raw string into FindInAD from the AdObjectModifier form.
....
if (FindInAD("Test").Count -gt 0)
....
There is nothing else on the output pipeline at the time, (at least not from me) in between the method invocation. It is EventHandler > Function Call with String parameter
Why are the strings I'm passing getting changed to a digit???
EDIT: I think my passed parameter is being automatically replaced with the resulting boolean somehow, but this doesn't make any sense to me....
Your have a syntax problem:
FindInAD($nameOfDeviceInput.Text).Count # WRONG
Note: Wrong in this context means: the syntax is formally valid, but doesn't do what you expect - see the bottom section.
It should be:
(FindInAD $nameOfDeviceInput.Text).Count
PowerShell commands - functions, cmdlets, scripts and external programs - are invoked like shell commands - foo arg1 arg2 - and not like C# methods - foo('arg1', 'arg2').
That is:
Do not put (...) around the list of arguments.
However, you do need (...) around the call as a whole if you want a command call to participate in an expression, as shown above with the access to property .Count - see this answer for more information.
Separate arguments with spaces, both from each other and from the command name - do not use ,
, between arguments functions differently: It constructs an array that is passed as a single argument - see below.
You may pass simple strings (ones that contain neither spaces nor PowerShell metacharacters such as ; or &) as barewords; that is, quoting them is optional; e.g., instead of foo 'bar', you can call foo bar - see this answer for how PowerShell parses unquoted command arguments.
Also, if a target function or script has explicitly declared parameters (which binary cmdlets invariably do), such as -bar and -baz, you can pass your values as named arguments, i.e. by prepending them with the target parameter name; doing so is good practice in scripts: foo -bar arg1 -baz arg2
By contrast, calling methods of objects uses the syntax familiar from regular programming languages such as C# ($obj.foo('arg1', 'arg2'))
This difference relates two PowerShell's two fundamental parsing modes, explained in detail in this answer:
Commands are parsed in argument mode - as in shells.
Method calls and operator-based expressions are parsed in expression mode - as in regular programming languages.
These modes are required in order to allow PowerShell serve double duty: as a shell on the one hand, and as a scripting (programming) language on the other.
PowerShell can help you avoid this syntax problem:
Note that the problem isn't that using method syntax to call a command is invalid syntax, but that it doesn't work as intended, which can be difficult to diagnose.
In short: When you call command foo as foo('foo', 'bar'), ('foo', 'bar')is a 2-element array, which is then passed to foo as a single argument.
To prevent the problem to begin with, you can set Set-StrictMode to -Version 2 or higher, which makes PowerShell report an error if you accidentally use method syntax when calling a command:
# Turn on the check for accidental method syntax.
# Note: This also turns on ADDITIONAL checks - see below.
Set-StrictMode -Version 2
# This call now produces an ERROR, because the proper syntax would be:
# foo 'a' 'b'
foo('a', 'b')
Caveats:
Set-StrictMode -Version 2 comprises additional strictness checks that you must then also conform to, notably:
You must not reference non-existent variables.
You must not reference non-existent properties; see GitHub issue #2798 for an associated pitfall in connection with PowerShell's unified handling of scalars and collections.
An error is reported only for pseudo method calls with multiple arguments (e.g.,
foo('bar', 'baz')), not with only one; e.g., foo('bar') is accepted, because the single-argument case generally still (accidentally) works.
The errors reported for strictness violations are statement-terminating errors: that is, they only terminate the statement at hand, but by default the script continues; to ensure that overall execution aborts - on any type of error - you'd have to set
$ErrorActionPreference = 'Stop' at the start of your code. See this answer for more information.
As for what you tried:
FindInAD($nameOfDeviceInput.Text).Count
is the same as:
FindInAD ($nameOfDeviceInput.Text).Count
That is, the result of expression ($nameOfDeviceInput.Text).Count is passed as an argument to function FindInAD.

Is it possible to dot source a string variable in PowerShell?

I know I can dot source a file:
. .\MyFunctions.ps1
But, I would like to dot source the commands in a string variable:
. $myFuctions
I see that this is possible:
.{$x=2}
And $x equals 2 after the script block is sourced.
But... .{$myFunctions} does not work.
I tried $myFunctions | Invoke-Expression, but it doesn't keep the source function in the current scope. The closest I have been able to come up with is to write the variable to a temporary file, dot source the file, and then remove the file.
Inevitably, someone will ask: "What are you trying to do?" So here is my use case:
I want to obfuscate some functions I intend to call from another script. I don't want to obfuscate the master script, just my additional functions. I have a user base that will need to adjust the master script to their network, directory structure and other local factors, but I don't want certain functions modified. I would also like to protect the source code. So, an alternate question would be: What are some good ways to protect PowerShell script code?
I started with the idea that PowerShell will execute a Base64-encoded string, but only when passed on the command line with -EncodedCommand.
I first wanted to dot source an encoded command, but I couldn't figure that out. I then decided that it would be "obfuscated" enough for my purposes if I converted by Base64 file into a decode string and dot sourced the value of the string variable. However, without writing the decoded source to a file, I cannot figure out how to dot source it.
It would satisfy my needs if I could Import-Module -EncodedCommand .\MyEncodedFile.dat
Actually, there is a way to achieve that and you were almost there.
First, as you already stated, the source or dot operator works either by providing a path (as string) or a script block. See also: . (source or dot operator).
So, when trying to dot-source a string variable, PowerShell thinks it is a path. But, thanks to the possibility of dot-sourcing script blocks, you could do the following:
# Make sure everything is properly escaped.
$MyFunctions = "function Test-DotSourcing { Write-Host `"Worked`" }"
. { Invoke-Expression $MyFunctions }
Test-DotSourcing
And you successfully dot-sourced your functions from a string variable!
Explanation:
With Invoke-Expression the string is evaluated and run in the child scope (script block).
Then with . the evaluated expressions are added to the current scope.
See also:
Invoke-Expression
About scopes
While #dwettstein's answer is a viable approach using Invoke-Expression to handle the fact that the function is stored as a string, there are other approaches that seem to achieve the same result below.
One thing I'm not crystal clear on is the scoping itself, Invoke-Expression doesn't create a new scope so there isn't exactly a need to dot source at that point...
#Define your function as a string
PS> $MyUselessFunction = "function Test-WriteSomething { 'It works!' }"
#Invoke-Expression would let you use the function
PS> Invoke-Expression $MyUselessFunction
PS> Test-WriteSomething
It works!
#Dot sourcing works fine if you use a script block
PS> $ScriptBlock = [ScriptBlock]::Create($MyUselessFunction)
PS> . $ScriptBlock
PS> Test-WriteSomething
It works!
#Or just create the function as a script block initially
PS> $MyUselessFunction = {function Test-WriteSomething { 'It works!' }}
PS> . $MyUselessFunction
PS> Test-WriteSomething
It works!
In other words, there are probably a myriad of ways to get something similar to what you want - some of them documented, and some of them divined from the existing documentation. If your functions are defined as strings, then Invoke-Expression might be needed, or you can convert them into script blocks and dot source them.
At this time it is not possible to dot source a string variable.
I stand corrected! . { Invoke-Expression $MyFunctions } definitely works!

command execution ordering inside a PowerShell scriptblock

I got excited with PowerShell ScriptBlock at first but I was confused recently with its executing ordering inside blocks. For example:
$test_block = {
write-host "show 1"
ps
write-host "show 2"
Get-Date
}
The output by calling $test_block.Invoke():
show 1
show 2
<result of command 'ps'>
<result of command 'get-date'>
Do commands who output something run first?
This behaviour is because write-host doesn't put the output on the pipeline. The other commands are placed on the pipeline so are not output to the screen until the function (invoke) returns.
To get the behaviour I believe you were expecting, use write-output instead, the results of all the commands will then be returned in the pipeline.
$test_block = {
write-output "show 1"
ps
write-output "show 2"
Get-Date
}
$test_block.Invoke()
To complement David Martin's helpful answer:
Avoiding Write-Host (which is often the wrong tool to use) in favor of Write-Output, i.e. outputting to the success output stream - rather than printing to the display with Write-Host[1] - solves your immediate problem.
However, you could have avoided the problem by using &, the call operator instead of the .Invoke() method:
# Invokes the script block and *streams* its output.
& $test_block
Using & is generally preferable, not just to avoid .Invoke()'s collect-all-success-output-stream-first behavior - see next section.
As an aside:
This answer describes common problem with similar symptoms (success output (pipeline output) appearing out of order relative to other streams), although it is technically unrelated and also occurs with &:
# !! The Write-Host output prints FIRST, due to implicit, asynchronous
# !! table formatting of the [pscustomobject] instance.
& { [pscustomobject] #{ Foo = 'Bar' }; Write-Host 'Why do I print first?' }
Why &, not .Invoke(), should be used to invoke script blocks ({ ... }):
Script blocks ({ ... }) are normally invoked with &, the call operator, in argument (parsing) mode (like cmdlets and external programs), not via their .Invoke() method, which allows for more familiar syntax; e.g.:
& $test_block rather than $test_block.Invoke()
with arguments: & $test_block arg1 ... rather than $test_block.Invoke(arg1, ...)
Perhaps more importantly, using this operator-based invocation syntax (& { ... } ... or . { ... } ...) has the following advantages:
It preserves normal streaming semantics, meaning that success output (too) is emitted from the script block as it is being produced, whereas .Invoke() collects all success output first, in a [System.Collections.ObjectModel.Collection[psobject]] instance, which it then returns - by contrast, the Write-Host output goes straight to the display in both cases.
As a beneficial side effect, your specific output-ordering problem goes away, but note that in PSv5+ there can generally still be an output-ordering problem, although its cause is unrelated:
Implicit tabular output (implied Format-Table) for output types without predefined format data is asynchronous in an effort to determine suitable column widths (your specific code happens to only use cmdlets with predefined format data).
See this answer for more information; a simple repro:
[pscustomobject] #{ foo = 1 }; Write-Host 'Should print after, but prints first.'
It allows you to pass named arguments (e.g. -Foo Bar), whereas .Invoke() supports only positional (unnamed) ones (e.g. Bar).
It preserves normal semantics for script-terminating errors:
# OK: & throw aborts the entire script; 'after' never prints.
& { throw 'fatal' }; 'after'
# !! .Invoke() "eats" the script-terminating error and
# !! effectively converts it to a *statement*-terminating one.
# !! Therefore, execution continues, and 'after' prints.
{ throw 'fatal' }.Invoke(); 'after'
Additionally, using operator-based invocation gives you the option to use ., the dot-sourcing operator, in lieu of &, so as to run a script block directly in the caller's scope, whereas an .Invoke() method call only runs in a child scope (as & does):
# Dot-sourcing the script block runs it in the caller's scope.
. { $foo='bar' }; $foo # -> 'bar'
Use of .Invoke() is best limited to PowerShell SDK projects (which are typically C#-based, where use of PowerShell operators isn't an option).
[1] Technically, since PowerShell v5 Write-Host outputs to the information stream (stream number 6), which, however, prints to the display by default, while getting ignored in the pipeline and redirections. See this answer for a juxtaposition of Write-Host and Write-Output, and why the latter is typically note even needed.

Call custom vim completetion menu with Information from Perl-Script

I wrote a script analyzing perl-files (totally without PPI, because it will be used on Servers where the admins don't want PPI to be installed and so on and so forth, but let's not talk about that).
Now, let's say I have this code:
my $object = MySQL->new();
my $ob2 = $object;
$ob2->
(Where MySQL is one of our modules).
My script correctly identifies that $ob2 is a MySQL-Object and sees where it came from, and then returns a list of found subs in that module.
My idea was, that, since I use vim for editing, this could be a really cool way for "CTRL-n"-Completetion.
So, when...
$ob2->[CTRL-n]
It shows the CTRL-n-Box which opens my Perl-Script and gives it a few parameters (I would need: The line that I am actually on, the cursor position and the whole file as it is in vim).
I already found things like vim-perl, which allows me to write something like
if has('perl')
function DefPerl()
perl << EOF
use MyModule;
return call_to_my_function(); # returns all the methods from the object for example
EOF
endfunction
call DefPerl()
endif
But somehow this does not get executed (I tried writing something to a file with a system call just for the sake of testing)...
So, in short:
Does anyone here know how to achieve that? Calling a perl-function from vim by pressing CTRL-n with the full file-code and the line vim is actually in and the position, and then opening a completetion-menu with the results it got from the perl-script?
I hope someone knows what I mean here. Any help would be appreciated.
The details and tips for invoking embedded Perl code from Vim can be found in this Vim Tips Wiki article. Your attempts are already pretty close, but to return stuff from Perl, you need to use Vim's Perl API:
VIM::DoCommand "let retVal=". aMeaningfullThingToReturn
For the completion menu, your Perl code needs to return a List of Vim objects that adhere to the format as described by :help complete-items. And :help complete-functions shows how to trigger the completion. Basically, you define an insert-mode mapping that sets 'completefunc' and then trigger your function via <C-x><C-u>. Here's a skeleton to get your started:
function! ExampleComplete( findstart, base )
if a:findstart
" Locate the start of the keyword.
let l:startCol = searchpos('\k*\%#', 'bn', line('.'))[1]
if l:startCol == 0
let l:startCol = col('.')
endif
return l:startCol - 1 " Return byte index, not column.
else
" Find matches starting with a:base.
let l:matches = [{'word': 'example1'}, {'word': 'example2'}]
" TODO: Invoke your Perl function here, input: a:base, output: l:matches
return l:matches
endif
endfunction
function! ExampleCompleteExpr()
set completefunc=ExampleComplete
return "\<C-x>\<C-u>"
endfunction
inoremap <script> <expr> <Plug>(ExampleComplete) ExampleCompleteExpr()
if ! hasmapto('<Plug>(ExampleComplete)', 'i')
imap <C-x><C-z> <Plug>(ExampleComplete)
endif