简体   繁体   English

将 Powershell 脚本传递给批处理文件

[英]Pass Powershell script to batch file

I'm trying to create a working PowerShell script.我正在尝试创建一个有效的 PowerShell 脚本。 However, it doesn't quite work correctly in the function, and we think it's because of the type of format.但是,它在 function 中不能正常工作,我们认为这是格式类型的问题。

Could you help me pass this function to a cmd/batch command?你能帮我把这个 function 传递给 cmd/batch 命令吗?

$datos = quser
foreach($id in $datos)
{
    $nom = ""
    $userid = $id -split '\s+'
    $ad = $userid[0].Replace(">","")
    if ($ad -eq $usuario)
    {
        $nom = $ad
        $userid[2]
    }
}

It is a function to get only the ID from the quser command utility.仅从quser命令实用程序获取 ID 是 function。

This PowerShell will output the active console session ID from quser.exe.这个 PowerShell 将 output 来自 quser.exe 的活动控制台 session ID。 Save to file Get-Qusers.ps1保存到文件 Get-Qusers.ps1

$pattern = '(?<username>.*?) {2,}(?<sessionname>.*?) {2,}(?<id>.*?) {2,}(?<state>.*?) {2,}(?<idletime>.*?) {2,}(?<logontime>.*?)$'
$quser = quser.exe

($quser | Select-String -Pattern $pattern ).Matches | Select-Object -Skip 1 | ForEach-Object {
    [PSCustomObject]@{
        Username    = $_.Groups['username'].Value.Trim() -replace '>'
        Sessionname = $_.Groups['sessionname'].Value
        Id          = $_.Groups['id'].Value
        State       = $_.Groups['state'].Value
        IdleTime    = $_.Groups['idletime'].Value
        LogonTime   = $_.Groups['logontime'].Value
    }
} |
    Where-Object { $_.Sessionname -eq 'console' } |
    Select-Object -ExpandProperty Id


To run the ps1 script in a batch file and save the Id to a variable在批处理文件中运行 ps1 脚本并将 Id 保存到变量

echo off
FOR /F "tokens=*" %%g IN ('powershell.exe -f get-qusers.ps1') do (SET QuserId=%%g)
echo %QuserId%

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM