FAQ Database Discussion Community


ACL “fuzzy” comparision

arrays,powershell,comparison,powershell-v2.0
I'm trying to compare ACLs on a folder with a reference set of ACLs, and then list any exceptions. The "fuzzy" part of the equation is that I want to be able to disregard any unknown SID. So creating a reference folder with the perms I want to test won't...

test winrm connectivity on list of systems using powershell

powershell-v2.0,powershell-v3.0,powershell-remoting,winrm,wsman
I want to test whether or not winrm is running on a list of servers. winrm id -r:servername works for individual systems but I want to test recursively for a list from a csv or text file. With output to a file saying "working" or "not working" for each. How...

Using powershell, how do I extract a 7-digit number from a subject-line (of an email ), regular expressions?

powershell,powershell-v2.0
I have the following code which lists the first 5 items in the Inbox folder (of Outlook). How would I extract only the number portion of it( say - 7 digit arbitrary numberss, which are embedded within other text)? Then using Powershell commands, I'd really like to take those extracted...

Export from the hash table to csv results in empty values

powershell,csv,powershell-v2.0
Everything works as expected except for the Path section of the csv file when I export the values. They are blank. Can anyone what is wrong with my code? $ht = @() $files = Get-ChildItem -recurse -Filter *.xml foreach ($file in $files) { $path = $file.FullName $lines = Get-Content $path...

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

powershell,batch-file,escaping,powershell-v2.0,comma
I have a command that I need to run in a Powershell script, the command is : ".\pacli DELETEUSER DESTUSER='"[email protected]`,com"' sessionid=333" | invoke-expression The comma (,) in here :[email protected],com is not a mistake, and that's what is giving me the hard time. I tried to escape the comma with `...

Where can i find PowerShell cmdlet to Object Class documentation?

.net,powershell,powershell-v2.0
I am new-ish to PowerShell, and I have a very Java-centric development background. As such I lean very heavily on the Javadoc for any API that I am using. I am now trying to write some PowerShell code that is a little more robust than just a simple script. I...

Powershell function with two argument give takes one argument [duplicate]

function,powershell,powershell-v2.0
This question already has an answer here: How do I pass multiple parameters into a function in PowerShell? 8 answers I define the powershell function as below function t ($a , $b ) { write-Host '1-', $a write-Host '2-', $b } When calling t(4,5) give 1- 4 5 2-...

Simultaneous PowerShell script execution

powershell-v2.0
I have written the following script for SQL patching: cls $computers = Get-Content D:\Abhi\Server.txt foreach ($line in $computers) { psexec \\$line -s -u Adminuser -p AdminPassword msiexec /i D:\SQL_PATCH\rsSharePoint.msi SKIPCA=1 /qb } My doubt here is to parallelize this script execution on all the servers mentioned in the text file....

Backup SSRS Encryption Keys Using Powershell

powershell-v2.0,ssrs-2008-r2
I have made the following script from google for backing up the SSRS Encryption keys: cls $pwd = "[email protected]@123" $SSRSClass = Get-Wmiobject -namespace "root\microsoft\sqlserver\reportserver\rs_BPSSRS\v10\admin" -class "MSReportServer_ConfigurationSetting" $key = $SSRSClass.BackupEncryptionKey($pwd) $stream = [System.IO.File]::Create("c:\\SSRS.snk", $key.KeyFile.Length) $stream.Write($key.KeyFile, 0, $key.KeyFile.Length) $stream.Close() But I'm getting the following errors: Method invocation failed because [System.Object[]] doesn't contain...

Color a cell on the basis of another cell value

html,powershell,powershell-v2.0
I have a file output.txt having below content: SERVER_NAME MOUNT_POINT TOTAL_SPACE USED_SPACE USED_PERCENTAGE AVAILABLE_SPACE Server_1 /dev 1200G 537G 54% 464G Server_2 /dev 600G 490G 85% 94G Server_3 /dev 600G 402G 69% 181G Backup_server /storage 800G 682G 72% 278G Using following script, I formatted my output.txt file to get a notification...

Processing a list with Powershell on a Scheduled Task

powershell,powershell-v2.0
I'm a newbie to powershell, so I'm not sure if I am over thinking what I want to do, hopefully somebody can help me out. I want to create a Windows scheduled task that calls my powershell script every 4 hours, no problems there. The script needs to process a...

scheduling task in windows 2008 with powershell

windows,powershell,scheduled-tasks,powershell-v2.0,scheduler
i want to schedule task in windows 2008 r2 with powershell. i used $username = "BUILTIN\Users" $TaskName = 'kakaka' $t=1 $TaskRun = "$PSHome\powershell.exe Start-Process -FilePath 'C:\v.exe' -ArgumentList '/a' -Verb runas -WindowStyle Normal" $start = (Get-Date).AddMinutes($t).ToString("HH:mm") schtasks /create /ru $username /tn $Taskname /tr $TaskRun /sc once /st $start /f on using...

Powershell - Looking Up File Owner in Active Directory

powershell,active-directory,powershell-v2.0
How do I look up for information about a file owner in Active Directory? The following doesn't work because it parses Domain\User to the Get-ADUser command $owner = Get-Acl file.txt | Select-Object Owner | Out-String Get-ADUser -Identity $owner I would also like to be able to query users from other...

How to pass a custom enum to a function in powershell

powershell,enums,powershell-v2.0,powershell-v4.0,pscmdlet
When defining a function, how can you reference a custom enum? Here's what I'm trying: Add-Type -TypeDefinition @" namespace JB { public enum InternetZones { Computer ,LocalIntranet ,TrustedSites ,Internet ,RestrictedSites } } "@ -Language CSharpVersion3 function Get-InternetZoneLogonMode { [CmdletBinding()] param ( [Parameter(Mandatory=$true)] [JB.InterfaceZones]$zone ) [string]$regpath = ("HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\{0}" -f [int]$zone)...

How to set file type for files without any type

powershell,powershell-v2.0
In a directory, there are some files without a file type. So they don't have a .xxx, I know their type and I want to set that. How can I get their list and add their type, for example .srt? I can get a list of all files with a...

Install .msi remotely using Powershell

powershell-v2.0,windows-server-2008-r2
I have made he following code using the code present on this forum. cls $computername = Get-Content 'C:\Users\C201578-db\Documents\server.txt' $sourcefile = "\\iceopsnas\LNT_SoftwareRep.grp\CORE\COTS\EMC\Avamar\Avamar_7.0\CR06794393\AvamarClient-windows-x86_64-7.0.102-47.msi" #This section will install the software foreach ($computer in $computername) { $destinationFolder = "\\$computer\C$\Avamar" #This section will copy the $sourcefile to the $destinationfolder. If the Folder does not exist...

In vb.net I need to create a shadow copy, trying to use power shell

vb.net,powershell-v2.0
I have a VB.net backup program. I need to create a shadow copy and it would seem that the easiest way is to just use power shell to create it. If I open a command prompt and go to power shell and type in: (Get-WmiObject -list win32_shadowcopy).Create("C:\","ClientAccessible") it works just...

Specifying certain characters for powershell script to run on

text,replace,parameters,find,powershell-v2.0
This may be a complete shot in the dark, I have done some research and can't seem to find anything on this. But anythings possible with powershell I guess! I asked a question earlier here! on how to change certain characters in a script. $infopath = Get-ChilItem "C:\Users\X\Desktop\Info\*.txt" -Recurse $infopath...

Convert Hashtable Values In-Place

string,powershell,hashtable,powershell-v2.0
I have a hashtable with values that are a mix of int and string (sometimes string array) objects. I want to convert them all to strings, but I don't know an easy way to do this without "rebuilding" the hashtable, converting each value to a string. Is there an easier,...

illegal characters in path using powershell

powershell,powershell-v2.0,powershell-v3.0
I need to verify one path using powershell. The problem is when given the path like Test-Path -Path "\\\10.2.200.13\share\Logger\Logger" its working fine, but my requirement is that, this path will be available in a Notepad - we need to read the path from the notepad then verify it. Here is...

Renaming files with similar pattern

powershell,powershell-v2.0
I have some video files and some subtitle files. There is a common part in the name of each of them, for example *E05*.srt and *E05*.mkv. I'd like to rename each video file to match its subtitle, without .srt of curse. Can you think of any script for that? I...

Powershell Proxy setting

powershell,proxy,powershell-v2.0
With this cmdlet can I check my proxy setting in powershell: $regKey="HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" $proxyServer = Get-ItemProperty -Path $regKey $proxyServer | fl *proxy* Or with this cmdlet: Get-ItemProperty Registry::HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings' | Select-Object *Proxy* My question is, how can I get the proxy settings for another network user?...

Converting Powershell command result to one line

powershell,powershell-v2.0
I am new to powershell and stuck with formatting the results. I have result of my command like below in horizontal format in a row which is of type "object" Name ---- Test Mrs. User12 Test Mrs. User13 Test Mr. User15 Test Mr. User20 How can I get only values...

How to select multi-line strings (including spaces), return true if found - PowerShell/SQL Batch

sql-server,powershell,batch-file,powershell-v2.0,powershell-v3.0
I have used select-string to validate strings found on one line, however I need PowerShell to recognise multi-line strings, as well as meeting all three conditions (see below) Output within .log file that needs to be selected: Return Value ------------ 0 I would want something to validate the following string...

Is there any way to set processor affinity of a powershell script before execution?

powershell,powershell-v2.0,processor,affinity
There are lots of examples showing the use of Get-Process myprocess to change the processor affinity, and some examples using Get-WMIObject; but these won't work for my use. I want to set processor affinity of my script as it executes. Is there a way to declare processor affinity when calling...

How do I run PowerShell 4.0 after upgrading from PowerShell 2.0?

powershell,powershell-v2.0,powershell-v4.0,chocolatey
I have installed DotNet 4.5.2 and PowerShell 4 on my Windows 7 SP 1 workstation using chocolatey: choco install dotnet4.5.2 -y choco install powershell -y They installed without errors and appear in the choco list: choco list --local-only DotNet4.5.2 4.5.2.20140902 PowerShell 4.0.20141001 I previously had PowerShell 2.0 installed, and when...

Moving every n files into a separate folder

powershell,powershell-v2.0
I have several files with a repetitive naming convention, e.g. 1*Intro* 2* 3* … 10*intro* …. I want to move each module into a separate folder. So, I should separate from every *intro* till the next one. Also, I should note that files are numbered and sorted. I guess, the...

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

variables,powershell,powershell-v2.0
I got two variables, filled with: $Var1: Dog Cat Bird $Var2: makes wau makes miau makes beep How can I mix both of them like: $Var3 Dog makes wau Cat makes miau Bird makes beep $Var3 = $Var1 + $Var2 dosen't work...

Powershell v2 and PowerShell v3 Object handling

powershell,powershell-v2.0,powershell-v3.0
When I create object in powershell v2 i am unable to access powershell member properties, which will flowlesly works with PowerShell V3. e.g. if i create below object in v3, $Services = @(); $item = @{}; $item.Name = "ServiceName"; $item.Action = 2; $item.ActionTime = Get-Date -Format "yyyy-MM-dd HH:mm:ss"; $obj =...

Sort and format in email

powershell,powershell-v2.0,powershell-v3.0
I'm new to Powershell and I'm trying to send the output by email of the following piece of code, if I send it to the console, it is formatted nicely, but when I pipeline it into an email, the retrieved objects are not lined up. $bios = Get-WmiObject Win32_BIOS -ComputerName...

Powershell error Add-PSSnapin “Microsoft.SharePoint.PowerShell”

powershell,sharepoint,sharepoint-2010,powershell-v2.0
I am getting an error when I run below command from sharepoint 2010 managment shell using admin rights. Add-PSSnapin Microsoft.Sharepoint.Powershell Add-PSSnapin : Cannot add Windows PowerShell snap-in Microsoft.Sharepoint.Power shell because it is already added. Verify the name of the snap-in and try again ...

How do I backup my mssql database using powershell

sql-server,powershell,powershell-v2.0,database-backups
I keep getting this error anytime i run my powershell script to backup my databases. I can't seem to figure out what the problem is. Any help will be most appreciated. Exception calling "SqlBackup" with "1" argument(s): "Backup failed for Server 'MyServer'. " At C:\Users\hp1\Desktop\scripts\backup.ps1:28 char:5 + $smoBackup.SqlBackup($server) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...

exlude folder with specific extensions after recursively search

powershell,powershell-v2.0
Hello scripting guys, get-childitem -recurse -path "C:\test\Media" -include *.mp3 , *m3u, *.jpg shows me my two subfolders “AudioAndJPG” including *.mp3, *m3u, *.jpg fles and “VideoJPG” including *.avi, *.mkv, *.jpg files. (Of course only *.mp3, *.m3u and *.jpg are shown). How can i exclude the whole folder which contains video and...

How can I get with PowerShell the project version in Visual Studio?

visual-studio,nuget,powershell-v2.0,post-build-event
I'm writing a simple PowerShell script for creating NuGet packages on Post-build event. For this I'd like to set the package version automatically to the project version. Currently it's hardcoded in my command: nuget pack .\MyProject.csproj -properties configuration=release -version 1.0.0 -outputdirectory .\NuGet\Packages Is there a way to change the above...

Custom Powershell Host Invoke external program without console window

c#,visual-studio,powershell,powershell-v2.0
I'm writing an embedded powershell host in C# (windows application), and if there is an external program called in the pipeline the console window flashes as it's executed. Ping and netstat are examples of this as shown in the following code snippet using (PowerShell PowerShellInstance = PowerShell.Create()) { PowerShellInstance.AddScript("Get-Content test.txt;...

Sort an PowerShell array according to a part of content in each element

arrays,sorting,powershell,powershell-v2.0,powershell-v3.0
I am working with a powershell script where I have an array containing following data. Each row below is an element in the array. Each element has two parts seperated by "/" a number (can be 1-12 digits) and a date time. I need to sort the array according to...

Rename-Item fails when there are brackets (regex/escaping issue)

regex,windows,powershell,powershell-v2.0
I am simply trying to rename files using PowerShell, but the script below does not work when there are brackets: $old = [regex] '_Jackson\(UK\)_' $new = [regex] '_Jackson\(US\)_' get-childitem "K:\CustomerVideos" -include @("*.webm","*.mp4","*.mkv") -recurse | foreach-object { rename-item $_ -newname ( $_.name -creplace $old,$new ) } Rename-Item : Cannot rename because...

Remove numerous characters including underscore

powershell-v2.0
I have a large number of files in numerous directories with this type of naming convention: "filename_yymmdd.csv", etc. I need to remove the underscore and the yymmdd. So the new file name would be "filename.csv". i need to recursively search through for .csv files and remove the date and underscore...

Use PowerShell to add and remove shortcuts from Explorer's favorite bar

powershell,windows-7,powershell-v2.0,explorer
Is there a way to use PowerShell to manage Explorer's shortcut? For example, remove 7346 then add a link to ~/Projects/9999? ...

Run Exchange Powershell commands from Linux using Ruby/WinRM

ruby,powershell-v2.0,winrm,exchange-management-shell
I am attempting to run the enable-mailbox command for existing users in Active Directory from a ruby script. I'm using this winrm gem. So far I have been able to connect to the exchange server using winrm and kerberos authentication. I can run an exchange management shell from powershell. From...

Unexpected token error when I have the variable already defined

powershell,powershell-v2.0
Simple script but can't figure out why I am getting the error : It should just write the machines that were successful to one text file and the failed to another. Here is the error I am getting : Unexpected token '$ip' in expression or statement. + CategoryInfo : ParserError:...

Excessive whitespace around filepath

powershell-v2.0
PS C:\> $pst_path = $outlook.Session.Stores | where { ($_.FilePath -like '*.PST') } | Select Filepath | format-table -hide PS C:\> $pst_path C:\Users\abelej\Documents\Outlook Files\My Outlook Data File(1).pst PS C:\> _ I've tried using $pst_path.trim() method to trim leading and trailing spaces but with no luck. You can see above all the...

Is there any way to view the source for built-in powershell cmdlets?

powershell,powershell-v2.0,powershell-v3.0,cmdlets,pscmdlet
I want to modify the code used in compare-object (so that I use the same algorithm for comparison, but modify output and possibly add some more to it). Is there any way to view the code that is used for this, or would I just have to guess? This could...

How to write an array to a file?

arrays,powershell-v2.0,cpu-usage
I try to write a short script what will count average value for CPU for last XY minutes. I wrote something like that (just short overview). First part of the script just stored values in tmp file. From this values is count avg value: $CPU= ........ Add-Content "myfile.txt" "$CPU" $array=(Get-Content...

Hashtable key syntax to refer to embedded hashtable element

powershell,hashmap,hashtable,powershell-v2.0
Assuming that I have a hashtable: $tokens = @{ Id=9999; Title="Lorem ipsum dolor sit amet"; [email protected]{Name="John Doe"; Email='[email protected]'}; [email protected]{Name="Jane Doe"; Email='[email protected]'} } And a template that I would like to populate, replacing the tokens (e.g. __Title__) with the corresponding hashtable's value: /* Author: __Author.Name__ <__Author.Email__> Analyst: __Analyst.Name__ <__Analyst.Email__> Request: __Title__...

Powershell - query servers with roles installed

powershell-v2.0
I have a txt file with all the server names. I want to query each server in the txt to see if RDS is installed. So far it works fine. But the export needs to have servername and the installed role. how can I pass the servername to the output...

Creating info files with same names of folders in different location

powershell,powershell-v2.0
Morning, I've got this section of powershell code which scans a selection of zip files in $path, and creates individual info files in $dest with the name of the info file being the same as the zip files in $path. $path = 'C:\Users\X\Desktop\Powershell\Zip' $dest = 'C:\Users\X\Dekstop\info\' Get-ChildItem -Path $path -Recurse...

Powershell script for going into texts files within a directory and replacing characters

powershell,text,replace,find,powershell-v2.0
Morning all, I'm trying to work out how to go into a number of text files within a directory, and replace the characters with the following: 'BS' = '\' 'FS' = '/' 'CO' = ':' What I managed to get to so far is: (get-content C:\users\x\desktop\info\*.txt) | foreach-object {$_ -replace...

Pass command-line arguments to script's 'internal' function

powershell,powershell-v2.0
I have a simple PowerShell script: # Foobar.ps1 Param( [parameter(Mandatory=$true)] [alias("i")] [String[]] $IDs, [parameter()] [alias("b")] [string] $Bar ) Foreach ($ID in $IDs) { write-host $ID } write-host $Bar PS> .\foobar -i 1234,5678 -b 'hello world' 1234 5678 hello world I want refactor the script to make use of the advanced...