Powershell equivalent of Batch command "START" to open window with Mapped Drive - powershell

This is the batch commands I use to open a window with Mapped Drive:
net use X: "\\SERVERNAME\FOLDER" /user:"USER" "PASSWORD"
START X:\
What is the Powershell version of this?

Both of your commands work as-is in PowerShell:
net refers to the net.exe external program (a standard Windows utility), which PowerShell can equally call.
On Windows 8 / Windows Server 2012 or higher, you can use the New-SmbMapping cmdlet as an alternative to net use.
Note that while PowerShell cmdlets are generally more secure by not allowing passwords to be specified as plain text and requiring a credential object instead (see Get-Credential), this appears not to be the case with New-SmbMapping.
While start is an internal cmd.exe command, PowerShell has an alias named start for its own Start-Process cmdlet; if you pass a drive specification, the two commands work the same.
Alternatively, you could have used the Invoke-Item cmdlet (Invoke-Item X:\),
which more narrowly supports opening only documents and folders, by relative or absolute paths (no $env:PATH search for executables is performed).
in the case of a drive-spec-only path such as X:, Invoke-Item opens File Explorer in whatever directory is current on that drive (by contrast, Start-Process and cmd.exe's start open the target drive's root directory).

Related

Powershell Script only opens as a .txt file when run

Hi I have a script on a memory stick that I want to be able to run in cmd line before a computer has windows fully installed. (the stage just after you've connected to a network).
Cmd used to run the script.
Start > Run D:\pscript\Intune.ps1
This only opens a .txt file, while researching I've found that the reason this happens is due to security, is there anyway to override this bar changing the default file type out.
Unlike batch files (.cmd, .bat) associated with cmd.exe (the legacy Command Prompt), PowerShell's .ps1 script files are by default not directly executable from outside PowerShell.
Instead, they are treated as documents that are by default associated with either Notepad or the (obsolescent) Windows PowerShell ISE, depending on the , and invoking them therefore opens them for editing, which applies to the following contexts:
Invoking a .ps1 file from cmd.exe
Invoking a .ps1 file from Start Menu's Run dialog, as in your case (which you can invoke with WinKey+R, for instance)
Opening (double-clicking) a .ps1 file from File Explorer or Desktop.
To execute a .ps1 script from outside PowerShell, you must therefore invoke it via PowerShell's CLI, powershell.exe for Windows PowerShell, pwsh for PowerShell (Core) 7+.
In the simplest case, using Windows PowerShell and the -File parameter, as also shown by Mathias R. Jessen in a comment; see the comments below and the linked docs for additional parameters:
# Note:
# * The effective execution policy applies; use -ExecutionPolicy Bypass to bypass.
# * Profiles are loaded; use -NoProfile to suppress.
# * The console window auto-closes when the script terminates; use -NoExit
# to keep the session open.
powershell.exe -File D:\pscript\Intune.ps1
For a comprehensive overview of PowerShell's CLI, see this post.
It is possible - though not advisable - to configure your system to execute .ps1 files by default - see this answer.

Alternatives to invoke-expression

I have this function:
function traced()
{
write-host "$args"
invoke-expression -Command "$args"
}
and I use it in several places like traced cp "$($_.FullName)" (join-path $directory $newfile) so that I have a log of all of the places that get copied (or removed, or whatever)
But when the directory contains spaces and dashes, it results in invoke-expression throwing.
I guess I could just define traced-cp and traced-rm, but if I have a lot of functions I want to trace, what's the generic answer? I just want a function that prints, then evaluates, the exact command its given. From what I understand, the & operator isn't what I want here-- It won't work for shell builtins.
[...] so that I have a log of all of the places that get copied (or removed, or whatever)
I'd strongly recommend you use transcript logging for this!
You can start a transcript interactively with the Start-Transcript cmdlet, but if you want to keep a transcript of every single instance of PowerShell you launch by default, I'd suggest turning it on by default!
Open the local policy editor (gpedit.msc) on your Windows box and navigate to:
Computer Configuration
> Administrative Templates
> Windows Components
> Windows PowerShell
Select the policy setting named "Turn on PowerShell Transcription", set it to Enabled, and optionally configure your preferred output directory (defaults to your home folder).
This way, you'll always have a full transcript of your interactions in PowerShell :)
Consider using argument splatting to build your command instead of building a string-based command with Invoke-Expression. I also don't know where you heard that & doesn't work with shell built-ins but it works with both commands and cmdlets.
Here is the official Microsoft documentation on splatting in Powershell.
This approach also eliminates the difficulty in crafting a command string correctly, having to escape characters, and dealing with path spaces - using splatting with named or positional arguments takes care of most of this for you.
I would suggest using -verbose with copy-item or remove-item, and also -passthru with copy-item.

Powershell Start-Process VS Invoke-Item

What's the difference between Start-Process and Invoke-Item? I noticed that you can't Invoke-Item chrome. I assume that Invoke-Item is specifically for files with a given file path. But are there any advantages to using Invoke-Item instead of Start-Process (besides that typing ii is faster than typing start)?
The Invoke-Item cmdlet performs the default action on the specified item. For example, it runs an executable file or opens a document file in the application associated with the document file type. The default action depends on the type of item and is determined by the PowerShell provider that provides access to the data.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/invoke-item?view=powershell-6
The Start-Process cmdlet starts one or more processes on the local computer. To specify the program that runs in the process, enter an executable file or script file, or a file that can be opened by using a program on the computer. If you specify a non-executable file, Start-Process starts the program that is associated with the file, similar to the Invoke-Item cmdlet.
You can use the parameters of Start-Process to specify options, such as loading a user profile, starting the process in a new window, or using alternate credentials.
https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Management/Start-Process?view=powershell-6

.cmd vs .ps1 in Path

I have added a folder to my Path that contains a foo.cmd batch file and foo.ps1 powershell script. (The batch file is there to run the powershell script with a bypassed execution policy.)
When in powershell/command prompt I run
> foo
it runs foo.ps1 in preference to foo.cmd, which is the opposite of what I want. Is there any way to get round this, without having to type > foo.cmd?
Command precedence in PowerShell is defined like this:
If you do not specify a path, PowerShell uses the following precedence order when it runs commands:
Alias
Function
Cmdlet
Native Windows commands
Therefore, if you type "help", PowerShell first looks for an alias named "help", then a function named "Help", and finally a cmdlet named "Help". It runs the first "help" item that it finds.
Precedence of external ("native Windows") commands is then controlled by the PATH and PATHEXT environment variables. The former lists the directories Windows searches for external commands is the command wasn't invoked with a (relative or absolute) path, the latter lists extensions that Windows will auto-append if no match was found. For each environment variable the first match wins, meaning if you have a PATH listing C:\foo;C:\bar and have a folder structure like this:
C:
├─bar
│ └─a.exe
└─foo
├─a.cmd
└─a.vbs
Windows will execute C:\foo\a.cmd when you invoke the command a (without path or extension), because C:\foo comes first in the PATH and .cmd comes before .vbs in the PATHEXT variable.
However, PowerShell scripts seem to rank somewhere between cmdlets and external commands as far as PowerShell is concerned, because their extension not listed in $env:PATHEXT, but you can't supersede builtin cmdlets with PowerShell scripts of the same name. I wasn't able to find documentation about this, though.
Bottom line: I think you'll either have to invoke the batch script with extension or rename the PowerShell script. The latter could be done by appending a fixed suffix to the basename of the file and then invoke it from the batch script like this:
#echo off
set "suffix=-bar"
powershell.exe -ExecutionPolicy ByPass -File "%~dpn0%suffix%.ps1"

powershell script center - what do these mean?

I'm learning to use powershell and it's not clear to me what is meant by the 4 Powershell subheaders in the image; in this case, looking at the Get-FolderItems.ps1 function at https://gallery.technet.microsoft.com/scriptcenter/Get-Deeply-Nested-Files-a2148fd7
Are they meant to represent different examples of how the function can be used? Or am i supposed to use them in a specific sequence (e.g. first . .\Get-FolderItem.ps1 then Get-FolderItem -Path .\mypath, etc)
The first cmdlet is to load the cmdlet from the ps1 file using the dot sourcing syntax.
. .\Get-FolderItem.ps1
You should already be in the same directory as that file. Also, your execution policy should allow execution of this script. You can set the Execution policy to either RemoteSigned (default mode in Windows Server 2012 R2 onwards) or Unrestricted (not recommended but ok for dev/test purposes).
Set-ExecutionPolicy Unrestricted
Rest are the examples of using the cmdlet Get-FolderItem.
Read more about that cmdlet in this blog: List All Files Regardless of 260 Character Path Restriction Using PowerShell and Robocopy