Powershell 脚本 - 在设置空闲时间后关闭电脑

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

我必须编写一个 PowerShell 脚本,该脚本将通过部署软件从晚上 9 点到凌晨 4 点每小时自动发送一次。该脚本应该找出 PC 空闲的时间,如果空闲时间为 3 小时甚至更长,则设备会在没有任何警告的情况下关闭(基本上是强制关闭)。 我从这个用户那里找到了这个脚本:PowerShell Idle Time of Remote Machine using Win32 API GetLastInputInfo。该脚本的作用是,它基本上显示设备空闲时间的 10 倍。 我通过插入“If”方法更改了代码的末尾。 这是我的脚本:

Add-Type @'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace PInvoke.Win32 {

    public static class UserInput {

        [DllImport("user32.dll", SetLastError=false)]
        private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

        [StructLayout(LayoutKind.Sequential)]
        private struct LASTINPUTINFO {
            public uint cbSize;
            public int dwTime;
        }

        public static DateTime LastInput {
            get {
                DateTime bootTime = DateTime.UtcNow.AddMilliseconds(-Environment.TickCount);
                DateTime lastInput = bootTime.AddMilliseconds(LastInputTicks);
                return lastInput;
            }
        }

        public static TimeSpan IdleTime {
            get {
                return DateTime.UtcNow.Subtract(LastInput);
            }
        }

        public static int LastInputTicks {
            get {
                LASTINPUTINFO lii = new LASTINPUTINFO();
                lii.cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO));
                GetLastInputInfo(ref lii);
                return lii.dwTime;
            }
        }
    }
}
'@


for ( $i = 0; $i -lt 10; $i++ ) {
    $Idle = [PInvoke.Win32.UserInput]::IdleTime
    if ($Idle.Hours -eq "3"){
    shutdown -r -t 1
    else
        Out-Null}
}

不幸的是,如果我通过我们的部署软件“PDQ”部署这个脚本,它不起作用。它甚至没有给出任何错误,所以我不知道为什么脚本不起作用。 我还尝试直接从电脑运行脚本并写下

if ($Idle.Minutes -eq "0"){
。 由于空闲时间确实为 0,因此它会自动重新启动整个机器(而不是关闭它,是吗?)。 有人知道另一种方法吗?或者我在脚本中遗漏了一些代码? 我感谢任何帮助!

powershell deployment automation shutdown idle-processing
1个回答
0
投票

在您的

for
块中,我看到
else
块包含在您的
if
块中,因此您可能需要修复该问题。

此外,如果您查看关闭参数 (

shutdown /?
),您会注意到
-r
参数将关闭 重新启动计算机。我认为
/s
参数就是您所需要的。

© www.soinside.com 2019 - 2024. All rights reserved.