LoginSignup
0
2

PowerShellのps1ファイルにC#のコードを埋め込んで実行してみる

Last updated at Posted at 2024-05-31

例1

PowerShellスクリプト例
$source = @"
public static class Proto
{
    public static void Function()
    {
        System.Console.WriteLine("Call!!");
    }
}
"@

# C#のコードをビルドする
Add-Type -TypeDefinition $source -Language CSharp

# 指定したクラスのメソッドを呼び出す
[Proto]::Function()

例2

PowerShellスクリプト例
Add-Type-TypeDefinition @"
using System;
using System.Runtime.Interopservices;

public static class User Input {
    [D11Import("user32.d11")]
    public static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);

    public struct LASTINPUTINFO{
        public uint cbsize;
        public uint dwTime;
    }
}
"@ -Language CSharp

function Get-IdleTime {
    $lastInput = New-Object UserInput+LASTINPUTINFO
    $lastInput.cbsize =[System.Runtime.InteropServices.Marshal]::Sizeof([Type]$lastInput.GetType())
    $result = [UserInput]::GetLastInputInfo([ref]$lastInput)
    
    if ($result) {
        $lastInputTime = $lastInput.dwTime
        $idleTime = [Environment]::TickCount - $lastInputTime
        return $idletime / 1000 # convert milliseconds to seconds
    } else {
        throw "Unable to get last input info"
    }
}

#Settings
$idleThreshold = 360 # 6minutes
$screensaverPath = "C:\Windows\System32\"

# Main loop
while ($true) {
    Start-Sleep -Seconds 10
    idelTime -Get-IdleTime
    if ($idleTime -ge $idleThreshold) {
        Start-Process $screensaverPath
        While ($true) {
            Start-Sleep -Seconds 1
            $idleTime = Get-IdleTime
            if ($idleTime -lt 2) {# Assume any input interrupts the screensaver
                break;
            }
        }
    }
}

参考

https://www.tetsuyanbo.net/tetsuyanblog/41825
https://ktts.hatenablog.com/entry/2021/04/02/005818

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2