无法识别 Cmdlet

Cmdlet not recognized

我写了我的第一个 cmdlet。

.\Scripts\Modules\NewShare\New-Share.psm1

当我将 .\Modules 添加到 $env:PSModulePath 并导入模块时,然后我可以检索帮助,但我无法执行它。

$evn:psmodulepath = C:\Users\bp\Documents\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules\;.\Modules;

当我运行脚本

New-Share -foldername 'C:\MyShare' -sharename 'MyShare'

我收到以下标准错误,因为该模块不存在。

The term 'New-Share' 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 line:1 char:10 + New-Share <<<< -foldername 'C:\MyShare' -sharename 'MyShare' + CategoryInfo : ObjectNotFound: (New-Share:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

有什么问题?

下面是我的 powershell 模块。

function New-Share
{ 
    <#
        .Synopsis
        This function create a new share
        .Description
        This function creates a new share. If the specified folder does not exist, it will be created, and then shared with the specified share name.
        .Example
        New-Share -foldername 'C:\MyShare' -sharename 'MyShare'
        Creates the share with name 'MyShare' for folder 'C:\MyShare'.
        .Parameter foldername
        The folder that needs to be shared. Will be created if it does not exist.
        .Parameter sharename
        The name for the share.
        #Requires PowerShell 2.0
    #>
    [CmdletBinding()] 
     Param (
        [Parameter(Position=0, Mandatory=$True)] 
        [alias("fn")] 
        [string]$foldername, 
        [Parameter(Position=1, Mandatory=$True)] 
        [alias("sn")]
        [string]$sharename
        ) 

    if (!(test-path $foldername)) 
    { 
        new-item $foldername -type Directory 
    } 

    if (!(get-wmiObject Win32_Share -filter “name='$sharename'”)) 
    { 
        $shares = [WMICLASS]”WIN32_Share”

        if ($shares.Create($foldername, $sharename, 0).ReturnValue -ne 0) 
        {
            throw "Failed to create file share '$sharename'"
        }
    }
}

如果您从互联网上下载了模块,它应该放在 C:\Windows\System32\WindowsPowerShell\v1.0\Modules

  1. 您应该能够在您的会话中找到它。

    Get-Module -ListAvailable
    
  2. 然后就可以添加模块了

    Import-Module newshare
    
  3. 验证 cmdlet 是否可用

    Get-Command -Module newshare
    

错误发生是因为您没有添加模块。