PowerShell 脚本的意外日志结果

PowerShell 脚本的意外日志结果

我有一个用于清除远程计算机数据的自动化脚本。该脚本运行良好,但我得到的报告输出为空白。我希望在报告中看到每行系统显示正或负结果。您能分享一些知识和经验吗?

虽然有点粗糙,但这是初稿。这是我的代码:

<##
Sets variables
##>
$Computers = Get-Content "C:\Tools\NodeScrub.txt"
$Day = (Get-Date).DayOfYear
$Year = get-date -format "MM-dd-yyyy"
$Date = "$Day.$Year"
$LogDir = "C:\Reports"

<##
Runs the command to delete all files older and "X" days
in the remote computers "C:\MGALFAUSER" folder.
The agreed upon history is anything older than 7 days.
The script is set to 8 days as a margin of safety.
##>

foreach ($Computer in $Computers) {Invoke-Command -Computername $Computer -ScriptBlock {Get-ChildItem "C:\MGALFAUSER\" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-8))} | Remove-Item -Recurse -Force -Confirm:$False} | Out-File -FilePath "$LogDir\$Date.txt" -Append -Force}

除了输出之外一切正常。我哪里搞砸了?

答案1

如果没有适当的作用域,您不能在远程调用中使用局部变量。所有代码都有作用域,其对象、属性等也一样。

about_Scopes

示例 5:在远程命令中使用本地变量

对于在本地会话中创建的远程命令中的变量,请使用“使用范围”修饰符。PowerShell 假定远程命令中的变量是在远程会话中创建的。

语法是:

$Using:<VariableName>

例如,以下命令在本地会话中创建一个 $Cred 变量,然后在远程命令中使用该 $Cred 变量:

$Cred = Get-Credential
Invoke-Command $s {Remove-Item .\Test*.ps1 -Credential $Using:Cred}

PowerShell 3.0 中引入了 Using 范围。在 PowerShell 2.0 中,若要指示在本地会话中创建了变量,请使用以下命令格式。

$Cred = Get-Credential
Invoke-Command $s {
  param($c)
  Remove-Item .\Test*.ps1 -Credential $c
} -ArgumentList $Cred

最佳实践:

简单字符串使用单引号。变量扩展或某些格式化用例则使用双引号。

所以,是这样的。

# Sets variables
$Computers  = Get-Content 'C:\Tools\NodeScrub.txt'
$Day        = (Get-Date).DayOfYear
$Year       = Get-Date -format 'MM-dd-yyyy'
$Date       = "$($Day).$($Year)"
$LogDir     = 'C:\Reports'

<#
Runs the command to delete all files older and "X" days
in the remote computers "C:\MGALFAUSER" folder.
The agreed upon history is anything older than 7 days.
The script is set to 8 days as a margin of safety.##>

foreach ($Computer in $Computers) 
{
    Invoke-Command -Computername $Computer -ScriptBlock {
        Get-ChildItem 'C:\MGALFAUSER' -Recurse | 
        Where-Object {($PSItem.LastWriteTime -lt (Get-Date).AddDays(-8))} | 
        Remove-Item -Recurse -Force
    } | Out-File -FilePath "$($Using:LogDir)\$($Using:Date.txt)" -Append -Force
}

您已经在执行 -Force 了,-confirm:false 是多余的。

相关内容