Shaggydog
Shaggydog

Reputation: 3798

Using output from a PowerShell command in a windows batch file

I have a path in variable (script parameter) %2. I need to do the following:

  1. Extract the leaf (last folder from the path) to a variable.
  2. Run the following command: robocopy %2 \\somepath\%leaf

I was told this could be done in PowerShell (cause I've tried going with batch file alone and failed miserably) Here's a pseudocode representation of what I'd like to achieve:

set leaf = powershell -command (split-path %2 -leaf)
robocopy %2 \\somepath\%leaf

Any idea how to write this correctly? Thank you.

Upvotes: 1

Views: 4715

Answers (2)

rojo
rojo

Reputation: 24476

Whenever you want to set a batch variable to the output of a command, use for /f. Here's an example:

@echo off
setlocal

set "psCommand=powershell -command "(split-path '%~2' -leaf)""
for /f "delims=" %%I in ('%psCommand%') do set "leaf=%%I"

echo %leaf%

But this is a terribly inefficient way to retrieve the last folder of a path. Instead of invoking PowerShell, what you should do is this:

@echo off
setlocal

for %%I in ("%~2") do set "leaf=%%~nxI"

echo %leaf%

The %%~dpnxI notation gets

  • d = drive
  • p = path
  • n = name
  • x = extension

It's traditionally intended for files, rather than directories; but it works just as well for directories anyway. See the last couple of pages of for /? in a console window for complete details.

Upvotes: 2

Magoo
Magoo

Reputation: 80203

FOR %%a IN ("%~2") DO FOR %%b IN ("%%~dpa.") DO ECHO %%~nxb

Batch one-liner. Take the parameter (second parameter here), remove any quotes and re-apply them. Select the drive and path, add '.' then select the name and extension of the result making leaf required.

Obviously, if you require this in a variable,

FOR %%a IN ("%~2") DO FOR %%b IN ("%%~dpa.") DO set "leaf=%%~nxb"

Upvotes: 0

Related Questions