Powershell ps1 file “is not recognized as a cmdlet, function, operable program, or script file.”

前端 未结 3 2008
你的背包
你的背包 2020-12-11 14:36

I made a Powershell function just now and saved it to a ps1 file. However, when I try to execute it from within powershell, it won\'t run.

I\'ve allready changed to

相关标签:
3条回答
  • 2020-12-11 15:00

    If you replace "function listallpaths" with param and get rid of the surrounding {} like this..

    param([string]$fromFolder, [string]$filter, [string]$printfile)
    Get-ChildItem -Path $fromFolder -Include $filter -Recurse -Force -Name > $printfile
    

    You will have a script file that you can call as required.

    PS> .\listAllPaths.ps1 c:\ *.pdf testingPDF.txt
    

    As Matt alluded to, by declaring the function, when you called the script, it would create the function and then exit. A PowerShell script is basically a function stored in a file (without the surrounding braces.. they are implied), where the function itself would be stored in memory.

    0 讨论(0)
  • 2020-12-11 15:03

    I could be off base here, but is it that your script is defining a function, rather than executing it? Perhaps you need to "source" the script:

    . .\listallpaths.ps1
    

    ... so that now your "listallpaths" function is defined.

    0 讨论(0)
  • 2020-12-11 15:23

    This is a typical error across many platforms where your environment path does not include your current directory. so when you execute your script (or command or program etc), your runtime environment looks everywhere except your current/working directory.

    Try

    PS> .\listAllPaths.ps1 c:\ *.pdf testingPDF.txt
    

    EDIT: After reading your comments, I'm going to suggest you try this. I haven't actually verified the logic of your PS script. I'm merely trying to get your script to execute first.

    Try editing your script as below, and execute as above.

    Function listAllPaths([string]$fromFolder, [string]$filter, [string]$printfile){
    Get-ChildItem -Path $fromFolder -Include $filter -Recurse -Force -Name > $printfile
    }
    
    listAllPaths
    
    0 讨论(0)
提交回复
热议问题