Menu
  • HOME
  • TAGS

Closing just CSVs

excel,powershell

Removing out-null has resolved the issue

How to dynamically create an environment variable?

powershell,puppet

[Environment]::SetEnvironmentVariable("TestVariable", "Test value.", "User") This syntax allows expressions in the place of "TestVariable", and should be enough to create a profile-local environment variable. The third parameter can be "Process", this makes new vars visible in Get-ChildItem env: or "Machine" - this required administrative rights to set the variable. To retrieve...

Running a Powershell script from c#

c#,powershell

The problem was in the path of the script. It had spaces on this particular machine and I had not handled that. The window closed too fast to see any error but setting process.StartInfo.RedirectStandardOutput = true; helped me catch it. The execution policy had nothing to do with my error....

Disconnect Session via Powershell [closed]

session,powershell,user,server,disconnect

Powershell can use normal commands, this one should (according to manual) disconnect a given session: tsdiscon <ID> [/server:PC] [/V] [/VM] Pretty much the same as you use, just the executable is sifferent....

Powershell Error - Null/Empty Argument

sql,sql-server,powershell,database-connection

You changed my ForEach-Object loop to a foreach loop. If you want to use the latter you need to change the current object variable $_ to your loop variable $Server: foreach ($Server in $ServerArray) { $os = Get-WmiObject -Class Win32_OperatingSystem -Computer $Server $disks = Get-WmiObject -Class Win32_LogicalDisk -Computer $Server |...

Variable not resetting during loop creating misleading output

powershell,error-handling

I fully support Matt's answer! Either of those two options are simple solutions to your problem. What I offer is more of a re-write with some definite changes to how some things are done. I dropped the stream writer in favor or collecting results, and dumping them to a file...

Run Powershell script from inside other Powershell script with dynamic redirection to file

powershell,io-redirection

Your last bit there is very close, but I'm not sure why you have the underscore in there, and you need to escape your dollar sign, and close the entire thing in double quotes to cause string extrapolation. $logStreams = "2>&1>" $command = "'C:\myscript.ps1' $logStreams 'C:\outputlog.txt'" iex "& $command" I...

Get list of files whose creation date is greater than some date time

powershell,windows-server-2012

Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" | Where-Object { $_.CreationTime -gt [datetime]"2014/05/28" } | Sort-Object CreationTime | Format-Table Name, CreationTime String is cast to datetime if you specify [datetime] before it. You can read about comparison operators by typing help about_Comparison_Operators in PowerShell console....

View All Certificates On Smart Card

powershell,x509certificate

So, the main problem is actually that you're linking an x86 DLL into a x64 Powershell process. You can check whether your Powershell process is x64 like here (by querying (Get-Process -Id $PID).StartInfo.EnvironmentVariables["PROCESSOR_ARCHITECTURE"]), and if an x64 Powershell detected, start manually a Powershell (x86) located at $env:windir\syswow64\WindowsPowerShell\v1.0\powershell.exe with the same...

Create powershell parameter default value is current directory

powershell,powershell-v3.0

Use PSDefaultValue attribute to define custom description for default value. Use SupportsWildcards attribute to mark parameter as Accept wildcard characters?. <# .SYNOPSIS Does something with paths supplied via pipeline. .PARAMETER Path Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.)....

Sum values from input-csv

powershell,csv

It looks like you were really close. You just initialized $totaldisk wrong (and in the wrong place). $coll = import-csv "C:\input.csv" foreach ($record in $coll) { $totaldisk =0 for ($i=1; $i -lt 4; $i++) { $diskname = "disk"+$i $totaldisk += $record.$diskname } $totaldisk } ...

How to add a SwitchParameter to an attribute collection?

powershell,parameters

You does not have to use any additional attributes to make parameter to be switch parameter. You just declare it's type as System.Management.Automation.SwitchParameter or switch. function f{ [CmdletBinding()] param( [string[]]$Names ) dynamicparam{ $DynamicParams=New-Object System.Management.Automation.RuntimeDefinedParameterDictionary foreach($Name in $Names){ [email protected]( New-Object Parameter -Property @{ParameterSetName="Set_$Name"} ) $Param=New-Object System.Management.Automation.RuntimeDefinedParameter $Name,switch,$Attributes...

PowerShell Where-Object $_.name -like -in $list

powershell

The Where-Object FilterScript block is just a scriptblock that returns $true, $false or nothing - you can do all kinds of crazy things inside it, including looping over an array to see if there is a wildcard match in one of the entries: Where-Object { $ProductName = $_.Name $_.pscomputername -like...

Color a cell on the basis of another cell value

html,powershell,powershell-v2.0

You should format your HTML result with a different style if there's a condition. To do that, you declare a variable for data style that should be equal to $normalDataStyle if your condition is false, and a special style if it's true. $redDataStyle='style = "border: 1px solid black; background: #c00000;...

Return results from function for $body of email

powershell

Your output is an object, or a list of objects. You need to transform it into a string for sending it via e-mail. Depending on what you want the mail body to look like, you could do something like this: $body = Get-LockedOutLocation -Identity y59x | Format-Table -AutoSize | Out-String...

Programmatically accessing TFS history [closed]

c#,.net,powershell,tfs

Shai Raiten's Blog is great for learning the TFS API. For getting file history - read this post: http://blogs.microsoft.co.il/shair/2014/09/10/tfs-api-part-55-source-control-get-history/...

Why does piping Get-PSSession to Exit-PSSession not work?

powershell

You've not looked closely enough. Don't forget, it's easy to get all cmdlets related to a certain subject by doing something like this: Get-Help PSSession This gets a list of all cmdlets with "PSSession" it its name. If you carefully review the output, there's Exit-PSSession and Disconnect-PSSession, but there's one...

Why doesn't “Set-Item” work on Windows 7 PowerShell?

windows,powershell,raspberry-pi

You need to use quotes rather than < > around the name of the device (minwinpc) Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'minwinpc' ...

Define an array with prefixes using the range operator

arrays,powershell

Would that do? @(4..9) | % {"usr" + $_} ...

How do I write a loop to read text file and insert it to the database

sql-server,loops,powershell

To add a simple loop, you can use your existing AutoImportFlatFiles function like this: $Folder= $(read-host "Folder Location ('C:\Test\' okay)") foreach ($file in (get-childitem $Folder)) { $location = split-path $file.FullName -Parent $filename = (split-path $file.FullName -Leaf).split(".")[0] $extension = (split-path $file.FullName -Leaf).split(".")[1] AutoImportFlatFiles -location $location -file $filename -extension $extension -server "WIN123"...

Enhancing the pipeline's content?

powershell,powershell-v3.0

Updating archive .\files.zip ... Compressing files.zip ? Check if your function has a case when adding Archive.zip to Archive.zip, this should throw a warning like copying over itself. About pipeline - I think you should employ -passthru switch, if the switch is present, return the archive as a Get-Item result...

Loop Issue - Remote Server

powershell

You never output $DRIVE anywhere, and the expression for $DRIVE shouldn't be in a scriptblock in the first place. The computer name is repeated several times, because you get the SystemName property for each logical disk object. Also, $OS gets the OS name for the local computer, not the remote...

PS pipe WorkingSet as variable

variables,powershell

Use Select-Object -ExpandProperty to grab just a single property from the process: $WorkingSet = Get-Process spiceworks |Select-Object -First 1 -ExpandProperty WorkingSet if($WorkingSet -gt 120MB) { # Send email } ...

PowerShell - Convert CSV to XLSX

powershell

What is the whole "gps" part of the script for? The two (gps excel -ErrorAction SilentlyContinue).count lines at the start and end of the script count the number of Excel executables running. gps is the shorthand alias for get-process. You can find out more by doing help gps which...

How to run a line in Powershell in Python 2.7?

python-2.7,powershell,subprocess

Using single quotes inside a single quoted string breaks the string. Use double quotes outside and single qoutes inside or vice versa to avoid that. This statement: powershell -command '& {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg' 'C:\Images' 'W:\product_images\import'}' should rather look like this: powershell -command "& {. ./uploadImageToBigcommerce.ps1; Process-Image '765377' '.jpg'...

grep string between two other strings as delimiters

regex,powershell,grep

What Ansgar Wiechers' answer says is good advice. Don't string search html files. I don't have a problem with it but it is worth noting that not all html files are the same and regex searches can produce flawed results. If tools exists that are aware of the file content...

Bind every line from two variables in a third variable in powershell

variables,powershell,powershell-v2.0

this is a rapid way (variables's lenght must be equal): $i = 0 ; $var3 = $var1 | % { "$_ $($var2[$i])"; $i++ } ...

Organizing Active Directory accounts

powershell,active-directory,user,organization,ou

You are running into a few problems here Like Vesper said you are not passing anything to Move-ADObject hence the error you are getting $DisplayNames is not a string array of names but an object with a displayname property. That is what -ExpandProperty parameter is for with Select-Object FYI. You...

Powershell Invoke-Command with PSCredential Cannot process argument transformation on parameter 'Credential'

powershell,arguments,transformation,credentials,invoke-command

You have a mistake calling ImpersonateSql function. You should not use any parenthesis or commas for specifying parameters when calling function (unless you deliberately want to pass a subexpression or an array as an argument), it's not like C# or javascript function you are used to. Look at an example:...

One button with 2 actions

winforms,powershell,button,click,action

If you want to toggle the action of the button each time the button is clicked, you need to replace the current action with the other action within each action: $actionAll = { # other operations here $OKButton.Text = 'None' $OKButton.Remove_Click($actionAll) $OKButton.Add_Click($actionNone) } $actionNone = { # other operations here...

How to get current working directory inside a Cmdlet

c#,powershell,cmdlet

I am starting in C:\Users\<myusername>. If I know enter cd.. I am in C:\Users\ Entering (Get-Location).Path returns C:\Users. Thats what you want, isnt it? Altrnativly try: WriteObject(this.SessionState.Path.CurrentFileSystemLocation); Reference: How can I get the current directory in PowerShell cmdlet?...

Format a command in powershell including a comma, can't find the right way to escape

powershell,batch-file,escaping,powershell-v2.0,comma

".\pacli DELETEUSER DESTUSER='"[email protected]`,com"' sessionid=333" You have double quotes in single quotes in double quotes, so the inner double quotes will terminate the string, so this will be parsed as three values: ".\pacli DELETEUSER DESTUSER='" [email protected]`,com "' sessionid=333" The answer is to escape, with a back tick (`), the inner...

Add Custom Argument Completer for Cmdlet?

powershell,cmdlet,chocolatey

You may want to look at the TabExpansion++ module, which was designed to make extending tab completion easier. I just played with it for few minutes, and I think you want something like this based on the example: Import-Module TabExpansion++ function PaketAddNugetCompletion { [ArgumentCompleter(Parameter = 'Nuget', Command = 'Paket-Add')] param($commandName,...

Get actual path from path with wildcard

powershell,if-statement

Sounds like you want Resolve-Path: if(($Paths = @(Resolve-Path "C:\Test6_*_15.txt"))){ foreach($file in $Paths){ # do stuff } } else { # Resolve-Path was unable to resolve "C:\Test6_*_15.txt" to anything } ...

Issue filtering out certain event logs from output

html,powershell

I think I see a couple of potential issues. If we have a look at a few event from my local computer. EventID InstanceId Message ------- ---------- ------- 1202 2147484850 Security policies were propagated with warning.... 0 0 The description for Event ID '0' in Source 'gupdate' cannot be found....

How to get stored procedure output parameter into variable using Powershell?

powershell,stored-procedures,output-parameter

Modify your script to be like below $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=myserver;Database=mydb;Integrated Security=True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = "testsp3" $SqlCmd.Connection = $SqlConnection $SqlCmd.CommandType = [System.Data.CommandType]'StoredProcedure'; <-- Missing $outParameter = new-object System.Data.SqlClient.SqlParameter; $outParameter.ParameterName = "@answer"; $outParameter.Direction =...

How to change the directory to program files using Powershell?

powershell

Unlike command.com/cmd.exe, PowerShell follows much more consistent rules and in the failing case Program and Files\R..bin are parsed as two separate arguments, where the second is invalid in context (as cd only accepts a single non-named argument). To fix this use quotes, eg. cd "C:\Program Files" With the quotes it...

Post messages from async threads to main thread in F#

.net,powershell,f#,system.reactive,f#-async

I ended up creating an EventSink that has a queue of callbacks that are executed on the main PowerShell thread via Drain(). I put the main computation on another thread. The pull request has the full code and more details. ...

How to retrieve the name and path of VM's through powercli

powershell

If the text infront and including "Resources" is redundant then using a simple regex we can replacing it before it is output from your function. From $path to $path -replace "^.*?Resources/" So that would replace the similar line inside your function ( Where you return the property). We take everything...

Powershell comparison of text file

powershell,readfile

Something to get you started: # $file1 will be an array with each element containing the line contents $file1 = get-content .\text1.txt # $file2 will be an array with each element containing the line contents just like $file1 $file2 = get-content .\text2.txt # This splits each line of $file2 on...

PowerShell logic to remove objects from Array

arrays,powershell

How about not performing a remove, but just sort on tastecode descending and taking just one first result? $DuplicateMembers = $Fruits | Group-Object Name $DuplicateMembers | ForEach-Object { $Outcome = $_.Group | Sort-Object TasteCode -descending | Select -First 1 $Outcome } This way you should not bother to remove anything...

Trying to rename several account types at once based on current displayName

powershell,active-directory,user,rename,identity

You can't use the current object variable ($_) if you have Set-ADUser read directly from the pipeline. And since Set-ADUser apparently doesn't play nice with scriptblock arguments, you have to put the statement in a loop: ... | % { Set-ADUser $_ -DisplayName ($_.DisplayName -replace '(.EPSILON ).+',"`$1$($Rename.NewName)") } Note that...

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment

powershell,credentials,start-process

start-process is an 'alias' for System.Diagnostics.Process.Start(), so yes, it does make use of CreateProcessWithLogonW(). As noted, this method can't be called from a service process, it can only be called from an 'interactive' process. The caveat to that "only" is the one you've discovered - that when you aren't changing...

Error with Get-ADUser: Invalid enumeration context

powershell,active-directory

The biggest issue you have here is you are asking a lot from Get-ADUser. Based on your comment you are pulling in over 900,000 accounts. On top of that you are pulling all properties of those users. There is a touch of insanity there. While I am not perfectly clear...

Regex not working in Powershell

regex,powershell

Take a look and see what it's doing manually: PS U:\> $item = 'Element 12657 - <Description trext>' PS U:\> $pattern = 'Element\s(\d*).*' PS U:\> $Matches Name Value ---- ----- 1 12657 0 Element 12657 - <Description trext> I would try $id = $matches[1];....

Powershell Data input [closed]

powershell,input,data

Try this: $PCname = Read-Host "Please enter the PC Name" $Userid = Read-Host "Please enter the Uder ID" Copy-Item -LiteralPath \\$PCname\C`$\Users\$UserID\AppData\Roaming\Nuance\NaturallySpeaking12\Dragon.log -Destination "\\Static PC\C`$\Users\MyName\Desktop\Dragon Logs" -Force $PCname and $Userid are examples of powershell variables. The values are to be entered when you run the script. The other answer is trying...

setting up azure ad certificate auth using powershell

powershell,azure,azure-active-directory

The 'value' field for the key credentials is always returned as 'null' for applications and service principals.

Copy File Name to New File

powershell

Use Get-ChildItem and Where-Object to find the relevant files, pipe them to ForEach-Object and create a new file with New-Item: Get-ChildItem -Filter *.txt |Where-Object {$_.Name -match "\d{4}Backup\d{8}.txt"} |Foreach-Object { New-Item "$($_.Name).pgp.trg" -ItemType File } ...

How to append datatable to existing records in CSV file

powershell,csv,datatable

Since PowerShell v3 the Export-Csv cmdlet has an -Append parameter that allows appending to an existing CSV. $data | Export-Csv 'MyFile.csv' -Append -NoType On earlier versions you can work around that by converting the data to CSV, skip the header line, then append to the output file using Add-Content or...

Merge XML documents into empty XML node?

c#,xml,powershell

Get the customer node first by doing the following: $customersNode = $doc.ChildNodes | ? { $_.name -eq "customers" } Now you can call AppendChild on $customersNode with document A, B and C. However to import document A, B and C you almost had it right. Use the DocumentElement property like...

Remove all folders .old

powershell

Get-ChildItem produces a list of objects. Use a pipeline for processing that list: Get-ChildItem '\\kiewitplaza\vdi\Appsense_profiles' | Where-Object { $_.Name -like '*.old' } | Remove-Item ...

CPU usage missing from log for some processes

powershell

You can't get CPU for some processes because of insufficient rights. You get null value then. To output "Nothing" you have to compare the cpu value with $null, something like this: [email protected]{Expression={$_.ProcessName};Label="ProcessName";Width=40},@{Expression={$cpu=$_.CPU;if($cpu -eq $null){"Nothing";} else {$cpu;}};Label="CPU";Width=20} $ServiceTable = @{Expression={$_.Name};Label="Name";Width=40},@{Expression={$_.Status};Label="Status";Width=10} Get-Process | Sort-Object CPU -Descending | Select-Object ProcessName, CPU | format-table...

Output format of TCM with PowerShell

powershell,tcm

You always get a single string if you execute an external program. In order to receive a string table, you first call $listOfSuites.split("`r`n") to get an array of strings, then you need to parse those strings by offset of those strings in the line-filled one (in your case, 0 to...

Having trouble with a script to move Hyper-V VM's

powershell,hyper-v,sccm

Never use format-anything if you intend to continue processing the data. People use it for "nice" output to text file ( if you like console tables ) but it is for appearances only. PowerShell has converted your object into [Microsoft.PowerShell.Commands.Internal.Format.FormatEndData] for the purpose of displaying on screen. At that point...

PowerShell XML formatting issue

xml,powershell

You're missing a set of parentheses (()) at the end of $XmlWriter.WriteEndElement: $xmlWriter.WriteStartElement("Disk$count") # Add tag for each drive $xmlWriter.WriteElementString("DriveLetter","$DriveLetter") # Write Drive Letter to XML $xmlWriter.WriteElementString("DriveSize","$DriveSize") # Write Drive Size to XML $xmlWriter.WriteElementString("DriveFreeSpace","$DriveFreeSpace") # Write Drive Free Space to XML $xmlWriter.WriteEndElement() # <-- Closing Drive Tag - don't forget...

How to pass a switch variable?

powershell,parameter-passing

You can use splatting: $xtraOptions = @{} if ($NoPromptForPushPackageToNuGetGallery) { $xtraOptions.Add("NPFPPTNG",$true) } & "$THIS_SCRIPTS_DIRECTORY_PATH\New-NuGetPackage.ps1" -PushOptions "$pushOptions" -Verbose -ProjectFilePath $project -PO "$packOptions" @xtraOptions If $xtraOptions is just an empty hashtable, @xtraOptions will simply have no effect on the parameters passed. You could also push all the parameters into the splatting table...

Search for certain UPN suffix

powershell,active-directory

You use Get-ADUser and filter on user principal names that end with @sec213.com: $domain = ([adsi]'').distinguishedName $ou = "OU=users,OU=SEC213,OU=Uofguelph,$domain" $suffix = '@sec213.com' Get-ADUser -Filter "userPrincipalName -like '*$suffix'" -SearchBase $ou ...

Powershell Start-Process : This command cannot be executed due to the error: Access is denied

powershell,access-denied,start-process

Ok, I finally got it. It seems that for security reason the System account can not initiate impersonation. The solution here was to change the account running the script, from system to a custom account. And then to allow impersonation for this account in security policies as said here: http://serverfault.com/questions/185813/which-ad-permission-is-required-to-allow-impersonation-of-an-account/193717#193717...

Join SQL query Results and Get-ChildItem Results

sql-server,sql-server-2008,powershell

OK so if the SQL query does not have results then NULL is returned and, in essence, nothing is added to the $dbResults array. Instead lets append the results to a custom object. I don't know what PowerShell version you have so I needed to do something that I know...

Using --check on a md5sum command generated checksum file is failing

powershell,cygwin,md5sum

Using the redirection operator to write the checksums to an output file causes the file to be created with the default encoding (Unicode). md5sum expects an ASCII file. Use Set-Content (or Out-File) to save the file with ASCII encoding: md5sum jira_defect.txt | Set-Content result.md5 -Encoding ASCII You can also work...

Why doesn't “go get gopkg.in/…” work while “go get github.com/…” OK?

windows,git,powershell,github,go

The root cause has been found: Because my computer use a web proxy, so I need to set proxy in environment variable: C:\Users\xiaona>set https_proxy=https://web-proxy.corp.hp.com:8080/ C:\Users\xiaona>set http_proxy=https://web-proxy.corp.hp.com:8080/ C:\Users\xiaona>go get -v gopkg.in/fatih/pool.v2 Fetching https://gopkg.in/fatih/pool.v2?go-get=1 Parsing meta tags from https://gopkg.in/fatih/pool.v2?go-get=1 (status code 200) get "gopkg.in/fatih/pool.v2": found meta tag main.metaImport{Prefix:"gopkg.in/fa tih/pool.v2", VCS:"git",...

Running curl via powershell - how to construct arguments?

powershell

In PowerShell curl is an build in alias to Invoke-WebRequest cmdlet. And aliases have priority in command resolution. To solve your problem you have more specific, use curl.exe instead of curl, so command not resolved to alias. Or you can remove alias Remove-Item alias:curl, but as it is build in...

Rename folders in file share

powershell,powershell-v4.0

How about just after: $delusercount = $delusercount + 1 Insert: rename-item "\\kiewitplaza\vdi\appsense_profiles\$name" ` "\\kiewitplaza\vdi\appsense_profiles\$name.old" Update: You probably also want to insert just after your foreach statement: if($name.EndsWith(".old")) { continue } This will prevent previously renamed folders from being processed and renamed again thus ending up for example with the folder...

Powershell Reading text file

powershell,text,text-files

To read the text after the # characters you must read the file content up to the # characters first. Also, in PowerShell you normally read files either line by line (via Get-Content) or completely (via Get-Content -Raw). You can discard thos parts of the read content that don't interest...

What is the `.` shorthand for in a PowerShell pipeline?

powershell

. is the dot sourcing operator, which runs a script in the current scope rather than a new scope like call operator (i.e. &). That second segment invokes a script block and in that script block defines an advanced function. The advanced function iterates each item in the pipeline and...

Extract e-mail from grouped objects

powershell

Your second bit of code hurts my brain, but I think what you want is to output where multiple accounts use the same email address, grouped by email address. So, let's start with getting duplicates. Your first bit of code is kind of functional, but it really collects way more...

Filter and delete Registry values with Where-Object

powershell,registry

I think this issue is a matter of stepping back and taking a look at the bigger picture. You're focused on the value or a property, and how to get that property name that you aren't taking into consideration that the property is just a part of a larger object,...

Where is git command after installing “GitHub for Windows”? [closed]

windows,git,powershell,github,github-for-windows

After checking, it should under: %LocalAppData%\GitHub For example, in my PC, it is: C:\Users\xiaona\AppData\Local\GitHub\PortableGit_c2ba306e536fdf878271f7fe636a147ff37326ad\bin ...

Change OS Language Silently (Windows 7)

powershell,batch-file,registry,windows-7-x64,regedit

didn't work for me but i found a solution to my problem. I use a XML file to change properties by executing : control.exe intl.cpl,,/f:"c:\Unattend.xml" in CMD.exe as Admin Here is my XML file : <gs:GlobalizationServices xmlns:gs="urn:longhornGlobalizationUnattend"> <gs:UserList> <gs:User UserID="Current"/> </gs:UserList> <!-- user locale --> <gs:UserLocale> <gs:Locale Name="fr-FR" SetAsCurrent="true" ResetAllSettings="false">...

Tab completion for array not shows after first selection

visual-studio,powershell,nuget,tabexpansion

you can use ValidateSet: function global:Add-Shape { param( [ValidateSet("Circle","Square","Triangle")] [string]$Shape, [ValidateSet("Brown","Red","Blue")] [string[]]$Colors ) Write-Host "Shape Name:$Shape" foreach ($i in $Colors) { Write-Host "Color Name:$i" } } ...

Get the users who are having server access for my server

powershell

There's no need for ADSI and PSRemoting. Example: $cComputerNames = @("computer1", "computer2") $cRows = @() foreach ($sComputerName in $cComputerNames) { $cAdminAccounts = Get-WmiObject -ComputerName $sComputerName ` -Class "Win32_GroupUser" ` | Where-Object { ($_.GroupComponent -split '"')[3] -eq "Administrators" } foreach ($cAdminAccount in $cAdminAccounts) { $oRow = New-Object -TypeName PSObject -Property @{...

Increment Serial Number using EXIF

windows,powershell,command-line,exif,exiftool

You'll probably have to go to the command line rather than rely upon drag and drop as this command relies upon ExifTool's advance formatting. Exiftool "-SerialNumber<001-001-0001-${filesequence;$_=sprintf('%04d', $_+1 )}" <FILE/DIR> If you want to be more general purpose and to use the original serial number in the file, you could use...

Add Binding To IIS With PowerShell Without Overwriting Existing

powershell,iis,octopus-deploy

You can use the New-WebBinding cmdlet: New-WebBinding ` -Name $webSiteName ` -Protocol 'http' ` -Port $bindingPort ` -IPAddress $bindingIpAddress ` -HostHeader $bindingHost And use Get-WebBinding cmdlet to check whether the binding already exists....

How to create a powershell script that triggers a NuGet Update-Package –reinstall?

powershell,nuget-package

You should run the update command from nuget.exe. One of the parameters of the update command is FileConflictAction, which tells what action to take when asked to overwrite or ignore existing files referenced by the project: overwrite, Ignore, None. You might have to wrap everything in a powershell script, possibly...

Send email with body consisting of objects

email,powershell,foreach

Also if you want it to look more nice and readable you can do something like this that will spit it out in a table: $body += "<body><table width=""560"" border=""1""><tr>" $bodyArray[0] | ForEach-Object { foreach ($property in $_.PSObject.Properties){$body += "<td>$($property.name)</td>"} } $body += "</tr><tr>" $bodyArray | ForEach-Object { foreach ($property...

Powershell workflow - Get-Service not filtering

powershell,workflow

I have no idea why -Name [wildcard] works and -DisplayName [wildcard] doesn't (inside a workflow), but you can use Where-Object to accomplish the filtering if you like: workflow Restart-Services{ $services = Get-Service |Where-Object -FilterScript {$_.DisplayName -like "S*"} Foreach -Parallel ($svc in $services){ $name = $svc.Name Restart-Service -Name $name } }...

How do I select a string from a string and replace it in powershell?

powershell

Not the best regex but this would be a good start. You aren't specific about what the line looks like so I will assume that it is on its own line with variable whitespace and or text. Get-ChildItem C:\temp\*.asp | ForEach-Object{ $file = $_.FullName (Get-Content $file) -replace '(.*UserRights\s*)"(.*?)"(.*)','$1("$2")$3' | Set-Content...

Recursive check files and perform zip if a particular file type exists

windows,powershell,batch-file,recursion,cmd

If you retrieve all images using the Get-ChildItem cmdlet you can group it by directory and get all information you need: $root = 'c:' $7zipPath = "C:\Program Files\PeaZip\res\7z\7z.exe" Get-ChildItem $root -recurse -Filter '*.jpg' | group Directory | select -expand name | foreach { $directoryName = get-item $_ | select -expand...

win32_physicalMemory.Capacity returns null in powershell

windows,powershell

It's because with powershell 2.0 you can't access an array with that method. get-WmiObject win32_physicalMemory -Impersonation 3 -ComputerName "localhost" | select -expand capacity that will work the other powershell 2.0 computers you mention probably only have one stick of memory, so it doesn't return an array...

Testing for path in SysWOW64 returns true if path does not exist, but does exist in System32

excel,powershell,automation,system32,syswow64

Assuming: C:\Windows\SysWOW64\config\systemprofile\Desktop exists, but: C:\Windows\System32\config\systemprofile\Desktop does not. 64bit PowerShell: Test-Path C:\Windows\SysWOW64\config\systemprofile\Desktop True Test-Path C:\Windows\System32\config\systemprofile\Desktop False 32bit PowerShell: Test-Path C:\Windows\SysWOW64\config\systemprofile\Desktop True Test-Path C:\Windows\System32\config\systemprofile\Desktop True The second test in the 32bit PowerShell is redirected from system32 to syswow64. Checks for syswow64 are usually not...

Find the New Drives connected through iSCSI

powershell,iscsi

Compare the DriveLetter property of the two sets: Compare-Object $initial $final -Property 'DriveLetter' Expanding the property will give you just the drive letter: $driveLetter = Compare-Object $initial $final -Property 'DriveLetter' | select -Expand 'DriveLetter' To be on the safe side you could add a filter that restricts results to "right...

Piping ADComputer objects to New-PSDrive

powershell

You need to correctly interpolate the $_.DNSHostname and escape the $ in D$. Try: -Root "\\$($_.DNSHostname)\D`$" ...

Get IP address of the Network Adapter of a computer having No gateway

powershell,ip-address,gateway

$configs=gwmi win32_networkadapterconfiguration | where {$_.ipaddress -ne $null -and $_.defaultipgateway -eq $null} if ($configs -ne $null) { $yourtargetIP= $configs[0].IPAddress[0] } # $yourtargetIP will have the IP address to make the gateway from In fact, should you have more than one IPv4 address on your network card, $configs[0].IPAddress will have them all,...

Parsing local HTML file using New-Object -ComObject “HTMLFile” broken?

html,powershell,powershell-v5.0

You could try with an Internet Explorer COM object: $ie = New-Object -COM 'InternetExplorer.Application' $ie.Navigate("file://$($PWD.Path)/passwordreminder.html") do { Start-Sleep -Milliseconds 100 } until ($ie.ReadyState -eq 4) # do stuff I don't have PowerShell v5, though, so I can't test. If HTMLFile is broken, this might be as well. You can call...

website creation fails with serverfarm not found Azure Powershell

json,powershell,azure,server-farm

It looks like the web app is unable to find the server farm (AKA app service plan) since it's in a different resource group. To fix this, try creating the ServerFarm and web app in the same resource group. i.e. use this command: PS C:\scripts> New-AzureResourceGroup -Name "azurepowershellush" -TemplateFile F:\DeployerScript\Acquiacom.AcquiaDrupal7SQL.0.3.16-preview.json...

Add new property based on a different objects property

arrays,regex,parsing,powershell

From the guess of it you just need one more calculated property on the end there for 'Pool'. You already have, and tested, the logic. Just need to implement it. $poolProperty = @{Label="Pool";Expression={ $lunID = $_.'LOGICAL UNIT NUMBER'; $pools | Where-Object{$_.LUNs -contains $lunID} | Select-Object -Expand 'Pool Name'} } $LUNSSummary...

Retain carriage returns in text filtered through a regular expression

regex,powershell

As @Matt pointed out, you need to read the entire file as a single string if you want to do multiline matches. Otherwise your (multiline) regular expression would be applied to single lines one after the other. There are several ways to get the content of a file as a...

Turn environment variable into an array

powershell

Split the value of the environment variable at whatever delimiter is used. Example: PS C:\> $env:Path C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\ PS C:\> $a = $env:Path -split ';' PS C:\> $a C:\WINDOWS\system32 C:\WINDOWS C:\WINDOWS\System32\Wbem C:\WINDOWS\System32\WindowsPowerShell\v1.0\ PS C:\> $a.GetType().FullName System.String[] Edit: The PowerShell equivalent to bash code like this for a in ${MYARR[@]} ; do...

Function inside Where-Object clause

powershell

If an AD user doesn't have a set GivenName attribute, or if you forgot to retrieve it by specifying -Properties GivenName in your AD cmdlet call, $_.GivenName will evaluate to $null. [Encoding]::GetBytes() has a number of overloads: byte[] GetBytes(char[] chars) byte[] GetBytes(char[] chars, int index, int count) byte[] GetBytes(string s)...

Logging actual error when script fails

powershell,automation,error-logging

Change this: catch { $status = "FAILED" Write-Verbose "`tFailed to Change the administrator password. Error: $_" } to this: catch { $status = "FAILED" Write-Verbose "`tFailed to Change the administrator password. Error: $_" $errmsg = $_.Exception.Message } to preserve the error message(s). And change this: if($Status -eq "FAILED" -or $Isonline...