#
Perl for Win32

## System Module Extensions

### Conventions

The following conventions are used throughout this document.

- arguments:

argname a required argument.

[argname] an optional argument.

(out) argname an output argument, typically requires a reference for this argument.

- Return values

All methods and functions return TRUE on success. FALSE on failure or unless otherwise noted. If an error occurs the Perl built in variable, '$!' is set. A reference to '$!' as a string will return a string explaining the error.

- All classes contain a destructor DESTROY, that can be called to destroy objects. The destructor is called automaticly when the object goes out of scope. The destructor frees any System Objects associated with the Perl Object.

### Table of Contents

Win32::Process

Win32::Semaphore

Win32::IPC

Win32::Mutex

Win32::ChangeNotification

Win32::Eventlog

Win32::Registry

Win32::NetAdmin

Win32::File

Win32::Service

Win32::NetResource

### Win32::Process

- Functions
- Methods
- Examples

Functions

Create((out)$ProcessObj,$ApplicationName,$CommandLine,$InheritHandles,$CreateOptions,$CurrentDir)

(out)$ProcessObj
  Reference to a Process Object.
$ApplicationName
  Full path of executable module.
$CommandLine
  Command Line as seen by executable
$InheritHandles
  Flag for handle inheritance. 1=true, 0=false.
$CreateOptions
  Process creation flags. (see description below)
$CurrentDir
  Location of working directory for executable

The Create function acts as a constructor for the Process class. The executable module ($ApplicationName) is executed and passed $CommandLine. $CommandLine is the full command line for the new process.
To execute a perl script:
`$CommandLine = 'perl myscript.pl';`
The options for CreateOptions are:

    Option Name                Description
    CREATE_DEFAULT_ERROR_MODE  Give the new process
                               the default error mode.

    CREATE_NEW_CONSOLE         The new process has a
                               new console. This can't
                               be used with
                               DETACHED_PROCESS.

    CREATE_NEW_PROCESS_GROUP   The new process is the
                               root of a new process
                               group.

    CREATE_SEPARATE_WOW_VDM    The new process is run
                               in it's own Virtual Dos
                               Machine (VDM). Only
                               applicable to 16-bit
                               apps.

    CREATE_SUSPENDED           The primary thread of
                               the process is created
                               in a suspended state.
                               The process can be
                               started with the Resume
                               method below.

    CREATE_UNICODE_ENVIRONMENT The environment block
                               of the new process uses
                               UNICODE characters.

    DEBUG_PROCESS              The calling process is
                               treated as a debugger,
                               and the new process is
                               being debugged.

    DEBUG_ONLY_THIS_PROCESS    If the calling process
                               is being debugged, then
                               the new process will
                               not be debugged.

    DETACHED_PROCESS           The new process does
                               not have access to the
                               console of the calling
                               process.

Methods

Kill($ExitCode)

$ExitCode
  The Exit code that the process should return.

Kills the process.

Suspend()

Suspend the process.

Resume()

Resume a suspended process. This call can be used to resume a process that was created with the CREATE_SUSPENDED flag.

GetPriorityClass((out) $Priority)

(out)$Priority
  The priority class of the process.

SetPriorityClass($Priority)

$Priority
  The Priority to set the Process to.

The GetPriorityClass and SetPriorityClass methods allow control over the priority of the process. The $Priority can be one of

    PriorityClass        Description
    IDLE_PRIORITY_CLASS  Indicates a process whose
                         threads run only when the
                         system is idle. (ex: screensaver)

    NORMAL_PRIORITY_CLASS  Normal process scheduling.
    HIGH_PRIORITY_CLASS  Indicates a process that
                         performs time-critical
                         tasks that must be executed
                         immediately.

    REALTIME_PRIORITY_CLASS The highest process
                         priority, even pre-empts OS threads.

GetExitCode((out)$ExitCode);

(out)$ExitCode
  The exit code.

GetExitCode can be used to find out how or if a process has exited.

Wait($Timeout)

$Timeout
  The number of milliseconds to wait for process to end, for no timeout value, use INFINITE.

Wait for the process to exit. Wait returns FALSE if it times out. $! Is set to WAIT_FAILED in this case.

Example

            #'use' the process module.
            use Win32::Process;
            #theWin32:: module. Includes the Win32 error checking etc.
            # see Win32:: section for included functions.
            use Win32;

            sub Error
            {
               print Win32::FormatMessage(Win32::GetLastError());
            }

            #Create the process object.
            Win32::Process::Create($ProcessObj,  #object to hold process.
                                 "C:/winnt35/system32/Notepad.exe" #executable
                                 "Notepad temp.txt" #command line
                                 0,   #no inheritance.
                                 DETACHED_PROCESS, #separate process
                                 ".") || die &Error; #current dir.

            #Set the process priority
            $ProcessObj->SetPriority(NORMAL_PRIORITY_CLASS) || die &Error;

            #Wait for the process to end. NO timeout
            $ProcessObj->Wait(INFINITE) || die &Error;

            $ProcessObj->GetExitCode($ExitCode) || die &Error;
            print" Notepad exited with $ExitCode\n";

### Win32::Semaphore

- Functions
- Methods
- Examples

Functions

Create((out)$SemaphoreObj,$InitialCount,$MaxCount,$Name);

$SemaphoreObj
  Reference to a Semaphore Object.
$InitialCount
  The initial count of the semaphore object.
$MaxCount
  The maximum count of the semaphore.
$Name
  A string containing a name for the semaphore.

The Create Function creates a semaphore object and returns the reference in the $SemaphoreObj scalar. The semaphore is created with an initial value of $InitialCount. The maximum number of accesses allowed is set to $MaxCount.

Destroy($SemaphoreObj )

$SemaphoreObj
  Reference to a Semaphore Object.

The DESTROY Function destroys the Semaphore object. This method is automatically called by Perl when the $SemaphoreObject scalar goes out of scope.

Methods

Wait($TimeOut )

$TimeOut
  Time to wait (in Milliseconds)

The Wait method causes the calling process to wait on the Semaphore. If the Semaphore is not released in $TimeOut milliseconds, the call returns, and the return value should be checked. For no timeout value, use the predefined constant INFINITE.

Release($ReleaseCount ,(out) $lastCount)

$ReleaseCount
  Amount to increase Semaphore count

$LastCount
  Previous value of the Semaphore.

The Release Method releases a semaphore and increments the count by $ReleaseCount. The value of the Semaphore before the change is recorded in the $LastCount var.

Example

            use Win32::Semaphore;
            use Win32;

            Win32::Semaphore::Create($Sem,1,1,"Sem")||die &Error;
            #wait for access to the shared resource.

            if($Sem->Wait(INFINITE))
            {
                    #Access the shared resource here.
                    &Access($Shared_Resource);
                    $Sem->Release(1,$last);
            }
            else
            {
                    print"Could not get access to shared resource\n";
            }

### Win32::IPC

- Functions
- Examples

Functions

WaitForMultipleObjects(@objects , $WaitAll ,$TimeOut );

@objects
  #a list of object references.
$WaitAll
  #TRUE: wait for all objects. FALSE wait for first object to return.
$TimeOut;
  #timeout value in milliseconds.

The WaitForMultipleObjects is used to coordinate multiple events. The @objects array can hold objects of type: Semaphore, Mutex, Process, or ChangeNotification. If the $WaitAll var contains a true value (non zero) then the call waits for all of the objects, otherwise, it will return when the first object returns.

Example

            Win32::Semaphore::Create($Sem, 1,1,"Sem") || die $!;
            Win32::Mutex::Create($mut,0,"Mut") || die $!;
            #note: the WaitForMultipleObjects call is inherited, and
            # not referenced directly.
            Win32::Semaphore::WaitForMultipleObjects(($Sem,$mut),1, 10000) || die $!;

#### Implementation note

The IPC package is inherited by Win32::Process, Win32::Semaphore, Win32::ChangeNotification, and Win32::Mutex, it does not need to be implicitly 'use'd.

### Win32::Mutex

- Functions
- Examples

Functions

Create((out) $MutexObj, $InitialOwner,$Name)

$MutexObj
  Reference to a mutex object.
$InitialOwner
  Flag to indicate initial ownership.
$Name
  Name of mutex

Create creates a mutex object and returns the reference in $MutexObj. If the $InitialOwner flag is set (nonzero) then the process calling the Create function has immediate ownership of the mutex. Otherwise, the mutex is available. $Name can be used by other processes in the Win32::Mutex::Open call to create an object to reference an already created mutex.

Open($MutexObj, $Name)

(out)$MutexObj
  Reference to a mutex object.
$Name
  A string naming an already created mutex.

Open creates a mutex object to access an already Created mutex. The $Name must point to an already created object or this call will fail. Methods Release() Release relinquishes ownership of the mutex, allowing anyone Waiting on the mutex to take ownership.

Wait($TimeOut)

$TimeOut
  Time out for wait (in milliseconds).

Wait causes the calling process to wait for $TimeOut milliseconds for the ownership of the mutex. If the mutex doesn't come available before the timeout, the call returns false. To specifiy and infinite timeout, set $TimeOut to INFINITE.

Example

           #Create a mutex object
           Win32::Mutex::Create($Mut,0, "MyMutex")|| die $!;
           #Use it
           sub EnterArea
           {
                   local($mut) = @_;
                   $mut->wait(5000)||die $!;
                   #access away!!!
                   $mut->Release();
           }

### Win32::ChangeNotification

- Functions
- Methods
- Examples

Functions

FindFirst((out)$Object,$PathName,$WatchSubtree,$Filter)

(out)$Object
  ChangeNotification Object.
$PathName
  Path to directory to monitor
$WatchSubTree
  TRUE: notify for changes to subtree. FALSE-don't monitor subtree.
$Filter
  Specifies the filter conditions that satisfy a change notification wait. The FindFirst function creates a notification object, and returns the reference in $Object. $Filter can be one or more of the following:

    Filter Option                Description
    FILE_NOTIFY_CHANGE_FILE_NAME Any naming changes in the
                                 watched directory satisfy
                                 a change notification
                                 wait.  Changes include
                                 renames, deletions, and
                                 creations.

    FILE_NOTIFY_CHANGE_DIR_NAME  Any directory name
                                 changes.

    FILE_NOTIFY_CHANGE_ATTRIBUTES Any attribute changes

    FILE_NOTIFY_CHANGE_SIZE      Any file-size change.
                                 The notification only
                                 occurs when the change is
                                 written to disk. If disk
                                 IO is cached, the change
                                 occurs when the cache is
                                 flushed.

    FILE_NOTIFY_CHANGE_LAST_WRITE Any change to the last
                                 write time for a file.
                                 See above for notes on
                                 caching.

    FILE_NOTIFY_CHANGE_SECURITY  Any security descriptor
                                 changes in the directory.

Methods

FindNext();The FindNext method requests that the operating system signal the change notification object the next time it detects an appropriate change.

Close();Stops the notification object monitoring.

Wait($TimeOut)$TimeOut #time out in milliseconds. The Wait method causes the calling process to block until notification of the change.

DESTROY()The DESTROY method is called when the ChangeNotification object goes out of scope. This will close the notification.

Example

           Win32::ChangeNotification::FindFirst($cnobj,
                                 "d:/mydir/",1,"
                                 FILE_NOTIFY_CHANGE_FILE_NAME") || die $!;

           #Wait for the change.
           $cnobj->FindNext();
           $cnobj->Wait(INFINITE);

           #do something about the change.
           &Notify($Someone);
           $cnobj->Close;

### Win32::Eventlog

- Functions
- Methods
- Examples

Functions

Open((out)$EventObj, $SourceName, [$ServerName])

(out) $EventObj;
  Reference to an EventLog Object.
$SourceName;
  Name of the source of the event.
$ServerName;
  Optional: name of machine. If none, assumes local.

Open the eventlog on the specified machine, if no server is specified, the local machine is used. An Eventlog object is returned in $EventObj.

OpenBackup((out)$EventObj, $FileName, [$ServerName])

(out)$EventObj
  Reference to an Eventlog Object.
$FileName
  name of the file containing the backup eventlog.
$ServerName
  Optional: UNC name of the server containing the backup log.

Open a backup eventlog and return an object to control it. If $ServerName is not given the local machine is used.

Methods

Backup($filename)
  $filename
file to write the eventlog to.
Save the current open event log to a file

Read($ReadFlags,$RecordOffset,(out)%EventInfo)

(out) $ReadFlags
  Specifies how to read log
$RecordOffset
  Number of first record
(out)%EventInfo
  Event information
The Read method reads an entry from the eventlog. $ReadFlags can be any combination of:

    ReadFlag option              Description
    EVENTLOG_FORWARDS_READ       Eventlog is read in
                                 forward chronological
                                 order.

    EVENTLOG_BACKWARDS_READ      Eventlog is read in
                                 reverse chronological
                                 order.

    EVENTLOG_SEEK_READ           The read begins at the
                                 record specified by the
                                 $RecordOffset parameter.
                                 Must also specify

    EVENT_LOG_FORWARD_READ or
    EVENTLOG_BACKWARDS_READ.

    EVENTLOG_SEQUENTIAL_READ     The read continues
                                 sequentially from the
                                 last read call.

See the Report method for information on the %EventInfo hash. Report($Event, %EventInfo)

$Event
  A scalar defining the type of event.
%EventInfo
  A hash containing the event info.

Reports an event. Implicitly calls RegisterEventSource.

The options for $Event are:

    $Event Options                Description
    EVENTLOG_ERROR_TYPE           Error event
    EVENTLOG_WARNING_TYPE         Warning event
    EVENTLOG_INFORMATION_TYPE     Information event
    EVENTLOG_AUDIT_SUCCESS_TYPE   Success Audit event
    EVENTLOG_AUDIT_FAILURE_TYPE   Failure Audit event.

    %EventInfo contains the following:
    Key            Value
    Category       integer value for the category of the
                   event (app defined)

    EventID        ID value of the Event. Source specific,
                   any value.

    EventRawData   The Raw binary data

    Strings        Any text strings to merge

    user           user name.

GetOldest((out)$oldest) Returns the Absolute record number of the oldest record in the event log.

GetNumber((out)$NumberOfEvents) Returns the number of events.

Clear([ $filename ]) If the $filename option is given, then the current eventlog is written to the file Clears the event log.

Example 1

           use Win32::Eventlog;
           sub TEST1
           {
                   my $number, $EventLog;
                   OpenEventObj ($EventLog , "System") || die $!;
                   $EventLog->GetNumberOfEvents($number) || die $!;
                   print "There are $number records in the System Event Log\n";
           }

Example 2

           sub TEST2
           {
                   # define the event to log. my $number, $EventLog;
                   $Event =
                   {
                           'EventType' => ERROR;
                           'Category' => 0;
                           'EventID' => 0x1003;
                           'EventRawData' => NULL;
                           'Strings' =>"SampleApp";
                   }
                   # open the event log.
                   OpenEventObj($EventLog , "SamplApp") || die $!;
                   #report the event and check the error
                   $EventLog->ReportEvent(%$Event) || die $!;
           }

### Win32::Registry

- Methods
- Examples

methods

open((out)RegistryObj,$key)

(out)RegistryObj
  Reference to a reference object
$key
  Pre-defined key.

Open the specified registry key and create an object to access the key. If the specified key does not exist, it is not created.$Key can hold any already opened key. When the Registry module is loaded, four Registry objects are created in the main:: namespace. These predefined registry objects are:

- $HKEY_LOCAL_MACHINE
- $HKEY_USERS
- $HKEY_CURRENT_USER
- $HKEY_CLASSES_ROOT

create((out)$RegistryObj, $key )

$RegistryObj
  Reference to a registy object.
$key
  Name of a key.

If the key exists, then open it, otherwise create it. The User must have the security to create a key.

SetValue($subkey,$type,$value)

$subkey
  Name of subkey
$type
  Type of value
$value
  Value

Set the value of the subkey of the current key to be $value.

QueryValue((out)$value,(out)$type, $name)

(out)$value
  Value of var $name
(out)$type
  Type of var $name
$name
  Name of value to query.

Sets $value, and $type for the specific name value in the current key.

QueryKey((out)$class,(out)$NumberOfSubkeys,(out) NumberOfValues)

(out)$class
  Class of the key.
(out)$NumberOfSubkeys
  Number of subkeys of the current key.
(out)NumberOfValues
  Number of values in the current key.

Get the information from the current key.

GetKeys((out) \@Subkeys)

\@SubKeys
  A reference to a list to hold the subkeys.

Return a list of character strings representing subkeys of the current key.

GetValues((out)@Values )

Save($filename)

$filename
  File to save the current hive of the registry to.

Save registry from current location. Set the security attributes of the file to the

Load( $subkey, $filename)

$subkey
  The subkey to load the file into
$filename
  The file to load into the current key.

Load a registry file.

Example

           use Win32::Registry;
           $HKEY_LOCAL_MACHINE->Open($NewObj, "MyKey") || die $!;
           $NewObj->SetValue("MySubKey", REG_SZ, 5);

### Win32::NetAdmin

- Functions
- Examples

Functions

GetDomainController($server,$domain,(out)returnedName)

$server
  The server to request.
$domain
  The windows domain name.
(out)$returnedName
  The result.

Return the name of the domain controller for server

UserCreate($server, $userName, $password,$passwordAge,$privilege,$homeDir, $comment, $flags, $scriptPath)

$server
  The name of the server
$userName
  The name of the new user.
$password
  The users password
$PasswordAge
  Time before password expires.
$privilege
  The Privileges of the new user(see below for options)
$homeDir
  The home directory of the user.
$comment
  A relevant comment about the user.
$flag
  A flag controlling user creation (see below for options)
$scriptPath Pathname of the login script.

Creates a user on server with password, passwordAge, privilege,homeDir, comment, flags, and scriptPath

$Privilege options:

- USER_PRIV_MASK
- USER_PRIV_GUEST
- USER_PRIV_USER
- USER_PRIV_ADMIN

    $flag options:

- UF_TEMP_DUPLICATE_ACCOUNT
- UF_NORMAL_ACCOUNT
- UF_INTERDOMAIN_TRUST_ACCOUNT
- UF_WORKSTATION_TRUST_ACCOUNT
- UF_SERVER_TRUST_ACCOUNT
- UF_MACHINE_ACCOUNT_MASK
- UF_ACCOUNT_TYPE_MASK
- UF_DONT_EXPIRE_PASSWD
- UF_SETTABLE_BITS
- UF_SCRIPT
- UF_ACCOUNTDISABLE
- UF_HOMEDIR_REQUIRED
- UF_LOCKOUT
- UF_PASSWD_NOTREQD
- UF_PASSWD_CANT_CHANGE

UserDelete($server, $user)

$server
  The name of the server.
$user
  The name of the user to delete.

Deletes a user from server

UserGetAttributes($server, $userName, $password, $passwordAge,$privilege,$homeDir, $comment, $flags, $scriptPath)

$server
  The name of the server.
$userName
  The name of the user.
$password
  The user's password.
$passwordAge
  The time before the password expires.
$privilege
  The user's privilege.
$homeDir
  The user's home directory.
$comment
  The user's comment.
$flags
  Flags re: user's account.
$scriptPath
  Pathname of user's login script.

Gets password, passwordAge, privilege, homeDir, comment, flags,and scriptPath for user.

UserSetAttributes($server, $userName, $password, $passwordAge,$privilege, $homeDir, $comment, $flags, $scriptPath)

$server
  The name of the server.
$userName
  The name of the user.
$password
  The user's password.
$passwordAge
  The time before the password expires .
$privilege
  The user's privilege.
$homeDir
  The user's home directory.
$comment
  The user's comment.
$flags
  Flags re: user's account
$scriptPath
  Pathname of user's login script

Sets password, passwordAge, privilege, homeDir, comment, flags,and scriptPath for user

LocalGroupCreate($server, $group, $comment)
GroupCreate($server, $group, $comment)

$server
  The name of the server.
$group
  The name of the group to create.
$comment
  A relevant comment for the group

Creates a group

LocalGroupDelete($server, $group)
GroupDelete($server, $group)

$server
  The name of the server.
$group
  The name of the group to delete.

Delete a group from the server.

LocalGroupGetAttributes($server, $groupName, (out)$comment)
GroupGetAttributes($server, $groupName,(out)comment)

$server
  The name of the server.
$groupName
  The name of the group
(out) $comment
  Contains the comment for the group after the call returns.

Gets the comment for the group $group on the server $server.

LocalGroupSetAttributes($server, $groupName, $comment)
GroupSetAttributes($server, $groupName, $comment)

$server
  The name of the server.
$groupName
  The name of the group.
$comment
  The comment to set for the group.

Sets the comment for the group $groupName on the server $server.

LocalGroupAddUsers($server, $groupName, $users)
GroupAddUsers($server, $groupName, @users)

$server
  The name of the server.
$groupName
  The name of the group.
@users
  The names of the users to add.

Adds users to a group.

LocalGroupDelUsers($server, $groupName, @users)
GroupDelUsers($server, $groupName, @users)

$server
  The name of the server.
$groupName
  The name of the group.
@users
  A list of user names to delete.

Deletes a list of users from a group.

LocalGroupIsMember($server, $groupName,$user)
GroupIsMember($server, $groupName, $user)

$server
  Name of the server to query.
$groupName
  Name of the group.
$user
  name of the user, whose membership is being tested.

Returns TRUE if $user is a member of $groupName

LocalGroupGetMembers($server, $groupName, (out)\@userArray)
GroupGetMembers($server, $groupName,(out) \@userArray)

$server
  The name of the server.
$groupName
  The name of the group.
(out)\@userArray
  A reference to an arry of users.

Fills userArray with the members of groupName

Example

           use Win32::NetAdmin;
           # set info for the user.
           $userName = 'TestUser';
           $password = '';
           $passwordAge = 0;
           $privilege = USER_PRIV_USER;
           $homeDir = 'c:\\';
           $comment = 'This is a test user';
           $flags = UF_SCRIPT;
           $scriptpath = 'C:\\';
           $groupName = 'TestGroup';
           $groupComment = "This is a test group";
           Win32::NetAdmin::UserCreate('', $userName,
                                  $password,
                                  $passwordAge,
                                  $privilege,
                                  $homeDir,
                                  $comment,
                                  $flags,
                                  $scriptpath) || print "not ";

           Win32::NetAdmin::UserGetAttributes('',$userName,
                                  $Getpassword,
                                  $GetpasswordAge,
                                  $Getprivilege,
                                  $GethomeDir,
                                  $Getcomment,
                                  $Getflags,
                                  $Getscriptpath) || warn();

           ($password eq $Getpassword) || warn();
           ($passwordAge == $GetpasswordAge) || warn();
           ($homeDir eq $GethomeDir) || warn();
           ($comment eq $Getcomment) || warn();
           ($flags == ($Getflags&USER_PRIV_MASK)) || warn();
           ($scriptpath eq $scriptpath) || warn();

#### Implementation Note

The Win32::NetAdmin module is to allow control over the Windows NT users and group functions. These are not available on Windows 95. The module will not load on a Windows95 machine.

### Win32::File

- Functions
- Examples

Functions

GetAttributes( $filename,(out)$FileAttributes)

$filename
  Name of the file.
(out)$FileAttributes
  Attributes of the file.

$FileAttributes contains one or more of the following values:

- ARCHIVE
- DIRECTORY
- HIDDEN,
- NORMAL
- READONLY
- SYSTEM

SetFileAttributes($filename, $FileAttributes )

$filename
  Name of the file.
$FileAttributes
  Attributes of the file.

Set the attributes for the listed file.

Example

           use Win32::File;
           Win32::File::GetAttributes("myfile.txt", $Attributes) || die $!;
           Win32::File::SetAttributes("myfile.txt", ($Attributes | READONLY)) || die $!;

### Win32::Service

- Functions
- Examples

Functions

StartService($hostname, $servicename)

$hostname
  Name of the host.If NULL, then the localhost.
$servicename
  String containing the name of the service to start.

Starts a service. This service must be registered with the Service Control Manager .

StopService($hostname, $servicename)

$hostname
  Name of the host. If NULL, then the localhost.
$servicename
  String containing the name of the service to stop.

Stops a service.

GetStatus($hostname, $servicename,(out)\%status)

$hostname
  Name of the host. If NULL, then the localhost.
$servicename
  Name of the service
(out)\%status
  Scalar containing the result of the GetStatus call.

The GetStatus call returns the status as a hash reference in $status.
The keys of this hash are:

- ServiceType
- CurrentState
- ControlsAccepted
- Win32ExitCode
- ServiceSpecificExitCode
- CheckPoint
- WaitHint

These keys correspond to the members of the SERVICE_STATUS structure. (refer to the Win32 Programmer's Reference V4).

PauseService($hostname ,$servicename)

ResumeService($hostname ,$servicename)

$hostname
  Name of the host. If NULL, then the localhost.
$servicename
  Name of the service.

This Pair of calls pause and resume services. (Service must be able to pause.)

GetServices($hostname,(out)\%list)

$hostname
  Name of the host. If NULL, then the localhost.
(out)\%list
  Reference to hold the list returned from EnumServices.

EnumServices returns a list of available services in @$list.

Example

            use Win32::Service;

            Win32::Service::GetServices('', \%list) || die $!;
            print "Display Name = Service Name\n";
            foreach $key (keys %list)
            {
                print $key, '=', $list{$key}, "\n";
            }

            print "\n\n\n";

            Win32::Service::GetStatuse('', 'Messenger', \%status) || die $!;
            foreach $key (keys %status)
            {
                print $key, '=', $status{$key}, "\n";
            }

### Win32::NetResource

- Data
- Functions
- Examples

Data

%SHARE_INFO
The ShareInfo hash is used to pass information to the NetResource functions concerned with shares.

       KEY                    VALUE
    'netname'       => Name of the share.
    'type'          => Type of share.
    'remark'        => A string comment.
    'permissions'   => Permissions value
    'maxusers'      => The max # of users.
    'current-users' => The current # of users.
    'path'          => The path of the share.
    'passwd'        => A password if one is req'd

NETRESOURCE

       KEY                      VALUE
    'Scope'         => Scope of an Enumeration. See Scopes below.
    'Type'          => The type of resource to Enum. See Types below.
    'DisplayType'   => The way the resource should be displayed.See Display below.
    'Usage'         => Specifies the Resources usage: see Usage below.
    'LocalName'     => Name of the local device the resource is connected to.
    'RemoteName'    => The network name of the resource.
    'Comment'       => A string comment.
    'Provider'      => Name of the provider of the resource.

    Scope values:
    RESOURCE_CONNECTED   The resource is already connected.
    RESOURCE_REMEMBERED  The resource is reconnected each time the user logs on.
    RESOURCE_GLOBALNET   The resource is available to the entire network.

    Type values:
    RESOURCETYPE_ANY     All resources
    RESOURCETYPE_DISK    Disk resources
    RESOURCETYPE_PRINT   Print resources

    Display Type:
    RESOURCEDISPLAYTYPE_DOMAIN    The object should be displayed as a domain.
    RESOURCEDISPLAYTYPE_SERVER    The object should be displayed as a server
    RESOURCEDISPLAYTYPE_SHARE     The object should be displayed as a sharepoint.
    RESOURCEUSAGE_CONNECTABLE     The resource can be connected to a local device.
    RESOURCEUSAGE_CONTAINER       The resource contains more resources.

Functions

GetSharedResources((out)\@Resources,dwType)

(out)\@Resources
  A list of references to %NETRESOURCE hashes.
DwType
  The type of the enumeration.

Creates a list in @Resources of %NETRESOURCE hash references.This list contains all network resources. (Shared printers, disks, etc).

AddConnection(\%NETRESOURCE,$Password,$UserName,$Connection)

\%NETRESOURCE
  A hash representing the connection to make.
$Password
  The password of the user making the connection
$UserName
  The username of the user.
%Connection
  flag for connection

Makes a connection to a network resource specified by %NETRESOURCE, for the user $user.The $Connection flag determines whether the connection should be remembered for the user, for all logins.

CancelConnection($Name,$Connection,$Force)

$Name
  The name of the local device the resource is connected to.
$Connection
  Type of connection.
$Force
  Boolean: whether or not to force the connection.

Cancels a connection to a network resource connected to local device $name.$Connection is either 1 - persistent connection or 0, non-persistent.

WNetGetLastError((out)$ErrorCode(out),$Description,(out)$Name)

(out)$ErrorCode
  The error code number.
(out)$Description
  A description of the error.
(out)$Name
  The name of the error.

Gets the Extended Network Error. This is only applicable if Win32::GetLastError() returns ERROR_EXTENDED_ERROR.

GetError((out)$ErrorCode)

(out)$ErrorCode
  last error caused by a Win32 Network call.

Gets the last Error for a Win32::NetResource call.

GetUNCName((out)$UNCName, $LocalPath)

(out)$UNCName
  The UNC name of the network connection.
$LocalPath
  The name of the local path.

Returns the UNC name of the disk share connected to $LocalPath in $UNCName.
NOTE: The $servername arg is optional for all of the Share calls.

NetShareAdd(\%SHARE,$parm_err,$servername)

%SHARE
  A ShareInfo hash describing the share.
(out)$parm_err
  An error value describing any errors that occurred.
$servername
  Name of the server.

Offer a disk resource for sharing on the network.

NetShareCheck($device,(out)$type,$servername)

$device
  Name of the device to be checked for shared access.
(out)$type
  On return, contains the type of share.
$servername
  Name of the server.

Check if a share is available for connection. The value in $type is only valid if the funtion returns a true value (non-zero).

NetShareDel( $netname, $servername)

$netname
  The name of the share.
$servername
  The machine offering the share.

Remove a share from a machine's list of shares.

NetShareGetInfo($netname, (out)\%SHARE,$servername)

$netname
  The network name of the share.
(out)
  \%SHARE The SHARE_INFO hash describing the share.
$servername
  The server.

Get the %SHARE_INFO information about the share $netname on the server $servername.

NetShareSetInfo($netname,\%SHARE,(out)$parm_err,$servername)

$netname
  The network name of the share.
\%SHARE
  The SHARE_INFO hash describing the share.
(out)$parm_err
  The error status.
$servername
  The name of the server.

Set the information for share $netname.

Example

           use Win32::NetResource;
           use Win32;
           $ShareInfo =
           {
               'path' => 'e:\\temp',
               'netname' => "myshare",
               'remark' => "This mine, leave it alone",
               'passwd' => "",
               'current-users' => 0,
               'permissions' => 0,
               'maxusers' => 10,
               'type' => 10
           };

           Win32::NetResource::NetShareAdd($ShareInfo, $parm) || warn();
           $NewShare = {};
           Win32::NetResource::NetShareGetInfo("Temp", $NewShare) || warn();
           $Aref=[];
           Win32::NetResource::GetSharedResources($Aref, 0);
           # try to connect to the Temp share.
           # Find the NETRESOURCE information for the Temp share.
           foreach $href (@$Aref)
           {
               $myRef = $href if($href->{'RemoteName'} =~ /Temp/);
           }
           $myRef->{'LocalName'} = "Z:";
           Win32::NetResource::AddConnection($myRef, $passwd, $user, 0);
           Win32::NetResource::GetUNCName($UNCName, "Z:");
           print "UNCName of the share is $UNCName\n");
           Win32::NetResource::CancelConnection("Z:", 0, 1);
           Win32::NetResource::NetShareDel("Temp") || print "not ";