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.
Related
I have a powershell Script that runs fine in the ISE, but when I run it directly from the .ps1 file it stops at this point:
Write-Host "Attempting to start FFMPEG Process with arguments:$ArgumentList::::" -ForegroundColor Green
Start-Process $SCRIPT:FFMPEGLocation $ArgumentList -Wait
I get the Write-Host printout, with the correct Argument List, but no window pops up for the start-process or anything. I made sure to use the SCRIPT scope variable for anything that is outside the function. It runs fine in ISE just not when I run it in Console. No errors either, and the $SCRIPT:FFMPEGLocation variable is a direct path to the exe to be executed.
Any help would be greatly appreciated, and if you need more let me know.
PSVersion 5.1.14393.1066
OSVersion 10.0.14393
As per comments, check the value passed to Start-Process to ensure it contains what you expect as the issue is likely to be with $SCRIPT:FFMPEGLocation.
The difference between the ISE and Console with regard to scope can be frustrating.
See this SuperUser post which explains the behaviour further
. You may also find this post helpful;
BartekB explains that F5 in the ISE actually dot-sources the script instead of calling it, and provides a function to run a clean session.
An alternative method which will also wait on the process that needs to be run:
& $EXE /arg 1 /arg 2 -etc 2>&1 | % { $_ }
This will execute the command and pass the args, redirect any errors to the output stream and then print that output (for some reason, I've had bad luck with actually getting output from commands)
For running ps1 file I should type something like:
powershell "./script.ps1 -t 'Param string'"
But the running of bat-file has much more kindly view:
script 'Param string'
Is it possible to simplify the syntax to run a ps1 file? It should be comfortable for typing from keyboard.
Since you are tagged the question with PowerShell only, I assume you want to call a ps1 from Powershell.
Consider a script printing a message, called message.ps1:
Param
(
$msg
)
Write-Host $msg
The way I used to call it is:
.\message.ps1 -msg "hello"
You can also omit the -msg prefix and just pass the string to print:
.\message.ps1 "hello"
It seems the most easy way to solve my question is calling ps1 script from bat script.
Then the string powershell "./script.ps1 -t 'Param string'"
could be easy represented as script 'Param string'
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!
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>
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
....