我有這個腳本(見下文),我想要:
- 在“PSComputerName”列的輸出檔案中包含服務器名稱
- 兩個檔案,一個是禁用的任務,一個是啟用的任務
$ComputerName = Invoke-Expression -Command 'hostname'
$FilePathEnabled = "c\temp" $ComputerName "-EnabledTasksResult.csv"
$FilePathDisabled = "c\temp" $ComputerName "-DisabledTasksResult.csv"
(Get-ScheduledTask).where{!($_.TaskPath -like "\Microsoft\*") -and !($_.Status -eq "Disabled")} | Get-ScheduledTaskInfo |
Export-Csv -NoTypeInformation -Path $FilePathEnabled
(Get-ScheduledTask).where{!($_.TaskPath -like "\Microsoft\*") -and !($_.Status -ne "Disabled")} | Get-ScheduledTaskInfo |
Export-Csv -NoTypeInformation -Path $FilePathDisabled
誰能幫幫我?謝謝
uj5u.com熱心網友回復:
首先對您的代碼進行一些評論:
- 創建檔案路徑,最好使用
Join-Path組合元素或.Net方法[IO.Path]::Combine() - 你忘記了驅動器號后面的冒號
"c\temp" - 在變數中獲取計算機名的最簡單方法是使用環境:
$env:COMPUTERNAME而不是Invoke-Expression -Command 'hostname' Status應該是State(至少在我的 Win10 機器上..)
接下來,我將首先收集所有任務,無論是否啟用,然后從該集合中過濾出啟用和禁用的任務。這使您免于運行Get-ScheduledTaskcmdlet 兩次。
$ComputerName = $env:COMPUTERNAME
$FilePathEnabled = Join-Path -Path 'c:\temp ' -ChildPath "$ComputerName-EnabledTasksResult.csv"
$FilePathDisabled = Join-Path -Path 'c:\temp ' -ChildPath "$ComputerName-DisabledTasksResult.csv"
$allTasks = (Get-ScheduledTask).Where{$_.TaskPath -notlike "\Microsoft\*"}
# filter and export the Enabled tasks
$allTasks.Where{$_.State -ne 'Disabled'} | Get-ScheduledTaskInfo |
Select-Object *, @{Name = 'PSComputerName'; Expression = {$ComputerName}} -ExcludeProperty PSComputerName |
Export-Csv -Path $FilePathEnabled -NoTypeInformation
# filter and export the Disabled tasks
$allTasks.Where{$_.State -eq 'Disabled'} | Get-ScheduledTaskInfo |
Select-Object *, @{Name = 'PSComputerName'; Expression = {$ComputerName}} -ExcludeProperty PSComputerName |
Export-Csv -Path $FilePathDisabled -NoTypeInformation
uj5u.com熱心網友回復:
In order to include the computer name in the output, you could use the select-object to create a custom object with the added property as follow:
Get-ScheduledTaskInfo | Select-Object *,@{Name = 'PSComputerName'; Expression = {$ComputerName}}
So you code will be something like that
$ComputerName = Invoke-Expression -Command 'hostname'
$FilePathEnabled = "c:\temp\" $ComputerName "-EnabledTasksResult.csv"
$FilePathDisabled = "c:\temp\" $ComputerName "-DisabledTasksResult.csv"
(Get-ScheduledTask).where{!($_.TaskPath -like "\Microsoft\*") -and !($_.Status -eq "Disabled")} | Get-ScheduledTaskInfo | Select-Object *,@{Name = 'PSComputerName'; Expression = {$ComputerName}}
Export-Csv -NoTypeInformation -Path $FilePathEnabled
(Get-ScheduledTask).where{!($_.TaskPath -like "\Microsoft\*") -and !($_.Status -ne "Disabled")} | Get-ScheduledTaskInfo | | Select-Object *,@{Name = 'PSComputerName'; Expression = {$ComputerName}}
Export-Csv -NoTypeInformation -Path $FilePathDisabled
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/423103.html
標籤:
