Sending complex, multi-line command via plink to Cisco Router =Unexplained behavior - powershell

I'm trying to get the below part of the code done in a relatively condensed fashion (to plug in to a much bigger script). I don't have any problems sending multiple commands this way. However, there's something that's causing the multi-line command to eventually choke. Syntax for Cisco comnmands appear to be correct. I'm not sure if I'm running into some kind of character limit or if I need to escape specific characters in $showintstatusCommands, but nothing I tried seems to work.
This code:
$BGPInterface = "GigabitEthernet0/2"
$showintstatusCommands = "`nterminal length 0`nsho int $BGPInterface | include reliability|errors`nsho log | include $Date.*LINK-3-UPDOWN.*$BGPInterface`nexit"
($Response = $showintstatusCommands | C:\Windows\plink.exe -ssh -2 -l $Credential.GetNetworkCredential().username -pw $($Credential.GetNetworkCredential().password) $DeviceName -batch) 2>$null | out-null
produces the below when I reveal the contents of the variables. $ShowIntstatusCommands appears to be correct when it echoes locally. Notice, the end of the 3rd line is cut off (number 2 character is missing at the end). Also the subsequent line is some weird residual of the previous line, which starts with $nclude.
PS C:\Users\MKANET\Desktop\test> $Response
CISCO-ROUTER#
CISCO-ROUTER#terminal length 0
CISCO-ROUTER#sho int GigabitEthernet0/2 | include reliability|errors
reliability 255/255, txload 1/255, rxload 1/255
0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
0 output errors, 0 collisions, 3 interface resets
CISCO-ROUTER#sho log | include Jul 17.*LINK-3-UPDOWN.*GigabitEthernet0/
$nclude Jul 17.*LINK-3-UPDOWN.*GigabitEthernet0/2
CISCO-ROUTER#
CISCO-ROUTER#exit
PS C:\Users\MKANET\Desktop\test> $showintstatusCommands
terminal length 0
sho int GigabitEthernet0/2 | include reliability|errors
sho log | include Jul 17.*LINK-3-UPDOWN.*GigabitEthernet0/2
exit

When you write to a variable in a non-global scope (like script or function scope), PowerShell will not modify any higher level scoped variables of the same name. IOW $Response = 'foo' will create a local copy of the $Response variable and assign 'foo' to it. If your intent is to modify the global variable $Response then change the line to $global:Response = ... What you see in $global:Response is residual, probably from previous tinkerings.

I finally verified that the same behavior was happening on all the remote devices if I typed in the command below manually. The line get's jumbled up if too many characters were used.
I changed:
sho log | include $Date.*LINK-3-UPDOWN.*$BGPInterface
to the below command (removing just a couple of characters); and, it worked fine. It looks like it was a Cisco IOS CLI limit.
sho log | include $Date.*LINK-3-UPDO.*$BGPInterface

Related

Strange powershell behaviour with script blocks and regex replace

I'm trying to use [regex]::Replace with a match evaluator to selectively replace parts of a string. I'm writing and debugging the function in PowerShell ISE. What is strange is that running the replacement code causes one machine to output a string that is the content of the match evaluator script block while the other replaces the text correctly. I had no clue this was even possible nor why it is happening.
Given this code (borrowed from another stackoverflow answer):
$global_counter = 0
$callback = {
$global_counter += 1
"string-$($args[0])-" + $global_counter
}
$re = [regex]"match"
$re.Replace('zzz match match xxx', $callback)
Executing it on one machine causes the output (PowerShell Version 5.1.18362.145):
zzz string-match-1 string-match-1 xxx
But on another it outputs (PowerShell Version 5.1.17134.858):
zzz
$global_counter += 1
"string-$($args[0])-" + $global_counter
$global_counter += 1
"string-$($args[0])-" + $global_counter
xxx
Both are running in an x64 PowerShell ISE clean instance directly from reboot. Does anyone know why this is happening?
With debugging help from Jeroen I've managed to figure out why this is happening.
PowerShell has a security feature called Constrained Language Mode that prevents the use of any, but a core set of whitelisted types. What appears to be happening is that I'm defining a scriptblock that in turn is converted to a System.Text.RegularExpressions.MatchEvaluator before being passed to the Replace function. The match evaluator however is outside of this core set of types which means when the PowerShell engine tries to coerce the type onto an overload of Replace the only other valid one is Replace(string, string, string) (thanks Jeroen for pointing this out in the comments). The Replace function does its job, but with a regular string as a replacement thus resulting in the odd behaviour.
I'm not able to alter the language mode of my PowerShell session on the machine I'm currently working with as it is applied through Group Policies, but a workaround for me at least was to use an elevated PowerShell session and ISE to test my script.

Leading 0 removed from argument in Powershell

New to Powershell, never needed it before I started this job. I'm just making an easier way for me to keep our stores pinging and kill some time learning. Some pretext; Our stores are always 4 numbers, so 1096 is 1096 but 704 is 0704.
Here is my current script:
$args.Length;
foreach ($arg in $args) {
Test-Connection $arg'router' }
Write-Host 'Pinging Store #'$arg
if($arg.legnth -lt 4) {
($arg).insert(0,'0')
}
If I execute with the argument 1096 all is well in the world, but if I use 0704 the leading 0 disappears. I've tried a number of potential resolutions, but I've found most are trying to remove trailing zeroes so I've just been trying to reverse engineer their solutions. What is the best way to ensure that the leading 0 isn't removed so the host is able to be found.
0704router exists.
704router doesn't exist.
This looks like an issue of how you call the script. You may be doing something like this:
./MyScript.ps1 1096 0704
Which will give you 2 arguments, but since they are unquoted and contain only digits, they are interpreted as integers, and so you lose leading zeros.
Instead, tell PowerShell you want these as string values by quoting them:
./MyScript.ps1 '1096' '0704'
The [string]$Args[1] worked for me and
it seems like the behavior is changing from version to version - same script worked without conversion with PS 2.0
Hope this helps!

Manage inputs from external command in a powershell script

First, I would like to apologize in case that the title is not descriptive enough, I'm having a hard time dealing with this problem. I'm trying to build an automation for a svn merge using a powershell script that will be executed for another process. The function that I'm using looks like this:
function($target){
svn merge $target
}
Now, my problem occurs when there are conflicts in the merge. The default behavior of the command is request an input from the user and proceed accordingly. I would like to automatize this process using predefined values (show the differences and then postpone the merge), but I haven't found a way to do it. In summary, the workflow that I am looking to accomplish is the following:
Detect whether the command execution requires any input to proceed
Provide a default inputs (in my particular case "df" and then "p")
Is there any way to do this in powershell? Thank you so much in advance for any help/clue that you can provide me.
Edit:
To clarify my question: I would like to automatically provide a value when a command executed within a powershell script require it, like in the following example:
Requesting user input
Edit 2:
Here is a test using the snippet provided by #mklement0. Unfortunately, It didn't work as expected, but I thought it was wort to add this edition to clarify the question per complete
Expected behavior:
Actual result:
Note:
This answer does not solve the OP's problem, because the specific target utility, svn, apparently suppresses prompts when the process' stdin input isn't coming from a terminal (console).
For utilities that do still prompt, however, the solution below should work, within the constraints stated.
Generally, before attempting to simulate user input, it's worth investigating whether the target utility offers programmatic control over the behavior, via its command-line options, which is both simpler and more robust.
While it would be far from trivial to detect whether a given external command is prompting for user input:
you can blindly send the presumptive responses,
which assumes that no situational variations are needed (except if a particular calls happens not to prompt at all, in which case the input is ignored).
Let's assume the following batch file, foo.cmd, which puts up 2 prompts and echoes the input:
#echo off
echo begin
set /p "input1=prompt 1: "
echo [%input1%]
set /p "input2=prompt 2: "
echo [%input2%]
echo end
Now let's send responses one and two to that batch file:
C: PS> Set-Content tmp.txt -Value 'one', 'two'; ./foo.cmd '<' tmp.txt; Remove-Item tmp.txt
begin
prompt 1: one
[one]
prompt 2: two
[two]
end
Note:
For reasons unknown to me, the use of an intermediate file is necessary for this approach to work on Windows - 'one', 'two' | ./foo.cmd does not work.
Note how the < must be represented as '<' to ensure that it is passed through to cmd.exe and not interpreted by PowerShell up front (where < isn't supported).
By contrast, 'one', 'two' | ./foo does work on Unix platforms (PowerShell Core).
You can store the SVN command line output into a variable and parse through that and branch as you desire. Each line of output is stored into a new enumerator (cli output stored in PS variables is in array format)
$var = & svn merge $target
$var

Fish Shell: Conditional execution based on $status?

In the fish shell the syntax for conditionals is hard to find. Does anyone have a link to an explanation of how to write an if, with ands and ors?
In particular I would like to write
if not $status
do a command
end
To do a command when the previous command returned a non-success. How do I do that?
See http://fishshell.com/docs/current/commands.html#if and http://fishshell.com/docs/current/tutorial.html#tut_conditionals.
Fish's if structure looks like this:
if COMMAND
# do something if it succeeded
else
# do something if it failed ($status != 0)
end
Then there are also the not, and and or commands, that you can use like
if not COMMAND1; or COMMAND2
# and so on
If you really want to test a variable (e.g. $status), you need to use test as the command, like
if test $status -eq 0
Do keep in mind that $status changes after every command, so if you need to use the status of an earlier command (common in prompts) you need to do what Joachim Pileborg said, save it to another variable.
Also, test has some issues with quotes (because it's one of the few parts of fish to adhere to POSIX) - if in test $foo -eq 0 $foo is undefined, test will error out, and if it is undefined in test -n $foo, the test will be true (because POSIX demands that test with one argument be true).
As a sidenote, in fish versions before 2.3.0, you need to add begin and end around a condition with and or or because it was interpreted weirdly.
So you'd have to do
if begin COMMAND; or COMMAND2; end
# do something for status = 0
The shortest short form would be
the_previous_command; or do_a_command
# ..................^^^^^
Assuming you get your $status from "the_previous_command"
I use the status variable to display it on the prompt if it's non-zero. For that I use the following function:
function __pileon_status_prompt
set -l __status $status
if test $__status != 0
printf '[%s%s%s]' (set_color red) $__status (set_color normal)
end
end
As you can see I set a local variable to the value of $status and the check that variable in the condition.

Variables may not be used as commands

Using fish shell, I'm writing very simple script that checks the command execution
#!/usr/bin/fish
command
if $status
echo "Oops error"
else
echo "Worked OK"
#...
end
And get the error message:
fish: Variables may not be used as commands. Instead, define a function like “function status; 0 $argv; end”. See the help section for the function command by typing “help function”.
The message looks pretty straight forward but no "defining function like..." nor "help function" helps solving the problem.
There is also a 'test' command, that sounds promising. But docs say it is to be used to check files...
How this simple thing should be done with fish shell?
Heh... And why all documentation is SO misleading?..
P.S. Please, don't write about 'and' command.
Fish's test command currently works exactly like POSIX test (i.e. the one you'll find in bash or similar shells). It has a couple of operations, including "-gt", "-eq", "-lt" to check if a number is bigger, equal or less than another number, respectively.
So if you want to use test, you'll do if test $status -eq 0 (a 0 traditionally denotes success). Otherwise, you can check the return value of a command by putting it in the if clause directly like if command (which will be true if the command returns 0) - that's what fish is trying to do here, which is why it complains about a variable being used in place of a command.