脚本.bat来移动文件

问题描述 投票:0回答:1

我正在使用

cmd.exe
powerShell.exe
命令编写批处理脚本,以将安装文件夹中的
.txt file
(由第三方软件创建)复制到另一个位置。

主要问题是,当我运行

.bat
文件并复制该文件时,生成的副本内容不同,它掺假了原始内容。

代码如下:

@echo off
set "origin_folder=C:\Program Files (x86)\PaperCut Print Logger\logs\"
set "destiny_folder=L:"

rem takes the most recent file
for /f "delims=" %%I in ('powershell -Command "& {Get-ChildItem '%origin_folder%' | Sort-Object LastWriteTime -Descending | Select-Object -First 1}"') do (
    set "recent_file=%%I"
)

if not defined recent_file (
    echo No file found
    exit /b 1
)

rem Gets computer name
for /f "delims=" %%a in ('hostname') do set "computer_name=%%a"

rem Gets date
for /f "tokens=1-2 delims=/" %%a in ('echo %date%') do (
    set "month=%%b"
    set "day=%%a"
)

rem Assembly file's name
set "new_name=%computer_name%_%day%-%month%.txt"

rem Moves the most recent file to the destiny folder
move "%recent_file%" "%destiny_folder%"

echo Successfully moved: %recent_file% -> %destiny_folder%\%new_name%

内容预计是一个数字,但我得到......

Successfully moved: %recent_file% -> %destiny_folder%

...其内容(%% 填充)。我尝试排除这一行,但代码什么也没做。

windows powershell batch-file cmd
1个回答
0
投票

使用 PowerShell 完成这一切怎么样?当您确信文件将被正确移动时,请从

-WhatIf
命令中删除
Move-Item

$OriginFolder = Join-Path -Path "$Env:ProgramFiles(x86)" -ChildPath 'PaperCut Print Logger' -AdditionalChildPath 'logs'
$DestinyFolder = 'L:'
$FileToCopy = Get-ChildItem -Path $OriginFolder | Sort-Object -Property LastWriteTime -Descending | Select-Object -First 1
$ComputerName = $Env:COMPUTERNAME
$DateMark = Get-Date -Format 'ddMM'
$DestinationFile = "$ComputerName$DateMark.txt"
Move-Item -Path $FileToCopy.FullName `
    -Destination Join-Path -Path $DestinyFolder -ChildPath $DestinationFile" -WhatIf

如果您-必须-使用 .bat 文件:

@pwsh -NoProfile -NoLogo -File 'Move-PcLogFile.ps1'
© www.soinside.com 2019 - 2024. All rights reserved.