How can I send a batch variable to a powershell command

牧云@^-^@ 提交于 2021-01-07 03:02:59

问题


I don't know how to fix it...

I'm trying to move random files from one folder to another but I want so I can determine the folders inside the batch file but when I run the batch file it doesn't work and if I change the %var% manual from editing the batch file it's working.

I'm sorry if this is a simple question but I'm kinda new to batch and still learning.

@echo off

set /p var1=Enter first dir:
set /p var2=Enter second dir:

::Var (Folder Directory)

echo %var1%
echo %var2%

powershell -Command "& {%var1% | Get-Random -Count 5 | Copy-Item -Destination %var2%}"

pause

回答1:


Use $env:var in PowerShell

@echo off & cd /d "%~dp0"

set /p "var1=Enter first dir: "
set /p "var2=Enter second dir: "

echo %var1% & echo %var2%

powershell -nop -c "ls $env:var1 | Get-Random -Count 5 | Copy-Item -Destination $env:var2"

pause



回答2:


There's no reason access those variables from within PowerShell itself, as they are parsed/expanded by cmd.exe before being passed to it.

The biggest issues with your shown method, is that you should use Get-ChildItem, (gci, dir, ls), to list the items in %var1%, and enclose your variables within single quotes, or escaped doublequotes, to ensure they are understood to be valid strings.

%__AppDir__%WindowsPowerShell\v1.0\powershell.exe -NoProfile "Get-ChildItem \"%var1%\" -File -Force | Get-Random -Count 5 | Copy-Item -Destination \"%var2%\""


来源:https://stackoverflow.com/questions/65453227/how-can-i-send-a-batch-variable-to-a-powershell-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!