I have a batch file that is supposed to execute a powershell
script and I also want pass a file path to the script out of the batch file. The file path should then be inserted at a certain point in the script.
$Berechtigung = Get-ACL -Path "C:\_TEST\TEST.txt"
do you have any ideas?
CodePudding user response:
From a batch file (
cmd.exe
), you must call the Windows PowerShell CLI,powershell.exe
, in order to execute a PowerShell script (.ps1
), optionally with arguments, via the-File
parameter.In your PowerShell script, you can refer to arguments passed by the caller:
- either: purely positionally, via the automatic
$args
variable, where$args[0]
contains the first argument,$args[1]
the second, and so on. - or: via declared parameters, such as
param([string] $Path)
- see the relevant section of the conceptual about_Functions help topic.
- either: purely positionally, via the automatic
Therefore:
Assuming your PowerShell script is named foo.ps1
and contains the following content:
# Content of foo.ps1
param([string] $Path) # Declare a string parameter named -Path
$Berechtigung = Get-ACL -Path $Path
You can then call this script from your batch file as follows (this assumes that foo.ps1
is located in the current directory - adjust as needed):
@echo off
:: ...
powershell.exe -NoProfile -File .\foo.ps1 "C:\_TEST\TEST.txt"
Note that if you declare parameters (with param(...)
) you can also pass your arguments as named ones, namely by placing the target parameter name before an argument:
:: Note the -Path before the file path.
:: Only works if you have declared this parameter via param(...)
powershell.exe -NoProfile -File .\foo.ps1 -Path "C:\_TEST\TEST.txt"