问题
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