【问题标题】:Power shell and .bat filePowershell 和 .bat 文件
【发布时间】:2020-11-05 21:32:47
【问题描述】:

因为我的power shell不太好,所以我想问一下如何管理这个任务。我已经创建了执行此操作的 .bat 文件:

echo before delete > delete.log

forfiles -p "C:\test1" -s -m *.* -d -0 -c "cmd /c echo @path" >> trace.log

forfiles -p "C:\test1" -s -m *.* -d -1 -c "cmd /c del @path" >> trace.log

echo preserved  >> trace.log

forfiles -p "C:\test1" -s -m *.* -d -0 -c "cmd /c echo @path" >> trace.log

我通过单独的 power shell 脚本成功发送了该 trace.log 的输出,如下所示:

$body = Get-Content -Path "C:\test1\trace.log" -Raw
Send-MailMessage -from doNotReply@company.com -to "nobody@company.com" -subject "Trace log delete status test" -body $body -smtpServer smtp.company.com

由于我对 power shell 的了解有限,有没有办法将 .bat 命令与我当前的 power shell 脚本合并?想法是像上面的示例一样执行删除操作,创建日志并在一个 power shell 脚本中通过电子邮件发送。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    试试这样:

    Write-Host "before delete" > delete.log
    (Get-ChildItem "C:\test1" -Recurse | 
        Select-Object -ExpandProperty Fullname) >>trace.log
    (Get-ChildItem "C:\test1" -Recurse | 
      Where-Object {$_.LastWriteTime -ge (Get-Date).addDays(-1)} |
        Remove-Item -Force) >>trace.log
    Write-Host "preserved"  >> trace.log
    (Get-ChildItem "C:\test1" -Recurse | 
        Select-Object -ExpandProperty Fullname) >>trace.log
    $body = Get-Content -Path "C:\test1\trace.log" -Raw
    Send-MailMessage -from doNotReply@company.com -to "nobody@company.com" -subject "Trace log delete status test" -body $body -smtpServer smtp.company.com
    

    【讨论】:

    • 现在我遇到了这个错误。ps1 无法加载,因为在这个系统上禁用了运行脚本。有关详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkID=135170 上的 about_Execution_Policies。我尝试了几种 Set-ExecutionPolicy 组合,但都失败了,有什么建议吗?
    • @user3391373 你应该更精确。 什么你到底尝试过,如何失败了。此外,stackoverflow 上有很多帖子解决了这个问题。
    【解决方案2】:

    @marsze 好的,抱歉,所以我像管理员用户一样运行 ISE 并执行了这一行 Set-ExecutionPolicy -Scope LocalMachine Unrestricted。比我在同一个会话中复制所有上述建议的代码并运行,我遇到了这个错误:

    Get-ChildItem : Access to the path 'C:\Program Files\Websense\Websense Endpoint\certutil' is denied.
    At line:8 char:2
    + (Get-ChildItem "C:\test1" -Recurse |
    +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (C:\Program File...dpoint\certutil:String) [Get-ChildItem], Unauth 
       orizedAccessException
        + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
     
    Get-ChildItem : Access to the path 'C:\Windows\CCM\ScriptStore' is denied.
    At line:8 char:2
    + (Get-ChildItem "C:\test1" -Recurse |
    +  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : PermissionDenied: (C:\Windows\CCM\ScriptStore:String) [Get-ChildItem], UnauthorizedA 
       ccessException
        + FullyQualifiedErrorId : 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 2013-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多