How to execute PowerShell commands from a batch file?

This is what the code would look like in a batch file(tested, works): powershell -Command “& {set-location ‘HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings’; set-location ZoneMap\Domains; new-item SERVERNAME; set-location SERVERNAME; new-itemproperty . -Name http -Value 2 -Type DWORD;}” Based on the information from: PowerShell script in a .bat file

Powershell 2 copy-item which creates a folder if doesn’t exist

In PowerShell 2.0, it is still not possible to get the Copy-Item cmdlet to create the destination folder, you’ll need code like this: $destinationFolder = “C:\My Stuff\Subdir” if (!(Test-Path -path $destinationFolder)) {New-Item $destinationFolder -Type Directory} Copy-Item “\\server1\Upgrade.exe” -Destination $destinationFolder If you use -Recurse in the Copy-Item it will create all the subfolders of the source … Read more

Extract a substring using PowerShell

The -match operator tests a regex, combine it with the magic variable $matches to get your result PS C:\> $x = “—-start—-Hello World—-end—-” PS C:\> $x -match “—-start—-(?<content>.*)—-end—-” True PS C:\> $matches[‘content’] Hello World Whenever in doubt about regex-y things, check out this site: http://www.regular-expressions.info

Equivalent to C#’s “using” keyword in powershell?

There’s really nothing at the namespace level like that. I often assign commonly used types to variables and then instantiate them: $thingtype = [FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It.Thingamabob]; $blurb = New-Object $thingtype.FullName Probably not worth it if the type won’t be used repeatedly, but I believe it’s the best you can do.

How to keep the shell window open after running a PowerShell script?

You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post. One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit “C:\SomeFolder\SomeScript.ps1” Per-script Fix: Add a prompt for input to the end … Read more

How to properly -filter multiple strings in a PowerShell copy script

-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \* to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters. Get-ChildItem $originalPath\* -Include *.gif, … Read more