PMP Style .global

PMP Style .global

Software engineer page

MENU

Launch a PowerShell script on your network from a batch file

I will explain how to start a PowerShell script in the network from a batch file. Make it versatile enough to work wherever you place a PowerShell script and a startup batch file as a set.

f:id:ruruucky:20210325010305p:plain

Overview

There are two ways to specify the file path. One is the format from the MS-DOS era. This method is limited to drives in the PC.

Drive name:\directory ...

The other is in the form of UNC (Universal Naming Convention) so that files on the network can also be accessed.

\\computer name\share name\directory ...


The batch file is a function of the command prompt, but the execution directory is limited to the old-fashioned MS-DOS method. Since the command prompt is an improved version of MS-DOS, it inherits the restrictions.

Commentary

Place the PowerShell script and its launch batch file on the server and launch it from the client.

\Server\share\test.bat
\Server\share\test.ps1

Contents of test.bat

PowerShell -ExecutionPolicy RemoteSigned test.ps1

The batch file cannot be started because the current directory cannot be set to \Server\share.

You can start it like this

PowerShell -ExecutionPolicy RemoteSigned \\Server\share\test.ps1

However, the full path is very ugly. If you set test.ps1 and test.bat as a set, I want to be able to freely deploy and start it both on the network and locally. Software engineers are a profession that sticks to such things :)

Solution 1 Network drive

Network drives allow you to mount network shares on virtual drives. If you use it, you can solve it like this

subst Z: \\server\share
PowerShell -ExecutionPolicy RemoteSigned z: \test.ps1
subst Z: /D

It can be solved, but there is a problem in terms of versatility. Someone may be using the Z drive. Creating drive allocation rules just for this is too exaggerated, and creating logic to search for free drives can be confusing.

Solution 2 Environment variables

The batch file has environment variables that can be used to refer to the path and arguments when it is started. Use %~dp0 in it.
You can get the path of the batch file with the file name removed from the full path.
For example, if you start \Server\share\test.bat, %~dp0 becomes \Server\share.

The completed system is here.

PowerShell -ExecutionPolicy RemoteSigned %~dp0\test.ps1

It was neatly organized. Now you can place PowerShell and the startup batch file as a set anywhere.