FAQ Database Discussion Community


Merge Text Files and Prepend Filename and Line Number - Powershell

powershell,text,powershell-v3.0
I've been trying to adapt the answer to this question: powershell - concatenate N text files and prepend filename to each line My desired output based on an example of 2 .txt files: First.txt lines of data Second.txt more lines of data Output.txt First1 lines of First2 data Second1 more...

how to write a powershell command to get a formatted date?

powershell-v3.0
I would like to know how to use Get-Date command in windows powershell to get the date format in following way. Tue 27/01/2015 20:10:21...

Implement the subcommand pattern in PowerShell

powershell,powershell-v3.0
Is it possible to implement the subcommand pattern in PowerShell? Something like: command [subcommand] [options] [files] Examples: Git, svn, Homebrew What would be the general architecture? A single function that delegates the actual work to script blocks? Each subcommand isolated in its own PS1 file that is dot-sources by the...

powershell Parsing a text file

regex,parsing,powershell,powershell-v3.0
Really new to the whole powershell thing and I was hoping someone could give me a hand. so I have a text file with multiple users (in the exact format) username:t-Hancock phoneNumber: 555555555 username:a-smith PhoneNumber: 987654321 username:r-Byer phonenumber: 123456789 I am trying to get all these users into an object...

Executing a batch file in a remote machine through PsExec

windows,powershell-v3.0,psexec,sysinternals
I am trying to run a batch file (in the batch file I have just written 'notepad') on a remote PC through PSExec. The psexec command below runs in my laptop but fails to do anything on the remote PC. I don't even see 'notepad' running on the list of...

PowerShell Iterate through array and if match copy-item

powershell-v3.0
I would like to be able to look through an array and if a source directory contains a copy of the file required from the text file place a copy of the file into another folder. $Source=get-content .\2cHotfix.txt $Available=gci foreach($item in $Source){ $_ -match $Available;` Copy-Item $item .\InUse\*.* } sample...

Upload file to SharePoint 2010 using PowerShell and the OData API

powershell,sharepoint,sharepoint-2010,odata,powershell-v3.0
I'm attempting to upload a file to SharePoint 2010: Function Add-Attachments() { [CmdletBinding()] Param( [Parameter(Mandatory=$True)] [int]$Id, [Parameter(Mandatory=$True)] [string[]]$Paths ) BEGIN {} PROCESS { $url = "http://server/resource/_vti_bin/listdata.svc/TheList($Id)/Attachments" Foreach ($Path in $Paths) { Write-Verbose "Attaching $Path ..." $headers = @{ 'Slug' = "TheList|$Id|$(Split-Path $path -Leaf)" } $Payload = @{filename=(Split-Path $path -Leaf);filecontent=([IO.File]::ReadAllBytes($path))} Invoke-WebRequest...

Escape single quotes in PowerShell

powershell,sharepoint,sharepoint-2010,powershell-v3.0
I'm trying to build a SharePoint 2010 listdata.svc query that resembles: http://server/FooList/_vti_bin/listdata.svc/FooList?$select=Title,Id,OwnerId,Status&$filter=(OwnerId eq 1234 and Status eq 'Ready') Single quotes don't work: $url = $url + '&$filter=(OwnerId eq 1234 and Status eq 'Ready')' Nor does escaping them with back-ticks: $url = $url + '&$filter=(OwnerId eq 1234 and Status eq `'Ready`')'...

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 - Why is Using Invoke-WebRequest Much Slower Than a Browser Download?

powershell,amazon-ec2,amazon-s3,powershell-v3.0
I use Powershell's Invoke-WebRequest method to download a file from Amazon S3 to my Windows EC2 instance. If I download the file using Chrome, I am able to download a 200 MB file in 5 seconds. The same download in PowerShell using Invoke-WebRequest takes up to 5 minutes. Why is...

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...

Create PowerShell script file in ASP.NET

c#,asp.net,powershell,webforms,powershell-v3.0
I research a lot in last couple days and I found only solutions for execute powershell scripts but I did't find how to create .ps1 file. I have web app (ASP.NET) and I need to dynamically create/save script without running. If anyone have some direction please tell me note. Version...

Powershell select-string usage

powershell-v3.0
This is my script that removes any lines that contain /> in it. I have a new requirement which is to leave all lines that have index="1"/>. Example of the full line I want to leave is <LOTLEVEL index="1"/>. Logic would be, If line contains index="1"/> leave the line, if...

Powershell: How to do a Select-String search with an -Exclude for multiple lines of text in another file

powershell-v3.0,select-string
Project: I have a log file that is being added to continuously. In this log file on occasion an error (error always includes with "Unable to import" and a unique ID) is added. I need to be alerted by email when this error is added to the log file. Current...

Powershell to select columns from csv when condition matches

powershell-v3.0
My csv looks like this SvnDirectory Release export Yes import service Yes My script should select only those SvnDirectory names whole Release value is "Yes" and store in an array. Script $svnDirectory = import-csv training.csv | % {$_.SvnDirectory -and $_.Release -eq "Yes"} Write-host $svnDirectory Without the and condition the script...

Dots in function parameter name

maven,powershell,maven-3,powershell-v3.0
Is a parameter name with dots possible in powershell? The obvious approach - see Dmaven.failsafe.debug fails: function mvn-failsafe-debug { param ( [string] $Dmaven.failsafe.debug="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_shmem,server=y,address=Maven,suspend=n", [parameter(Position=0, ValueFromRemainingArguments=$true)] $args ) & "$env:M2_HOME\bin\mvn.bat" $args } ...

Distinguish Windows services with the same ProcessName

powershell,memory,windows-services,monitoring,powershell-v3.0
I am adjusting a monitoring system which checks if a service is running or not. It does that by checking the process name and it's memory consumption. Once it drops below 1 MB an alert is triggered. Also I use the memory usage value to display it in a graph....

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 =...

Powershell Copy-Item remote machine copying to wrong location

powershell,powershell-v3.0,powershell-remoting
I am on server A (dev box) creating a remote Powershell session to server B (IIS server). The script copies from server C (build machine) to server B. I got passed (I think) the multi-hop credential issue EXCEPT the copy is copying to the wrong location on server B. It...

How to get the tfs build folder name, generated inside dropfolder while running the TFS build

tfsbuild,powershell-v3.0,tfs2013
Created the TFS build definition and scheduled to run automatically. Also copying the build output to a drop folder at server location(\server\TFSBuildOutput). When build runs, a separate folder is created inside drop folder(\server\TFSBuildOutput) in the format - $(BuildDefinitionName)_$(Date:yyyyMMdd)$(Rev:.r) Now i want to get the name of this newly generated folder...

start-process with a special name, or handle to kill it

powershell,powershell-v3.0
We have a number of node.js programes that all are created with powershell. We used the start-process to spawn the node.js executable in the background (node.exe). We would like to give each one a different "handle" so that we can later use the powershell command stop-process to kill them. e.g....

Update SharePoint list entry using ListData.svc and PowerShell

powershell,sharepoint,sharepoint-2010,odata,powershell-v3.0
Is there a way to update a SharePoint 2010 list entry using PowerShell without using the SharePoint client? If so, how? To get the desired fields, I would: $url = 'http://myserver/resource/_vti_bin/ListData.svc/TheList(1234)?$select=Id,Title,StartingDate,Hours' $webRequest = Invoke-WebRequest -Uri $url -Method Get -UseDefaultCredentials [xml]$xml = $webRequest.Content $properties = $xml.feed.entry.content.properties $properties | Format-Table -Property Id,Title,StartingDate,EndingDate,Hours...

Access SharePoint expanded properties

powershell,sharepoint,sharepoint-2010,odata,powershell-v3.0
I'm accessing a SharePoint lists has an associated stakeholder entity--I'm having difficultly accessing the stakeholder's properties. The 'primary' content's properties are located on xpath /feed/entry/content/properties/*. The stakeholder's properties are located on xpath /feed/entry/link/inline/entry/content/properties/*. Assuming that I include the stakeholder's name in the odata query: http://server/list/_vti_bin/listdata.svc/TheList?$select=Id,Title,Stakeholder/Name&$expand=Stakeholder How do I reference the...

remotely login to linux using powershell

linux,powershell,ssh,powershell-v3.0
I am using the following script (ssh module)to remotely login to a linux server to start a process. This 'prompts' me for the credentials at the command line. I am trying to run this script through Bamboo So, is there a way I can pass the credentials while I run...

How can I import a module into powershell without waiting for it to complete?

powershell,module,powershell-v3.0,import-module
I have a psm1 file I want to load into my $profile, but it takes long to load. I would prefer to load it "in the background" where it doesn't prevent immediate action in my powershell prompt. If I run it as a job, I don't get the functions from...

Powershell 3: preventing excessive memory usage for webrequest

powershell,powershell-v3.0
I wrote a short script that lets me download a file. Invoke-WebRequest -Uri $r2.Forms.Action -WebSession $myWebSession -OutFile $destination$filename The whole download is buffered in memory, which is obviously not optimal for larger files. I was wondering (and I couldnt find) a way/ property to prevent this and stream straight to...

How to read and parse from multiple files?

powershell,powershell-v3.0
I have 3 text files that I need to read each content, then grab the relevant fields, and then finally output these fields all together to a new text file. All fields per file should be output as one line (no newline). My problem is with the final output step....

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...

More-efficient way to modify a CSV file's content

powershell,csv,powershell-v3.0,ssms-2012
I'm attempting to remove some of the detritus that SSMS 2012 generates when a query's results are exported as CSV. For example, it includes the word 'NULL' for null values and adds milliseconds to datetime values: DATE_COLUMN,DATETIME_COLUMN,TEXT_COLUMN,NUMBER_COLUMN 2015-05-01,2015-05-01 23:00:00.000,LOREM IPSUM,10.3456 NULL,NULL,NULL,0 Unfortunately, Excel doesn't automatically format datetime values with fractional...

call custom functions from Add-ons menu in Powershell ISE

powershell,menu,powershell-v3.0,powershell-ise
I've developed a collection of functions that are to be used by our Desktop and Service Desk team and have deployed a custom powershell ISE profile to each staff member that loads the module file that contains all of the functions. I've been asked to make them more user friendly,...

Load script from PowerShell ISE's command environment

powershell,powershell-v3.0,powershell-ise
Is there a way to open a script file ($profile or otherwise) from within the IDE's command environment (PS> prompt), such that it loads in the IDE itself? # loads the current user/current host profile in Notepad (probably because .PS1 is associated w/ Notepad.exe) PS > ii $profile # same...

Automate process of Disk Cleanup cleanmgr.exe without user intervention

powershell,registry,powershell-v3.0,resource-cleanup
I am developing a powershell script file which shall execute some disk cleanup without user intervention. The user shall not be able to configure anything. When I run cleanmgr.exe /d c: sageset:1 a popup window appears to select files/folders to be cleaned(cleanup options). This will create a registry entry containing...

Prevent coercion

powershell,powershell-v3.0
Assuming: Function Invoke-Foo { Param( [string[]]$Ids ) Foreach ($Id in $Ids) { Write-Host $Id } } If I do this: PS> Invoke-Foo -ids '0000','0001' 0000 0001 If I do this: PS> Invoke-Foo -ids 0000,0001 0 1 In the second case, is there a way to prevent the coercion, other than...

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...

Display element's attribute using PowerShell's Format-Table

powershell,sharepoint,sharepoint-2010,powershell-v3.0
Assuming Atom feed's XML: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <feed ... > <title type="text">Attachments</title> <id>http://server/list/_vti_bin/listdata.svc/list(1234)/Attachments/</id> <updated>2015-05-12T13:00:05Z</updated> <link rel="self" title="Attachments" href="Attachments" /> <entry> <id>...</id> <title type="text">spreadsheet.xlsx</title> <updated>2015-05-12T13:00:05Z</updated> <author>...

Exporting Drive Letters to Columns

powershell,server,powershell-v3.0
I am trying to get a list of drive letters to post to a CSV across the page not down, EX: systemname, Drive1,Drive2,Drive3,Drive4,Drive5 SVR,C:,D:,E:,F: not systemname, deviceid SVR, C: SVR, D: SVR, E: SVR, F: The code i put together and that has worked before for my other projects is...

Passing Variables Into Statement Block Brackets In PowerShell

powershell,powershell-v3.0,powershell-v4.0
I have an array I want to pass into a variable which is then passed into a Register-ObjectEvent. It looks like the following: $body = @{ project_id = $project_id task_token = $task_token } $action = {Invoke-RestMethod -Uri http://localhost/temp.php -Method Post -Body $body} Register-ObjectEvent -InputObject $timer -EventName Elapsed -SourceIdentifier MyTimer -Action...

How do I set-location ad: to a different active directory domain with Powershell

powershell,active-directory,powershell-v3.0
I have the Active Directory module installed on my Windows 7 workstation using PowerShell 3 and when I use "Set-Location AD:", it is using my current domain. Is it possible to set my base location to a different domain? Import-Module ActiveDirectory Set-Location AD: Get-ChildItem (shows current DC info) I would...

How can Powershell copy an entire folder structure but exclude one folder and its contents

powershell,powershell-v3.0
This seems like a simple operation but I can't figure out how to get Powershell to copy an entire folder structure from one location to another but exclude one folder (called 'connections') and its contents. I've tried combining Copy-Item and Get-ChildItem like so cpi (gci folder1 -Exclude connections) folder2 -recurse...

How to rename the most recent files in order?

powershell-v3.0
I have a powershell script (triggered by automation software). It effectively renames files by the directory, followed by an underscore, leading zero and sequential numbering. $i = 0 $folder = Any-path Get-ChildItem -Path $folder |ForEach-Object {$extension = $_.Extension $newName = $_.Directory.Name + '_{0:d3}{1}' -f $i, $extension $i++ Rename-Item -Path $_.FullName...

Running function as a job in powershell

powershell,powershell-v3.0,powershell-v4.0
Below is the funtion for just pinging all the machines from a win-form appliaction: I am just pinging all the machines and displaying result in output box and saving it into a csv file: As the UI running as Single thread mode, I am not able to perform any other...

Add value into three different variables from Foreach-Object

powershell,powershell-v3.0
I have a file (config.cfg) which has three strings like this: host:user:pass In my Unix code, I do this to get and assign the value into three different variables: $FTP_HOST=$( cut -f1 -d: config.cfg ) $FTP_USER=$( cut -f2 -d: config.cfg ) $FTP_PASS=$( cut -f3 -d: config.cfg ) How can I...

Copying folder contents from one server to another using Windows PowerShell scripting

powershell-v3.0
I am trying to copy the folder contents from Server 1 to Server 2 using PowerShell scripting. The code is working, but the files inside sub-folders are getting copied outside them. Probably i am missing something or not doing correctly, as i am beginner to PowerShell scripting. Could anyone please...

why custom tasks on windows scheduler do not execute..?

windows,powershell,scheduled-tasks,powershell-v3.0,windows-scheduler
I tried creating a task in windows task scheduler, where i put trigger on some specific time. but even when time passes task is not triggered. my task always shows me status "Ready", even at anticipated time is shows "Ready" not "Running" why is it so, if there is any...

Install msi file with PowerShell v3.0

windows-installer,powershell-v3.0
I am trying to automatically install SharePoint 2013 and for this I have to install a MSI file with PowerShell but it returns an error when I execute it. This is the error message: Error: This command cannot be run due to the error: No application is associated with the...

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...

Improve code to use optional switch parameter in PowerShell

powershell,powershell-v3.0
I have a Powershell function that wraps Invoke-WebRequest. Depending on the value of parameter $verbose I want to use -Verbose or not. The code I have wrote using an API does the work... but I feel there should be a better way with less lines of code. It feels wrong...

Powershell $? Symbol

powershell-v3.0
What does the PowerShell $? symbol mean and what is it used for? I'm currently using it in the context of the following code block: Invoke-Command -Session $session -ScriptBlock { param($proc, $arg) Start-Process $proc -ArgumentList $arg -Wait } -ArgumentList $processName, $processArgs if ($? -ne $true) { } So I'm assuming...

Changes last name, first name to first name, last name in last column CSV powershell

string,powershell-v3.0
I am a newbie to powershell. I was trying to change last name, first name to first name, last name in the last column in CSV file and export all of the changes I have made to a new csv file. The data looks like this. Sport, Gender, Zip, Recruiter...

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...

PowerShell + AD: Return users from within any groups in a specific OU, plus count

active-directory,powershell-v3.0,quest
PowerShell "white belt" here, first time poster. I'll try not to lower the collective IQ of such a helpful community while I'm here! :) I'm running PowerShell 3.0 with Quest installed. My organization has an Active Directory OU with several Security Groups that all control VPN access - these were...

Retrieving session ID from COM method

powershell,com,powershell-v3.0
I have a method named GoLogon in a COM object named BS.Logon which requires 5 parameters: Username Password ApplicationID XMLRoot IPAddress This method logins to the web server with the username, password, and other details, and returns the session ID. I have written the Powershell script to call the method...

PowerShell to get Folder Owner 3 Folders Deep

powershell,permissions,acl,powershell-v3.0,folders
I need to get a list of all the folders owners on a shared network drive. However, I want to limit the recursion to just 3 folders deep (some of our users will create folders several levels deep, despite us telling them not to). I've found the below script, and...

Create powershell parameter default value is current directory

powershell,powershell-v3.0
I'm hoping to create a parameter who's default value is the 'current directory' (.). For example, the Path parameter of Get-ChildItem: PS> Get-Help Get-ChildItem -Full -Path Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.). Required? false Position? 1 Default...

scheduling task with powershell

powershell,scheduled-tasks,powershell-v3.0,webclient-download,schtasks.exe
I am trying to schedule task on remote computer where i was successful in scheduling a task on remote computer its not executing. like i wanted to download a file on some triggered time. in my task scheduler it shows task is completed successfully but i m not seeing any...

Enhancing the pipeline's content?

powershell,powershell-v3.0
Let's assume that you have a command that compresses files using 7-zip that accepts values from the pipeline: Function New-Archive { [CmdletBinding()] param ( [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)][Alias('FullName')] [string[]]$Files, [string]$Archive='Archive.zip' ) BEGIN {} PROCESS { Foreach ($File in $Files) { & 7z a -tZIP $Archive $File } } END {} } Assuming the...

Replace NTFS Permissions with PowerShell

permissions,powershell-v3.0,ntfs
I'm working with a fileserver that was connected to an old domain a few years ago. For some reason, the old domain is now gone and replaced by a new one. The only problem is that there are still some NTFS Permissions that uses the old users, of the old...

Powershell - WMI & AD Objects

powershell,powershell-v3.0
Can someone please show me a solution to the following problem or a better way to approach it - all I am trying to do is return some information about a selected server and contain the AD Description Field: $cred = Get-Credential -Credential "test_user" $servername = "servername" [wmi]$os = Get-WmiObject...

powershell error recovery from native applications

powershell,powershell-v3.0
On a windows 2008R2 server, I have to use the native schtasks to schedule tasks. I created the below script that first deletes any old task with the ID of Watson, and then schedules it. The only issue is cosmetic. Schtasks /DELETE will give an error of: ERROR: The system...