2

関数を使用し、ISE 内で正常に実行される次の PowerShell スクリプトがあります。

Get-ComputerSessions -Computer "localhost"

# ===========================================================================
# Functions
# ===========================================================================


Function Get-ComputerSessions {
<#
.SYNOPSIS
    Retrieves tall user sessions from local or remote server/s
.DESCRIPTION
    Retrieves tall user sessions from local or remote server/s
.PARAMETER computer
    Name of computer/s to run session query against.
.NOTES
    Name: Get-ComputerSessions
    Author: Boe Prox
    DateCreated: 01Nov2010
 
.LINK
 
https://boeprox.wordpress.org
 
.EXAMPLE
Get-ComputerSessions -computer "server1"
 
Description
-----------
This command will query all current user sessions on 'server1'.
 
#>
[cmdletbinding(
    DefaultParameterSetName = 'session',
    ConfirmImpact = 'low'
)]
    Param(
        [Parameter(
            Mandatory = $True,
            Position = 0,
            ValueFromPipeline = $True)]
            [string[]]$computer
            )
Begin {
    $report = @()
    }
Process {
    ForEach($c in $computer) {
        # Parse 'query session' and store in $sessions:
        $sessions = query session /server:$c
            1..($sessions.count -1) | % {
                $temp = "" | Select Computer,SessionName, Username, Id, State, Type, Device
                $temp.Computer = $c
                $temp.SessionName = $sessions[$_].Substring(1,18).Trim()
                $temp.Username = $sessions[$_].Substring(19,20).Trim()
                $temp.Id = $sessions[$_].Substring(39,9).Trim()
                $temp.State = $sessions[$_].Substring(48,8).Trim()
                $temp.Type = $sessions[$_].Substring(56,12).Trim()
                $temp.Device = $sessions[$_].Substring(68).Trim()
                $report += $temp
            }
        }
    }
End {
    $report
    }
}

ただし、powershell コマンド ラインからこれを実行しようとすると、次のエラーが発生します。

PS C:\Downloads\Powershell> C:\Downloads\Powershell\test.ps1
The term 'Get-ComputerSessions' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path
 is correct and try again.
At C:\Downloads\Powershell\test.ps1:25 char:21
+ Get-ComputerSessions <<<<  -Computer "localhost"
    + CategoryInfo          : ObjectNotFound: (Get-ComputerSessions:String) [], CommandNotFoundExc
   eption
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\Downloads\Powershell>

関数を別のモジュールに入れる必要がありますか?

私のバックグラウンドは VB スクリプトなので、ロジックを理解するのに苦労しています。

4

2 に答える 2

2

この通話を移動:

Get-ComputerSessions -Computer "localhost"

関数 Get-ComputerSession の定義の下に移動して、再試行してください。関数を定義する前に、PowerShell で関数呼び出しが発生しています。

于 2013-09-03T13:25:27.167 に答える