翻译批处理脚本PowerShell脚本 [英] Translate batch script to Powershell script

查看:348
本文介绍了翻译批处理脚本PowerShell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有这个剧本我运行一个计划任务:

I currently have this script I run as a scheduled task:

@echo on
START /WAIT c:\windows\system32\Robocopy.exe "D:\folder" "\\192.168.2.87\folder" /E /MT:20 /R:50 /W:10 /V /ETA /LOG:c:\robocopy.txt

我想转换并运行此作为一个PowerShell脚本,因为两个原因:

I want to convert and run this as a PowerShell script because of two reasons:


  • 更现代

  • 的最重要的原因是我想要的日志日期和时间存储为 C:\\ robocopylog3004201510214043.txt ,我发现从字面上就如何剥离没有信息字符,如:和/从批处理脚本,我知道的PowerShell可以

  • Its more modern
  • The most important reason is that I want to store the log with date and time as C:\robocopylog3004201510214043.txt and I am literally finding no information on how to strip characters like ":" and "/" from a batch script and I know PowerShell can.

这是最后一个号码是不是随机的。它是日期和时间。

That last number is not random. It is the date and time.

日期的例子是30/04/2015(分拆它会离开30042015)
时间例子是10:21:40,43(分拆它会离开10214043)

Date for example is "30/04/2015" (striping it would leave 30042015) Time for example is "10:21:40,43" (striping it would leave 10214043)

因此​​,它会留下robocopylog3004201510214043.txt的文件名

So it would leave a file name of robocopylog3004201510214043.txt

推荐答案

有CMD和PowerShell相差不大,当涉及到运行外部程序。我建议使用调用运算符(&安培; ),但是,即使它是不是在这种特殊情况下强制

There is little difference between CMD and PowerShell when it comes to running external programs. I'd recommend using the call operator (&), though, even if it isn't mandatory in this particular case.

& c:\windows\system32\Robocopy.exe "D:\folder" "\\192.168.2.87\folder" /E /MT:20 /R:50 /W:10 /V /ETA /LOG:c:\robocopy$(Get-Date -format 'ddMMyyyyHHmmss').txt

的Robocopy 运行同步,无论如何,所以没有等待所需的指令。

robocopy runs synchronously anyway, so no "wait" instruction required.

借助数字格式 ddMMyyyyHHmmss 生产由日,月,年,小时,分钟和秒时间戳。我不会建议包括毫秒为好,因为你可能不会在同一秒内,运行Robocopy几次。如果您必须包括毫秒,追加 FF 格式字符串(或˚F FFF 等等,取决于你所需要的位数)。您可能要考虑使用ISO日期格式( YYYYMMDDHHMMSS ),但是,因为它简化了在创造顺序列出的日志文件。

The number format ddMMyyyyHHmmss produces a timestamp consisting of day, month, year, hour, minutes and seconds. I wouldn't recommend to include milliseconds as well, because you probably won't run robocopy several times within the same second. If you must include milliseconds, append ff to the format string (or f, fff, etc., depending on the number of digits you need). You may want to consider using an ISO date format (yyyyMMddHHmmss), though, because that simplifies listing the log files in creation order.

至于在批处理脚本替换字符,可通过<一个完成href=\"http://blogs.msdn.com/b/joshpoley/archive/2011/06/03/batch-file-string-substitution-with-nested-environment-variables.aspx\"相对=nofollow>字符串替换的:

As for replacing characters in batch scripts, that can be done via string replacements:

C:\>echo %DATE:/=%
30042015

C:\>echo %TIME::=_%
10_01_22.39

这篇关于翻译批处理脚本PowerShell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆