Search code examples
windowspowershellpowershell-2.0aliaspowershell-3.0

Trying to make a function with multiple commands into a single alias in powershell?


Here's the code and the error I get:

function CSheridanStruct {
    New-Item -Path "C:\Users\Admininistrator\" -Name "Sheridan" -ItemType "directory" |
        New-Item -Path "C:\Users\Admininistrators\Sheridan\" -ItemType "directory" -Name "SYST23551", "Notes"
}

Set-Alias Sheridan CSheridanStruct

Sheridan
New-Item : Cannot convert 'System.Object[]' to the type 'System.String' 
required by parameter 'Name'. Specified method is not supported.
At line:2 char:167
+ ... rators\Sheridan\" -ItemType "directory" -Name "SYST23551", "Notes" }
+                                                   ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.NewItemCommand

I also tried it without the pipline on separate lines (this is within the function) tried just Set-Alias Sheridan CSheridanStruct same errors. And I tried to do Set-Alias -Name "Sheridan" -Value CSheridanStruct. Same output. The functions commands within, I've already checked and work and have created the directories. I just need to set an alias for all the commands to launch at once with typing the alias Sheridan in PowerShell..


Solution

  • This issue you are having is trying to put a array in the new-item -name field

    New-Item -Path "C:\Users\Admininistrators\Sheridan\" -ItemType "directory" -Name "SYST23551", "Notes"
    

    The error you are getting is because of -Name "SYST23551", "Notes"

    Second there is no need to pipe these commands as they have nothing to do with each other

    Here is a working version of your script

    function CSheridanStruct {
        New-Item -Path "C:\Users\Admininistrator\" -Name "Sheridan" -ItemType "directory"
        New-Item -Path "C:\Users\Admininistrator\Sheridan" -Name "SYST23551" -ItemType "directory"
        New-Item -Path "C:\Users\Admininistrator\Sheridan" -Name "Notes" -ItemType "directory"
    }
    
    Set-Alias Sheridan CSheridanStruct
    
    Sheridan