In moderneren Programmier- und Skriptsprachen wie PowerShell verschwindet aus berechtigten Gründen die Möglichkeit die goto-Funktion zu nutzen. Dadurch lässt sich einfach zu schnell Spaghetti-Code fabrizieren und bei wachsenden Skripten und langem Quellcode verliert man so relativ schnell den Überblick, wann etwas durch goto an welcher Stelle bzw. zu welchem Zeitpunkt im PowerShell-Skript passiert.
Allerdings wollen genügend Programmierer, vermutlich für eine schnelle Quick&Dirty-Umsetzung, trotzdem noch gerne goto und Sprungmarken in einem solchen PowerShell-Skript verwenden. Auch wenn es nicht zu empfehlen ist, kann man sich mit Hilfe der Switch-Funktion eine goto-ähnliche Funktionsweise des Skriptes aufbauen!
Goto durch Funktion mit Switch-Case
Die neue Skriptsprache PowerShell bietet im Vergleich zu einfachen Batch-Skripten viele andere Kontrollstrukturen und vereinfachte Schleifen, mit denen man viel komfortabler programmieren und Code einsparen und wiederverwenden kann, als mit den beliebten goto-Statements.
Trotzdem kann man sich mit eben diesen neuen Kontrollstrukturen auch wieder die alten goto-Statements auf die eine oder andere Weise zurückholen. Hierzu kann man z. B. eine Funktion namens „goto“ erstellen. In dieser nutzt man die Switch-Case-Funktion und teilt sich dadurch seinen Code in Abschnitte ein. Wichtig ist, dass das gesamte Skript nun in dieser einzigen goto-Funktion aufgebaut wird! Am Ende jeden Abschnitts muss der jeweils nächste Abschnitt aufgerufen werden. Am Ende ruft man die goto-Funktion mit der Ausführung des ersten Abschnitts, also dem ersten Case, auf. Das sieht beispielweise so aus:
Nun kann man natürlich innerhalb der Abschnitte z. B. mit „if und else“-Abfragen hin und her springen und auch wieder einen anderen als den nächsten Abschnitt aufrufen.
0 |
To run automated scripts, you must have the latest major version of the relevant framework installed on the .
- On the page, select Create new job.
Can’t find the page in the left menu? That’s probably because the
Devices menu is collapsed. Click the arrow to expand it.

- On the Create job page, choose the platform where you want to run automation steps.
- PowerShell execution
- JavaScript execution
- Python execution
- Shell script execution (available on Mac only)
- Paste your script to the field. You can also select files to upload that the remote can download.
You can reference the file(s) from the script. You can upload up to three files per job with a maximum size of 1GB each. Any file can be used.
- Optional: When you work with PowerShell, you can select Open script library to choose a pre-defined script to run. Then select Apply script.
At this point, you can still edit the script as necessary.
- From the list of Devices define the or a group of that will receive the script.
You can organize your devices by selecting a grouping option from the top of the list.

- Name the job in a way that is easy to remember later on.
Optionally, you can schedule jobs up to one year in advance. To do so, toggle
Schedule this job and set the time and date for the job to run. In the
Date and time field, either type a date or click the calendar icon to choose it from a date picker.You can select offline devices for scheduled jobs, but when a job runs, devices must be online; otherwise, the job will fail on that device. Scheduled jobs run on each remote device’s local time.
A preset timeout pertains to both the job and the .
A timeout for every is set to two hours, meaning that waits two hours for the script to finish on the remote computer. When the script finishes, starts the next step and waits another two hours for that step to finish. If a step does not finish on a remote computer in two hours, then it times out and the whole job fails.
When you reference a file from the script, you only have to enter its name. Once the ends, the file is deleted from the , unless it is copied somewhere else with the script.
You upload ‘a.txt’ file for the job and you would like to copy it into a folder (also known as file distribution). Your script should look something like this:
Copy-Item a.txt C:\DestinationI want to place PowerShell code in a BAT File and start the BAT file from the Windows explorer by double-click. Powershell shall execute BAT as PowerShell script. The intention is show in this example “a.bat”:
@rem = ""
powershell -NoLogo -File %0
goto :eof
""
"Greetings from Powershell" | Out-HostBut Powershell insist on .ps1 file extension:
Processing -File ‘.\a.bat’ failed because the file does not have a ‘.ps1’ extension. Specify a valid Windows PowerShell script file name, and then try again.
I know, I can fold the script from the BAT file in one line and pass it with the -Command option to Powershell. But this makes it unreadable.
I could also store the Powershell code in a .ps1 file. But a double-click will open it in notepad instead of executing the code.
Is there any way to fold both (BAT and Powershell script) in one file?
asked Oct 9, 2023 at 7:53
9 gold badges61 silver badges109 bronze badges
Your question is closely related to this post, though your particular use case involves a simplification:
You do not need to support pass-through arguments, given that running batch files by double-clicking from File Explorer (or the desktop) doesn’t allow for passing arguments to the executable (batch file) being invoked.
More work is needed in order to also support pass-through arguments (that is, if your batch should also be callable from the command line, with arguments) and to do so robustly you do need the
-FileCLI parameter, which in turn requires creating a temporary copy of the batch file with a.ps1extension, as demonstrated in this answer (of mine) to the linked post.
Robust solution without pass-through argument support:
<# ::
@echo off & setlocal
set "__thisBatchFile=%~f0"
powershell -NoProfile -ExecutionPolicy Bypass -c "iex (gc -Raw -LiteralPath \"%~f0\")"
exit /b %ERRORLEVEL%
#>
# Paste arbitrary PowerShell code here.
# Use $env:__thisBatchFile to refer to this file's full path.
"Hello from the PowerShell part of hybrid batch file `"$env:__thisBatchFile`""set "__thisBatchFile=%~f0"creates an environment variable containing the batch file’s own full path (%~f0), which the PowerShell code can reference as$env:__thisBatchFile- It won’t matter in the double-click scenario, but the
setlocalpart of@echo off & setlocalensures that this aux. variable doesn’t linger if the batch file is called from an interactivecmd.exesession (Command Prompt).
- It won’t matter in the double-click scenario, but the
-NoProfilesuppresses loading of PowerShell’s profile files, which can speed up the call and makes for a more predictable execution environment.-ExecutionPolicy Bypassbypasses the effective execution policy to ensure that your PowerShell code predictably executes.- This assumes that you fully control or implicitly trust not just the PowerShell code in the batch file itself, but also any outside code it calls.
- If a GPO-based execution policy that prevents execution of local scripts altogether or unsigned local scripts is in effect, it can not be overridden with
-ExecutionPolicy. - However, as long as the PowerShell code placed directly in the batch file doesn’t call
.ps1files or script modules, that won’t matter.
-cis the alias of-Command, which causes all subsequent arguments to be interpreted as PowerShell code.iexis the built-in alias ofInvoke-Expression(which is usually to be avoided), to which the full text of the batch file (obtained viagc, the built-in alias ofGet-Contentand its-Rawswitch) is passed for evaluation.
exit /b %ERRORLEVEL%passespowershell.exe‘s process exit code through, as the batch file’s exit code.
As noted in the comments, an alternative is to redefine the file type for .ps1 files that double-clicking them executes them, instead of the default behavior of opening them for editing.
If you still want to do it, see this answer for a (nontrivial) solution.
answered Oct 9, 2023 at 14:59
68 gold badges673 silver badges862 bronze badges

Table of contents
- Introduction to PowerShell Change Directory
- How to change the Directory in PowerShell?
- Changing the drive in PowerShell
- Setting the default working directory in PowerShell
- Push-Location and Pop-Location
- Viewing the Current Directory in PowerShell
- Tips and tricks for using PowerShell Change Directory Effectively
- Common pitfalls and errors when changing directories in PowerShell
- Wrapping up
Introduction to PowerShell Change Directory
The CD command is an alias of the Set-Location cmdlet used to navigate through the file system and change the working directory. It takes a directory name as an argument and changes the working directory to that directory. We can use either relative or absolute path names as arguments to navigate to a specific directory.
To change the current directory in PowerShell, you can use the Set-Location cmdlet, also known as the cd alias. Here is how to CD in PowerShell:
If the directory name contains spaces, you can enclose the folder name in double quotes like this:
Changing to a parent directory
To navigate to the parent directory of the current working directory, you can use the double-dot (..) notation, like this:
Similarly, Instead of moving one level up, you can move two levels by appending a backslash (\) at the end of each.
To reach the root drive, use:
This will set the current working directory to the root drive, such as “C:\”.
Changing to a child directory
The dot (.) represents the current working directory, and we use the backslash (\) as the directory separator. When you execute this command, you change the current working directory to the “Reports” folder.
PowerShell to Navigate to a Folder
To change the directory in PowerShell, you need to provide the path to the desired folder. This path can be either an absolute path (starting from the file system’s root) or a relative path (relative to the current working directory). You can use an absolute path to navigate to a specific folder. An absolute path specifies the entire path from the root directory to the target directory. For example, to navigate to the “Documents” directory on the C: drive, type:
CD C:\Users\username\Documents
Changing to any other folder is possible with Set-Location by passing the path parameter to it:
Set-Location -Path C:\Scripts
You can also use relative paths to navigate to a directory. A relative path specifies the path from the current working directory to the target directory. For example, to navigate to a directory named “Data” that is located in the “Documents” directory, you can use a relative path like this:
Auto-Completion: Similar to other shells, PowerShell supports auto-completion. Start typing the path and press Tab to complete folder or file names. This tab completion is especially useful when dealing with long directory names.
Using environment variables
Set-Location ${env:ProgramFiles}This changes the working directory to “C:\Program Files”.
Set-Location (Join-Path -Path $HOME -ChildPath "Documents") # or cd (Join-Path -Path $HOME -ChildPath "Documents")
Changing the drive in PowerShell
You can also use PowerShell to navigate through different drives on your computer. To navigate to a different drive, you can use the Set-Location cmdlet with the Drive parameter like this:
- Open the PowerShell console.
- Type the drive letter followed by a colon like this – D:
- Press Enter to change to the specified drive.
- You can now navigate through the file system on that drive using the CD command.
Similarly, you can navigate to a folder in another drive using:
Set-Location -Path D:\Scripts #Also works: CD D:\Scripts

In addition, add the “-PassThru” parameter to return the path after PowerShell changes the current working directory. Changing to network drives is also possible. E.g.,
Set-Location \\Fileserver\Public
Provide the UNC path to Set-Location or cd.
Setting the default working directory in PowerShell
# Check if profile exists
if (-not (Test-Path $profile)) { # Create profile if it doesn't exist New-Item -Type File -Path $profile -Force Write-Host "Profile created at $profile" -ForegroundColor Green
} else { Write-Host "Profile already exists at $profile" -ForegroundColor Yellow
}
# Set the desired default directory
$DefaultDirectory = "C:\Scripts"
# Append the Change-Location command to the profile
Add-Content -Path $profile -Value "Change-Location $DefaultDirectory"
Write-Host "Default directory set to $defaultDirectory" -ForegroundColor Green
# Inform user to reload their profile or restart PowerShell
Write-Host "Please reload your profile or restart PowerShell for changes to take effect." -ForegroundColor CyanThe working directory should now be set to the directory you specified.
Push-Location and Pop-Location
You can also the Push-Location cmdlet (alias pushd) to temporarily change to a different directory and then use the Pop-Location cmdlet (alias popd) to return to the previous directory. This can be useful if you need to perform some tasks in a different directory and then return to the previous location when you are done.
# Change to the D:\Scripts directory Push-Location D:\Scripts # Perform some tasks here # Return to the previous directory Pop-Location
Here is how it works:

Viewing the Current Directory in PowerShell
If you’re not sure which directory you’re currently in, you can use the command:
You can also use the alias “pwd”, which stands for “print working directory” and will display the current directory path on the command line.
Setting the working directory to the script location in PowerShell
When writing PowerShell scripts, it is often necessary to ensure that the script’s working directory is set to the location where the script is executed. This can be achieved using the Set-Location cmdlet, which is an alternative to the cd command.
Set-Location -LiteralPath $PSScriptRoot
Here, the $PSScriptRoot variable represents the path to the script’s location. By executing this command, the working directory will be set to the script’s location, allowing you to access files and folders relative to the script. You can also get the current path of the script using the automatic variable “$Script:MyInvocation.MyCommand.Path”. E.g.,
#Get path of your current directory location $CurrentPath = Split-Path $Script:MyInvocation.MyCommand.Path -Parent #Get Files and folders in current path Dir $CurrentPath
Tips and tricks for using PowerShell Change Directory Effectively
Now that you know how to use the CD command to navigate through the file system in PowerShell, here are some tips and tricks to help you use it more effectively:
- Use the Tab key to autocomplete the directory and file names. This will save you time and reduce the risk of typos.
- Use the Up Arrow key to quickly recall and reuse previous commands.
- Use the Push-Location command to save the current directory to a stack and navigate to a new directory. You can then use the Pop-Location command to return to the previous directory.
- Use aliases: PowerShell provides aliases for common commands, including
cd. You can use aliases to save typing time and streamline your workflow. For example, instead of typingcd, you can use the aliasslorchdirto change directories. - Use wildcard characters: PowerShell supports wildcard characters, such as
*and?, for pattern matching. You can use wildcard characters to navigate to folders or files with similar names. For example, to change to a folder that starts with “Proj” you can use the following command: “CD Proj*”.
In addition to the basic CD command, PowerShell provides several advanced techniques for changing directories. Here are some of the most useful techniques:
- Use the Join-Path command to combine multiple path components into a single path.
- Use the Resolve-Path command to resolve the full path of a file or directory, even if it contains relative path components.
- Use the Split-Path command to split a path into its parent and child components.
- Use the Test-Path command to test whether a file or directory exists at a specified path.
Common pitfalls and errors when changing directories in PowerShell
While changing directories in PowerShell, you may encounter some common pitfalls and errors. Understanding these pitfalls can help you avoid potential issues and troubleshoot problems effectively. Here are some common pitfalls to watch out for:
- Directory Does Not Exist: If you get an error indicating the directory does not exist, check your spelling and path.
- Invalid characters: PowerShell has specific rules regarding valid characters in folders and file names. If a folder or file name contains invalid characters, you may encounter errors when attempting to change directories. Make sure to use valid characters and escape special characters, if necessary.
- Permissions issues: Some folders or files may have restricted permissions, preventing you from accessing or changing directories. Ensure you have the necessary permissions to navigate to the desired folders or files.
- Missing drives: If you attempt to change to a drive that does not exist or is not currently mounted, you will encounter errors. Make sure to verify the existence and availability of drives before attempting to change them.
Wrapping up
How do I change the current directory in PowerShell?
How do I change from C drive to D drive in PowerShell?
How to change the path in PowerShell?
How do I change the directory in PowerShell when there is a space?
To change the directory in PowerShell, when there is a space in the path, you can enclose the path in double quotes (“”). For example, if the directory is “C:\Program Files”, you would use the command: cd “C:\Program Files”
How do I run a PowerShell script in a specific directory?
How do I change the default directory in PowerShell?
To change the default directory in PowerShell, you can create a PowerShell profile and set the default directory in it. For example, if you want to set the default directory to “C:\Scripts”, you would add “Set-Location C:\Scripts” in the profile file (Create one, if it doesn’t exist already: New-Item -path $profile -type file –force).
How do I navigate a directory in Windows PowerShell?
How do I navigate to a parent directory?
To navigate to a parent directory, you can use the .. symbol. For example: Set-Location ..cd ..
This will move you one level up from the current directory.
How can I quickly navigate to my home directory?
How can I check the current directory in PowerShell?
To check the current directory in PowerShell, you can use the Get-Location cmdlet or its alias pwd. For example: Get-Location
How do I list all directories in PowerShell before changing to a new one?
To list all directories in PowerShell, you can use the dir or ls command to view all directories and files in your current location.
The aim of this page📝 is to illustrate bringing a program’s window to the front with a simple command from Powershell. Here is a particular code from my $profile, mainly for jumping into the VLC player, where I listen to BBC essential mix for routine tasks and don’t want to use WIN+<number> as that’s already reserved for other tasks and I don’t want to restart instances if I am listening to 2-hour mix that which I am pausing and unpausing, etc.

- In PowerShell, you can get a list of running processes using the
Get-Processcmdlet. - Once you have access to a process, you can read its properties or call its methods to perform various actions.
- However, some actions require interacting with the Windows API, which is not directly accessible from PowerShell.
- For example, bringing a running program’s window to the front requires calling the
SetForegroundWindowfunction from theuser32.dlllibrary. - To call this function from PowerShell, you need to use the
Add-Typecmdlet to define a new class with a static extern method forSetForegroundWindow. - Then, you can call this method with the handle of the program’s main window as an argument.
- The handle of the main window can be obtained from the
MainWindowHandleproperty of the process.
CODE
- I know
gotois a provocative name given the history of the phrase - I am still testing this, using it with SingleInstance, just take it as an inspiration


