Echo equivalent in PowerShell for script testing - powershell

I would like to output variables and values out in a PowerShell script by setting up flags and seeing the data matriculate throughout the script.
How would I do this?
For example, what would be the PowerShell equivalent to the following PHP code?
echo "filesizecounter: " . $filesizecounter

There are several ways:
Write-Host: Write directly to the console, not included in function/cmdlet output. Allows foreground and background colour to be set.
Write-Debug: Write directly to the console, if $DebugPreference set to Continue or Stop.
Write-Verbose: Write directly to the console, if $VerbosePreference set to Continue or Stop.
The latter is intended for extra optional information, Write-Debug for debugging (so would seem to fit in this case).
Additional: In PSH2 (at least) scripts using cmdlet binding will automatically get the -Verbose and -Debug switch parameters, locally enabling Write-Verbose and Write-Debug (i.e. overriding the preference variables) as compiled cmdlets and providers do.

Powershell has an alias mapping echo to Write-Output, so you can use:
echo "filesizecounter : $filesizecounter"

PowerShell interpolates, does it not?
In PHP
echo "filesizecounter: " . $filesizecounter
can also be written as:
echo "filesizecounter: $filesizecounter"
In PowerShell something like this should suit your needs:
Write-Host "filesizecounter: $filesizecounter"

Write-Host "filesizecounter : " $filesizecounter

By far the easiest way to echo in powershell, is just create the string object and let the pipeline output it:
$filesizecounter = 8096
"filesizecounter : $filesizecounter"
Of course, you do give up some flexibility when not using the Write-* methods.

echo is alias to Write-Output although it looks the same as Write-Host.
It isn't What is the difference between echo and Write-Host in PowerShell?.
echo is an alias for Write-Output, which writes to the Success output stream. This allows output to be processed through pipelines or redirected into files. Write-Host writes directly to the console, so the output can't be redirected/processed any further.

The Write-host work fine.
$Filesize = (Get-Item $filepath).length;
Write-Host "FileSize= $filesize";

It should also be mentioned, that Set-PSDebug is similar to the old-school echo on batch command:
Set-PSDebug -Trace 1
This command will result in showing every line of the executing script:
When the Trace parameter has a value of 1, each line of script is traced as it runs. When the parameter has a value of 2, variable assignments, function calls, and script calls are also traced. If the Step parameter is specified, you're prompted before each line of the script runs.

PowerShell has aliases for several common commands like echo. Type the following in PowerShell:
Get-Alias echo
to get a response:
CommandType Name Version Source
----------- ---- ------- ------
Alias echo -> Write-Output
Even Get-Alias has an alias gal -> Get-Alias. You could write gal echo to get the alias for echo.
gal echo
Other aliases are listed here:
https://learn.microsoft.com/en-us/powershell/scripting/learn/using-familiar-command-names?view=powershell-6
cat dir mount rm cd echo move rmdir chdir erase popd sleep clear h ps sort cls history pushd tee copy kill pwd type del lp r write diff ls ren

I don't know if it's wise to do so, but you can just write
"filesizecounter: " + $filesizecounter
And it should output:
filesizecounter: value

Try Get-Content .\yourScript.PS1 and you will see the content of your script.
also you can insert this line in your scrip code:
get-content .\scriptname.PS1
script code
script code
....

Related

Powershell - Cat out string in different colors

Any advice or assistance would be greatly appreciated.
I am writing a simple base64 encoder for windows so I can encode strings faster when required.
The encoding happens in CMD and then the script opens a PowerShell in order to cat out the encoded string in the terminal.
For easier reading I am trying to change the color of the string that is retrieved with cat but am having a hard time achieving this. Here is a snippet of the code that is problematic:
certutil -encode data.txt tmp.b64 && findstr /v /c:- tmp.b64 > secret.b64
powershell.exe -Command "Write-Host Your secret is: -ForegroundColor Green";cat secret.b64
PAUSE
When the information is retrieved; "Your secret is: " is green as intended in the code but I cannot seem to find a way to color the "cat secret.b64" command.
As far as the original request goes, I suppose you wanted something like:
powershell -command "$i = cat secret.b64; Write-Host Your secret is: $i -ForegroundColor Green"
You can however skip powershell and do batch-file only.
#echo off
for /F %%a in ('echo prompt $E ^| cmd') do set "cl=%%a"
(certutil -encode data.txt tmp.b64 && findstr /v /c:- tmp.b64)>secret.b64
set /p secr=<secret.b64
echo Your secret is: %cl%[92m%secr%%cl%[0m
pause
Do it entirely in PowerShell; PS can call any console executables that CMD can. To take the stdout of a console executable and use it as string input to a PS cmdlet or function, either enclose the entire console executable's command in parens (e.g., $foocontent = (cat.exe foo)), or pipe it to a parameter of the PS cmdlet/function that accepts pipeline input (e.g., cat foo | Format-Table)
(Note that in PowerShell under Windows, cat is generally aliased to the PowerShell cmdlet Get-Content.)

PowerShell script does not receive arguments no matter what

Trying to pass a single command line argument to a powershell script on Windows 7, but the script does not seem to recognize any arguments. It blasts through the first lines below
foreach($arg in $args)
{
Write-Host "Arg: $arg";
}
without outputting anything that I use on the command line and fails due to $args[0] being empty. However the rest of my script works if I instead hardcode the value of the variable I am trying to assign from the command line (it simply opens that file and does something).
I was inspired by this answer Passing a variable to a powershell script via command line specifically by the link in the accepted answer, and tried using param block but that did not print out anything as well
param(
[string]$fileName
)
Write-Host "Filename: [ $fileName ]";
when invoked like script.ps1 -filename SampleFile.txt
When I simply copy/paste the first script from the link into a new script:
Write-Host "Num Args:" $args.Length;
foreach ($arg in $args)
{
Write-Host "Arg: $arg";
}
and call it as 1.ps1 1 2 3 its output is only Num Args: 0.
What am I doing wrong?
PS: If it matters, here is version information
PS Z:\> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
I don't think it has anything to do with file linking, or registry hacking! :)
When running the example code, I also get no return when using your code. But when you make the parameter MANDATORY, it starts to display the arguments. Just need to format the PARAM Correctly, as in:
Param( [Parameter(Mandatory=$True)]
[string]$argument_one
)
Write-Host "Hello World $argument_one"
There you have it. Now you can call it from CMD as in:
powershell.exe -command "& 'thePSFile.ps1' -$argument_one 'it works now'"
I hope this Helps. I know, resurrected from the dead, but I thought some other people searching could see how they were almost there.
//ark
I have this problem as well. It took a while to recover what I have done previously.
First approach: make sure assoc, ftype and %PATHEXT% are set for powershell:
C:\>assoc .ps1
.ps1=Microsoft.PowerShellScript.1
C:\>ftype Microsoft.PowerShellScript.1
Microsoft.PowerShellScript.1="C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -noexit -file %1 %~2
C:\>echo %PATHEXT%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.py;.pyw;.ps1
But this likely will not work in windows 7 or higher.
Then edit the registry (all cautions apply here)
Edit the registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\0\Command
Set it from
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-file" "%1"
To
"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-file" "%1" %~2
Good luck!

Pass argument into Powershell

I have a powershell script that completes some tasks in Active Directory and MS Exchange. I need to pass in the Active Directory username from our call logging system. Having the Call log system pass the argument is simple.
The problem i am facing is having powershell read the argument into a variable.
I will provide a proof of concept example.
Here is a sample command passing the argument into powershell.
C:\Users\UserName\Desktop\Test.ps1 -ADusername "Hello World"
Here is the sample script:
Param([string]$adusername)
$adusername
pause
I am Expecting the following output:
Hello World
Press Enter to continue...:
This is the actual output:
Press Enter to continue...:
Just wrapping my head around this core concept will help me immensely. I was unable to find any examples or tutorials that worked when applied to my scenario. I apologize if this is a duplicate post, couldnt find anything on this site as well.
EDIT: per request, this is my full script: http://pastebin.com/ktjpLQek
I think you will have much better luck if you avoid trying to use params and call the script exactly that way.
It is possible, but paramaters work better if you either inline the scriptfile like:
. .\scriptFile.ps1
function "Hello World"
Staying closer to what you are doing however, you should be using $args and calling PowerShell (the exe directly)
If you call your scriptfile like: (I used the runbox)
powershell c:\Path\Folder\Script.ps1 "Hello World!"
and then replace your Param([string]$adusername) with:
$adUserName = $args[0]
write-host $adUserName
Additionally, this should work for you (to dissect):
Param([string]$ad)
Write-Host $args[0]
Write-Host $ad
Read-Host
pause
Call the script with the path,
powershell c:\Path\Folder\Script.ps1 "Hello World!" $ad = "JSmith"
If this does not work, you should ensure that your execution policy is set correctly. Get-ExecutionPolicy will tell you the current level. For testing you can set it very low with Set-ExecutionPolicy unrestricted
Add the following to the top of your script.
Param(
[Parameter(Mandatory=$true)]
[string]$Euser
)
Write-Host "Deactivating $EUser"
Calling example after cd to the script directory
.\ScriptName.ps1 -Euser "FOO" # Tab auto completion works
The following in a new script works for me.
Param([string]$servers)
"You chose $servers"
PS C:\scripts> .\Untitled1.ps1 "this test"
You chose this test
PS C:\scripts>

Script echo current command in PowerShell

Suppose I'm running a PowerShell script that takes several input parameters. The command looks like:
psScript.ps1 -arg1 "arg1value" -arg2 "arg2value"
Is there a way to store this exact command in a variable within the script so that I can log it?
Specifically, I'd like to know what to assign to the variable $currentCommand:
$currentCommand = <something>
Write-Host "currently running script " $currentCommand
Such that the Write-Host output would be the exact command line used to invoke the script. If the script command was the same as above, for example, then the output would be:
currently running script psScript.ps1 -arg1 "arg1value" -arg2
"arg2value"
This may suit your needs:
Write-Host "currently running script " $myinvocation.Line
Reference
The $MyInvocation variable will have the information. Here is a good blog post about it.

How to pass command-line arguments to a PowerShell ps1 file

For years, I have used the cmd/DOS/Windows shell and passed command-line arguments to batch files. For example, I have a file, zuzu.bat and in it, I access %1, %2, etc. Now, I want to do the same when I call a PowerShell script when I am in a Cmd.exe shell. I have a script, xuxu.ps1 (and I've added PS1 to my PATHEXT variable and associated PS1 files with PowerShell). But no matter what I do, I seem unable to get anything from the $args variable. It always has length 0.
If I am in a PowerShell shell, instead of cmd.exe, it works (of course). But I'm not yet comfortable enough to live in the PowerShell environment full time. I don't want to type powershell.exe -command xuxu.ps1 p1 p2 p3 p4. I want to type xuxu p1 p2 p3 p4.
Is this possible, and if so, how?
The sample I cannot get to work is trivial, foo.ps1:
Write-Host "Num Args:" $args.Length;
foreach ($arg in $args) {
Write-Host "Arg: $arg";
}
The results are always like this:
C:\temp> foo
Num Args: 0
C:\temp> foo a b c d
Num Args: 0
c:\temp>
This article helps. In particular, this section:
-File
Runs the specified script in the local scope ("dot-sourced"), so that the functions and variables that the script creates are available in the current session. Enter the script file path and any parameters. File must be the last parameter in the command, because all characters typed after the File parameter name are interpreted as the script file path followed by the script parameters.
i.e.
powershell.exe -File "C:\myfile.ps1" arg1 arg2 arg3
means run the file myfile.ps1 and arg1 arg2 & arg3 are the parameters for the PowerShell script.
After digging through the PowerShell documentation, I discovered some useful information about this issue. You can't use the $args if you used the param(...) at the beginning of your file; instead you will need to use $PSBoundParameters. I copy/pasted your code into a PowerShell script, and it worked as you'd expect in PowerShell version 2 (I am not sure what version you were on when you ran into this issue).
If you are using $PSBoundParameters (and this ONLY works if you are using param(...) at the beginning of your script), then it is not an array, it is a hash table, so you will need to reference it using the key / value pair.
param($p1, $p2, $p3, $p4)
$Script:args=""
write-host "Num Args: " $PSBoundParameters.Keys.Count
foreach ($key in $PSBoundParameters.keys) {
$Script:args+= "`$$key=" + $PSBoundParameters["$key"] + " "
}
write-host $Script:args
And when called with...
PS> ./foo.ps1 a b c d
The result is...
Num Args: 4
$p1=a $p2=b $p3=c $p4=d
OK, so first this is breaking a basic security feature in PowerShell. With that understanding, here is how you can do it:
Open an Windows Explorer window
Menu Tools -> Folder Options -> tab File Types
Find the PS1 file type and click the advanced button
Click the New button
For Action put: Open
For the Application put: "C:\WINNT\system32\WindowsPowerShell\v1.0\powershell.exe" "-file" "%1" %*
You may want to put a -NoProfile argument in there too depending on what your profile does.
You could declare your parameters in the file, like param:
[string]$param1
[string]$param2
And then call the PowerShell file like so .\temp.ps1 param1 param2....param10, etc.
Maybe you can wrap the PowerShell invocation in a .bat file like so:
rem ps.bat
#echo off
powershell.exe -command "%*"
If you then placed this file under a folder in your PATH, you could call PowerShell scripts like this:
ps foo 1 2 3
Quoting can get a little messy, though:
ps write-host """hello from cmd!""" -foregroundcolor green
if you want to invoke ps1 scripts from cmd and pass arguments without invoking the script like
powershell.exe script.ps1 -c test
script -c test ( wont work )
you can do the following
setx PATHEXT "%PATHEXT%;.PS1;" /m
assoc .ps1=Microsoft.PowerShellScript.1
ftype Microsoft.PowerShellScript.1=powershell.exe "%1" %*
This is assuming powershell.exe is in your path
https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/ftype
You may not get "xuxu p1 p2 p3 p4" as it seems. But when you are in PowerShell and you set
PS > Set-ExecutionPolicy Unrestricted -Scope CurrentUser
You can run those scripts like this:
./xuxu p1 p2 p3 p4
or
.\xuxu p1 p2 p3 p4
or
./xuxu.ps1 p1 p2 p3 p4
I hope that makes you a bit more comfortable with PowerShell.