Execute bat file from same folder - powershell

I have a Bat file with
"C:\Program Files (x86)\Jenkins\jre\bin/java" -jar "C:\Program Files (x86)\Jenkins/war/web-inf/jenkins-cli.jar" -s "http://localhost:8080" create-job "buildjob" < "config.xml"
"C:\Program Files (x86)\Jenkins\jre\bin/java" -jar "C:\Program Files (x86)\Jenkins/war/web-inf/jenkins-cli.jar" -s "http://localhost:8080" safe-restart
"C:\Program Files (x86)\Jenkins\jre\bin/java" -jar "C:\Program Files (x86)\Jenkins/war/web-inf/jenkins-cli.jar" -s "http://localhost:8080" build buildjob -p "Path=/" -w -s
I couldn't get this running directly in PowerShell, so I put it into a bat file in the same folder as the script and added
cmd.exe /c 'ConfigureJenkinsJob.bat'
But that gives an error that the system couldn't find the specified file.

The command is trying to run the batch file from the current working directory, which isn't necessarily the same folder in which the scripts reside. If you need to run another script from the same folder, use the $MyInvocation automatic variable to determine the parent folder:
$dir = Split-Path -Parent $MyInvocation.MyCommand.Path
cmd.exe /c "$dir\ConfigureJenkinsJob.bat"
Instead of using cmd /c you could also simply use the call operator (&), since batch files can be run directly from PowerShell:
$dir = Split-Path -Parent $MyInvocation.MyCommand.Path
& "$dir\ConfigureJenkinsJob.bat"

Related

How to change the current directory using .bat file in Windows PowerShell?

I am learning Windows PowerShell and I am struggling with the very basic task, how to create a .bat file to change the current directory? The simple .bat file with cd mydir inside worked well using cmd.exe, but it does not work in PowerShell:
PS C:\Users\ET\test> dir
Directory: C:\Users\ET\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 01/10/2021 10:57 mydir
-a---- 01/10/2021 10:58 10 changeDir.bat
PS C:\Users\ET\test> type changeDir.bat
cd mydir
PS C:\Users\ET\test> .\changeDir.bat
C:\Users\ET\test>cd mydir
PS C:\Users\ET\test>
You see that my current directory has not changed after executing the .bat file.
Works as expected using cmd.exe:
C:\Users\ET\test>changeDir
C:\Users\ET\test>cd mydir
C:\Users\ET\test\mydir>
Because a batch file (.bat, .cmd) runs in a child process (via cmd.exe), you fundamentally cannot change PowerShell's current directory with it.
This applies to all calls that run in a child process, i.e. to all external-program calls and calls to scripts interpreted by a scripting engine other than PowerShell itself.
While the child process' working directory is changed, this has no effect on the caller (parent process), and there is no built-in mechanism that would allow a given process to change its parent's working directory (which would be a treacherous feature).
The next best thing is to make your .bat file echo (output) the path of the desired working directory and pass the result to PowerShell's Set-Location cmdlet.
# Assuming that `.\changeDir.bat` now *echoes* the path of the desired dir.
Set-Location -LiteralPath (.\changeDir.bat)
A simplified example that simulates output from a batch file via a cmd /c call:
Set-Location -LiteralPath (cmd /c 'echo %TEMP%')
If you're looking for a short convenience command that navigates to a given directory, do not use a batch file - use a PowerShell script or function instead; e.g.:
function myDir { Set-Location -LiteralPath C:\Users\ET\test\myDir }
Executing myDir then navigates to the specified directory.
You can add this function to your $PROFILE file, so as to automatically make it available in future sessions too.
You can open $PROFILE in your text editor or add the function programmatically, as follows, which ensures on-demand creation of the file and its parent directory:
# Make sure the $PROFILE file exists.
If (-not (Test-Path $PROFILE)) { $null = New-Item -Force $PROFILE }
# Append the function definition to it.
#'
function myDir { Set-Location -LiteralPath C:\Users\ET\test\myDir }
'# | Add-Content $PROFILE
try the following
$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
Write-host "running in directory $dir"
Actually, I found a way to start PowerShell in the directory I need. For that, I am using Windows Terminal app https://www.microsoft.com/en-gb/p/windows-terminal/9n0dx20hk701. I've configured the settings.json file this way:
"guid": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
"name": "PowerShell",
"source": "Windows.Terminal.PowershellCore",
"startingDirectory": "C:\\Haskell\\HaskellWikiBook"

How to convert PowerShell code for a batch file?

This code unblocks a OneDrive library, for the sake of security. The library is found in the C:\ODTool directory, and is downloaded form a GitHub online open project. It uses PowerShell to import a module, then run the command Get-ODStatus, to determine the sync status of OneDrive, outputting it to output.csv in the current directory.
PS C:\ODTool> Unblock-File -Path C:\ODTool\OneDriveLib.dll
Import-Module C:\ODTool\OneDriveLib.dll
Get-ODStatus > output.csv 2>&1
I need to convert this PowerShell script to an executable batch file command.
Create a txt file and add the following code:
#ECHO OFF
Powershell.exe -executionpolicy bypass -File <full path to ps1>
then save the file as a .bat

I can use cd command to open folder, but can not see folder both in cmd or explorer

When preparing to reinstall Windows OS, I use xcopy to backup a partition (driver letter D) to folder E:\Backup200407
Command line:
xcopy D:\ E:\Backup200407\ /E /C /Y
After copy, I can use cd command to open folder E:\Backup200407
But I can't see it with dir command, or open E:\ in explorer
dir

put a powershell script on path through powershell commands.

I have a powershell script that I want to run from cmd/ps any location by putting it in path.
What is the command that can achieve that ?
I m basically looking for a UNIX equivalent of putting your script in bashrc and thus available from anywhere to run.
echo 'export PATH=$PATH:/path/to/script' >> ~/.bashrc && source ~/.bashrc
In windows you also have the system variable PATH that's used for defining where to locate executables.
You could do the following that should be equivalent assuming you're only using Powershell:
$newPath = "c:\tmp\MyScriptPath";
[Environment]::SetEnvironmentVariable('PATH', "$($env:Path);$newPath", [EnvironmentVariableTarget]::User);
# Update the path variable in your current session; next time it's loaded directly
$env:Path = "$($env:Path);$newPath";
You can then execute your script directly in Powershell with just the name of the script.
However_ : this will not work under cmd because cmd doesn't know how to handle the ps1 script as an executable. Normally one would execute the script from cmd by calling the following:
Powershell.exe -executionpolicy remotesigned -File C:\Tmp\Script.ps1
If this is "unacceptable" for you, the easiest way is to create a bat script along with your ps1 script (same path) and add the following content :
Script.bat (Assuming you have Script.ps1 in the same folder):
#ECHO OFF
PowerShell.exe -Command "& '%~dpn0.ps1'"
PAUSE
This will create the wrapper needed to Invoke Script anywhere in your cmd as batch files can be executed from cmd

Run Executable (with Support Files) In a Separate Directory

I'm attempting to run "AutoRun.exe" from an iso file mounted to DriveLetter:\
& "${DriveLetter}:\AutoRun.exe"
Using the above method I can properly tell PowerShell to run the executable, but it expects the support files (AutoRun.cfg, etc) to be in the place of execution (in this case my Desktop). I want this to be able to work no matter the location of the PowerShell script.
Any suggestions?
Change the working directory to whereever the required files are located. If they reside in ${DriveLetter}:\ change to that directory:
Set-Location "${DriveLetter}:\"
& "${DriveLetter}:\AutoRun.exe"
If they reside in the same folder as the PowerShell script change to that directory:
Set-Location (Split-Path -Parent $MyInvocation.MyCommand.Definition)
& "${DriveLetter}:\AutoRun.exe"
or (PowerShell v3 and newer):
Set-Location $PSScriptRoot
& "${DriveLetter}:\AutoRun.exe"