Powershell How do I reference files with brackets in the name

Create a file called Valid[File].txt and stick some text in it. Start powershell and go to the directory. gc Valid[File].txt should display the value in the file. It returns blank. If you use tab auto-completion it escapes the name: gc 'Valid[File].txt' but still returns nothing. How do I reference files with brackets in their names?

Null coalescing in powershell

Is there a null coalescing operator in powershell? I'd like to be able to do these c# commands in powershell: var s = myval ?? "new value"; var x = myval == null ? "" : otherval;

PowerShell: What is the difference between 1234 and (1234)?

I was hoping that someone could help me out with the following: Function Get-FormattedNameValuePair([string] $name, [object] $value) { return "$("{0,-24}" -f $name) : $("{0,15:N2}" -f $value)" } Write-Output (Get-FormattedNameValuePair -name MyField -value 1234) The above returns: MyField : 1234 I was expecting, however: MyField : 1,234.00 The expected result is correcly returned if I add evaluation brackets around the 1234: Wri

Hosting powershell import-module failure

I'm trying to host powershell and run Get-Windowsfeature which requires the "ServerAdmin" module. The OS is Server 2008 R2. I can run "Import-module ServerAdmin" at the PS comamnd prompt with success, so I know the machine config is good. However, I cannot get it to work in my custom c# host. I've tried two approaches, shown below. The first, using the import-module command, reports the error "The specified module 'ServerAdmin' was not loaded because no valid module file was found in any modu

In powershell how can a simulate the shift key being held down?

I need to run the following 2 lines of code to open an access database. The issue is this database has an auto loaded model form that blocks the rest of the powershell script from running till it's closed. $ms_access = New-Object -ComObject "Access.Application" $ms_access.OpenCurrentDatabase("C:\db.accdb", $false) I can avoid the dialog when opening the database if the shift key is pressed. I've tested this and it works. Now I would like to not have to hold the shift key while running my pow

Powershell Search for folders created after date X and copy them

I need to go through a large folder (let's call it D:\Files ) which contains about 50.000 folders and about 1 million files, and copy all folders that were created (not modified) after August 31th 2012, including everything in their subfolders (including second/third/fourth level deep subfolders etc.) and files (also files in subfolders, no matter when they got changed) in those folders, for them no matter when they were created, as long as they're in a "higher up" folder that go created after A

Powershell How to rejoin domain when trust relationship is lost

I have a number of virtual machines which have snapshots applied by using a PowerShell script. Occasionally, the virtual machines lose their "trust relationship" with the domain. This breaks the script as I can no longer use PowerShell remoting to get into the machines and configure them. How can I remotely reset the trust relationship of these virtual machines? Perhaps there are possibilities for rejoining the domain that don't involve remoting? Any alternate solutions to manually rejoining t

Powershell Cannot find path 'SharePath' because it does not exist

I am running command to copy a file from shared location to the local machine. Command is Copy-Item '\\ServerName\share\Setup\Setup.msi' 'C:\Windows\Temp\RiversandSetup' This command is works fine when I run it from Server1. But when i run same command from remote machine by opening a session it fails with error 'Cannot find path 'SharePath' because it does not exist.'. Command is $sessions = New-PSSession -ComputerName RemoteServerName Invoke-Command -session $sessions -ScriptBlock {Copy-Item

Can calculated properties in Powershell be refactored into a Function?

For instance, I have several date attributes I'd like to retrieve from a single folder. I'd like to format them in a particular format. I've found a way to do this using Get-Date inside of a calculated property. PS B:\abrabackups> Get-ItemProperty -Path .\AbraSuite01.03.2014 | select Name,@{Name="CreationTime";Expression={($_.CreationTime | Get-Date -format 'ddd MMM dd yyyy HH:mm:ss') + ' GMT-000' }} | ConvertTo-JSON However, if I do this for the rest of the date attributes I have to c

Powershell ConvertTo-Html modifies a text variable

I am trying to write a variable contents into a html file, but it gets modified by ConvertTo-Html. the code: $nb = 10 $text = '<font color="#008000">All ' + $nb + ' test(s) passed</font>' $file = "$env:USERPROFILE\Desktop\test.html" Write-Host "`$text = " Write-Host $text Write-Host Write-Host "(`$text | ConvertTo-Html -Fragment) =" $text | ConvertTo-Html -Fragment prints: $text = <font color="#008000">All 10 test(s) passed</font> ($text | ConvertTo-Html -Fragment)

Does Powershell have an Aggregate/Reduce function?

I realize there are related questions, but all the answers seem to be work-arounds that avoid the heart of the matter. Does powershell have an operation that can use a scriptblock to aggregate elements of an array into a single value? This is what is known in other languages as aggregate or reduce or fold. I can write it myself pretty easily, but given that its the base operation of any list processing, I would assume there's something built in I just don't know about. So what I'm looking for

Powershell Script says "Site doesn´t exist" when trying to upload to SharePoint

I got a script which uploads all files from a Folder to SharePoint-site: asnp "*sh*" $url=Read-Host "Enter Site Url" $web=Get-SPWeb -Identity $url if($web) { try { $list = $web.Lists.TryGetList("Documents") $files = Get-ChildItem -Path "D:\Manju" -Force -Recurse foreach ($file in $files) { $stream = $file.OpenRead() $done= $list.RootFolder.Files.Add($file.Name, $stream, $true) Write-Host $done.Name "Uploaded into t

Powershell function dispose or abort handler

I have a pipe function that allocates some resources in begin block that need to be disposed at the end. I've tried doing it in the end block but it's not called when function execution is aborted for example by ctrl+c. How would I modify following code to ensure that $sw is always disposed: function Out-UnixFile([string] $Path, [switch] $Append) { <# .SYNOPSIS Sends output to a file encoded with UTF-8 without BOM with Unix line endings. #> begin { $encoding =

This powershell doesnt give item count to all the sub or sub-sub or sub-sub-sub folders

I am trying to get a count of each folders in a document library. There are many folders under the parent. Each folder may have few more folders and each one of this may have child, grand child folders. I can add lot more coding but I have a feeling it could be done better way. Please suggest. $web = Get-SPWeb "http://inside.cnv.uk/sales/SouthWest" $list = $web.Lists["SalesManJR"] $folders = $list.RootFolder.Subfolders foreach ($folder in $folders) { if (!$folder.Name.Equals("Forms"))

Powershell Set registry key to open notepad++

I tried running this script using the ISE, and I also tried to run it on the command line as administrator. It freezes at the "Remove-ItemProperty" line. I've tried to remove that step, but then it freezes at the next step "Set-ItemProperty". It looks like the New-Item lines are working fine. if (Test-path "HKCR:\") { } else { New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT } Add-Type -AssemblyName System.IO.Compression.FileSystem function Unzip { param([string]$zip

Enabling Proxy server using Powershell remoting

I am trying to add a Proxy server to a remote server(ServerB) using PowerShell Remoting. However each time, the proxy is cleared after being set. Below is the code which I use: Invoke-command -computername ServerB -authentication Negotiate -scriptblock{$regKey="HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" $proxyServer = "" $proxyServerToDefine = 'our.proxy.server:port' $proxyServer = Get-ItemProperty -path $regKey ProxyServer -ErrorAction SilentlyContin

Powershell Add header to multiple CSV files

I'm looking for a way to add a header line into multiple CSV files. Problem with this code below is that it will add an extra empty row at the end of each file. I don't understand why there is extra empty line but I need to delete those lines. $header="Column1,Column2,Column3,Column4,Column5,Column6" Get-ChildItem .\ -Recurse -Filter *.csv| Foreach-Object { $header+"`r`n"+ (Get-Content $_.FullName | Out-String) | Set-Content -Path $_.FullName }

Powershell Test non-idempotent web methods with Pester

I'm attempting to test a PowerShell command (Set-PropertyValue) that sets a property value of a SharePoint list item. The function use the Invoke-WebMethod function do to the actual work. My current Set-PropertyValue.Test.ps1 file: # include stuff omitted Describe 'Set-PropertyValue' { # # arrange # # set $url, $list, $id, $property variables ... # the value that it should be $expected=10.5 BeforeEach { # get the property's current value $original = Get-PropertyV

How do I download all versions of a file in TFS with PowerShell?

I have Visual studio PowerTools installed and am trying to download the physical files that are associated with every changeset. I can find all changesets associated with a file and downloaded the latest version of the file by performing the following: $tfsServer = Get-TFSServer 'http://myserver/tfs' $history = Get-TfsItemHistory -HistoryItem $tfsHistoryItem -Server $tfsServer $tfsProjColl = Get-TfsProjectCollection -Uri $tfsRootUrl $tfsVersionControl = $tfsProjColl.GetService([Microsoft.TeamF

Powershell MS Access (ADODB connection) slow on .Close()

Newb Question: I'm working on a PowerShell script that will store it's "working data" in a local MS Access database file using the method outlined in this blog post. Everything seems to be functioning, but when adding around 500 records to the database file, the subsequent $connection.Close() command takes in excess of 20 seconds to complete. Is this normal? Thanks in advance! EDIT - Relevant code below: # setup & open the internal database $dbCursor = 3 $dbLock = 3 $connection = New-Ob

Find and replace in Text Box in Header of Word Doc using Powershell

I am trying to use Powershell to do a find and replace of some text within a Text Box that is within the Header of a Word Document (.docx). I was able to get it working for text outside of the Header but not that within. I think it is failing because I am not correctly accessing the contents of the Text Box, so I added in the final line (before quit and save) to see what the text was but it printed out blank for each of the three Items in my Header. This is my first time using Powershell and I t

How to create Active Directory users and put them under Organization Unit using PowerShell?

I have OUs that have the following form: Accounts |->Normal |->100 |->A |->B |->101 |->A |->B And so on with more OUs. What I want to do is I want to bulk create users under each A and B OU. In each A and B, I want to have 10 users. And I want their name to have the following form: Account-100-A-01, Account-100-A-02, and so on. Basically, the word Account followed by the OU number which can be from 100 to

Actions on powershell window closing with 'x'

There is at least this question on how to initiate actions on shell closing. The problem is it doesn't catch closing powershell window with 'x' button. Apparently it doesn't generate said event. Is there any way to capture such close and force actions upon it? What I want is to pipe some values upon closing from session variables (hashtable of System.Diagnostisc.Process) to system variables upon closing. So that new session can access them directly.

Replacing Side Indicator in Powershell

I've hit a dead end and I'd like your expertise on the subject :) I have 2 Files. Printer name and their Driver - with a NoteProperty of Name and DriverName Printer Drivers - with a NoteProperty of Name (The driver name) and MajorVersion The whole point of it is to know which printer has what type of driver as in: Printer DriverName MajorVersion I know that the output of Get-Driver just gets the driver name and the printer name. Whilst Get-DriverPrinter gets the driver and MajorVersion.

Powershell Exchange Web Services (EWS) - Appointment Resources

I managed to create an appointment to an impersonate account with EWS command-lines. But I want to include a room (Exchange Room Mailbox) as Resource / Location. In my script I've added the two command-lines below : $NewAppointment.Location($RoomName) $NewAppointment.Resources.Add($RoomMail) $RoomName and $RoomMail are found by the Get-MailBox command-lines : $Room = Get-MailBox $CSV.Room $RoomName = $Room.DisplayName $RoomMail = $Room.UserPrincipalName or $Room.PrimarySmtpAddress Edi

Powershell Attach available EBS volume when new instance gets launched for windows server

I am using below script to re-attach the "available" volumes when the instance starts but somehow it's not working.I have attached snippet of my cloud formation template. Tq Under LaunchConfiguration I am creating the EBS volumes BlockDeviceMappings: - DeviceName: /dev/sda1 Ebs: VolumeType: gp2 VolumeSize: '100' - DeviceName: /dev/sdb Ebs: DeleteOnTermination: "false" VolumeSize:

Powershell set ad user title to group name

I want to set the title of all users in a set of groups to the names of said groups. All of the groups begin with "Position - " in the name. Here is an example of what I know I can do manually for each group: get-adgroupmember -identity "Position - Accounts Payable Specialist" | get-aduser -properties title | % {set-aduser $_ -title "Accounts Payable Specialist"} As you can tell, I'm manually removing the beginning "Position - " part of the group name, so if anyone knows of way to do thi

Sovled: Powershell - How to store arguments to a variable and use it?

I have written a CMD script for batching atlas packs, and it works fine. CMD Script set OutputDir=%1 set MaxSize=%2 set Scale=%3 set TpCmd=--format unity-texture2d --smart-update --max-size %MaxSize% --scale %Scale% TexturePacker %TpCmd% --data "%OutputDir%.tpsheet" --sheet "%OutputDir%.png" "D:\xxx" . . Recently I am learning PowerShell and try to write a script that could works like above. PowerShell Script $AtlasMaxSize = 4096 $AtlasScale = 0.5 function Pack-Atlas($FileName) { $At

Powershell Need to find totals for Resource Group Spend based on Cost Management API

I have managed to export an xlsx file that has 2 columns based on a list of amount spent on each Resource Group based on a daily basis over a 30 day period but what I know need to do now is for each Resource Group create a total based on the 30 entries. I have been looking at this link (Using Powershell, how can I sum the values in an excel column and sort by the value of another variable?) that is close to what I am trying to do but I am fairly new to doing this type of Powershell. I only ha

How to exclude some column in CSV using Powershell?

I have csv file looks like this NO ID TOTAL 1 123 1000 2 456 1500 3 123 2500 4 112 4000 I want to exclude once the ID=123 and the TOTAL>3000. Anyone can has idea, please. Thanks a lot. $File = Import-Csv 'SELL.csv' $File | Where-Object { $_.ID -eq "123", $_.TOTAL -lt "3000" } -Exclude | Export-Csv 'SELLREPORT.csv' -NoType

Powershell Delete folder with content exclude folder with content

I need to write a script that deletes folders with last write time ~7 Days. But keep 2 "special" folder with the content in it. Here's my script so far: $source = "D:\TestOrdner" $time = (Get-Date)#.AddDays(-7) Start-Transcript "C:\log_files\log.txt" gci $source -Recurse | ?{$_.LastWriteTime -lt $time} | del -Force -Verbose Stop-Transcript My only problem is how to EXCLUDE the folders with content? My folder to keep: D:\TestOrdner\Test.

Local New-PSSession fails in official powershell linux based docker images

Running powershell core using docker (official microsoft images), I am trying to set up a local session in my script so I can later execute code in that session. I have tried using the following Linux Images: 6.2.3-alpine-3.8 6.2.3-centos-7 6.2.3-debian-9 6.2.3-ubuntu-18.04 In both alpine and debian I am getting error: This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. In both Centos & Ubuntu

Powershell Trying pipe in a list of CSV in to import CSV

So I am trying to pipe in a file list into import CSV: ls *.csv | select FullName | where FullName -NotMatch "fixed" | ForEach-Object { Import-Csv -Path %($_.FullName) -Delimiter ";" } But I am getting this error: Import-Csv : A positional parameter cannot be found that accepts argument 'C:\***\Documents\Daraz Order\order.list.export 2019-11-13.csv'. At line:2 char:1 + Import-Csv -Path %($_.FullName) -Delimiter ";" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo

Powershell Export-Csv - Added new properties doesn't export

This is my very first StackOverflow post so I will try to be undestandable as much as possible :D I'm parsing some .pst files to get all the mails and their properties and then export them as .csv files. The thing is I don't want the attachments as a list or string. I want to create a new column in the CSV for each of them. Let's say this are my datas : Sender : bla@bla.com Receiver : blu@blu.com Subject : How not to die Attachments : BestCatPic.jpg BestDogPic.jpg Then

Debuging Windows firewall rules in VS Code with Powershell

I'm working on powershell scripts whose purpose is to add rules to Widnows firewall. Using VSCode, powershell 5.1 and powershell extension for VSCode. now there are 2 problems: First I just want to run debugger to see if the script is executed with no errors, but what happens is that the rule is added to firewall for real. Is there a way to avoid adding rule to firewall for real, just test if it works, ie. dry-run? Secondly, I can't debug if VSCode is not run as Admin, obviously since I'm mod

Powershell : Not all .dll load from the specified source LoadFrom

I am quite new to powershell and in one of the Powershell Project I am not able to load all the DLLs from the same specified source $dllPath using LoadFrom. As shown, Az.NewUtility (first dll) references all below .dlls and all 9 dlls are present in my DBScripts\KvProviderLib Folder. But powershell automatically loads two from the folder "Az.Accounts\1.2.1\" instead from DBScripts\KvProviderLib As per the functionality this project executes some Powershell commands like Get-AzContex, Get-Az

Is there way to determine whether a Windows Task Scheduler scheduled task is supposed to run today using Powershell?

I have a bunch of scheduled tasks set up in Windows Task Scheduler and I am trying to use Powershell to read the task metadata and determine whether the task has a trigger that will execute (or already has executed) on the current day. I'm using Powershell 5.0 on Microsoft Windows Server 2012 R2 Datacenter. For Daily task triggers, it's straightforward as I can read the trigger's DaysInterval property and if it's 1, then the task is Daily and will execute every day. For Weekly task triggers, I'm

PowerShell command to get members of email group - Get-ADGroupMember not working

I'm trying to find the members of a group email box with PowerShell and the Get-ADGroupMember command but no matter what I use for the -Identity parameter it won't work. One thing I found odd was when using Get-ADObject on the email address it shows the ObjectClass as user. So that has me thinking it isn't set up as a group at all. But I'm sure that when emails are sent to the email address a group of employees gets the email. Maybe there's something strange with our AD configuration? Here's the

PowerShell Custom Columns Grid View

I'm sure i've done something wrong, but i'm playing around with accessing multiple office 365 powershells and it works fine, but I want to add custom columns in my grid view. 1 column saying "Client Name" another saying something else. This is what I've got so far. # Prompt For Login [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') $title = 'Email Address' $msg = 'Enter your email address:' $emailAddress = [Microsoft.VisualBasic.Interaction]::InputBox($msg

replace several lines in a text file using powershell script

I have just recently started working with PowerShell scripts and I am currently working with a .ini file that is being modified by another program as well, which is why I'm looking for a dynamic approach. I have also tried to test it with a .txt file to see if it has another result. The file I'm looking to edit is organized like so: [topic1] Value1=1 Value2=3 Value3=keep [topic2] Value1=2 Value2=4 (... etc.) There are several topics which have different amounts of values, however, topic 1 will

Powershell Can not modify property of an object

I have following file below which I read as Hashtable and need to modify value of a property but it fails to do so with error InvalidOperation: The property 'apiVersion' cannot be found on this object. Verify that the property exists and can be set. Code $template = ConvertFrom-Json ([System.IO.File]::ReadAllText(".\template.json")) -AsHashtable; $template.resources.apiVersion = "d" JSON file { "resources": [ { "apiVersion": "2019-07-01&

What is the simplest way to make Alias in powershell?

I was wondering if there's any simple way to make aliases for powershell like cmd. For example: In cmd, doskey art=php artisan $* where $* is optional. Currently, I'm using the following alias in powershell. function runArtisanCommand { param( [Parameter(Mandatory=$false, Position = 0, ValueFromRemainingArguments = $true)] $command ) php artisan $command } Set-Alias art runArtisanCommand This works somewhat but don't take flags. For example: I can't write art -h or

Powershell PSScriptRoot variable has a value but cannot be used

The PSScriptRoot variable appears to have a value, but it cannot be used. My apologies if this turns out to be silly. What's going on? PS C:\> Get-ChildItem Variable:PSScriptRoot Name Value ---- ----- PSScriptRoot C:\Windows\System32\WindowsPowerShell\v1.0 PS C:\> $PSScriptRoot PS C:\> $PSScriptRoot.Length 0 PS C:\> $PSScriptRoot.GetType() IsPublic IsSerial Name BaseType ----

PowerShell: Copy the content of one file to other several files with regex

people. I have in Folder1 a html file named file1.html that has this content: Folder1 <!-- FLAGS_1 --> <div class="cautareField"> <div align="right"> <a href="https://neculaifantanaru.com/izolarea-cercetatorului-in-cursa-lunga-a-leadershipului.html">&nbsp; <a href="https://neculaifantanaru.com/fr/l-isolement-du-chercheur-dans-le-marathon-de-leadership.html">&nbsp; <a href="https://n

Powershell How to make "Export-CSV" export quoting only texts?

I have an input file with the following data: cod_uf;uf;nome_uf;pop_estimada 11;RO;Rondônia;1796460 12;AC;Acre;894470 13;AM;Amazonas;4207714 issuing the command Import-Csv ".\in.csv" -Delimiter ";" | Export-Csv ".\out.csv" -NoTypeInformation -Encoding utf8 yields: "cod_uf","uf","nome_uf","pop_estimada" "11","RO","Rondônia","1796460" "12","AC","Acre","8

  1    2   3   4   5   6  ... 下一页 最后一页 共 219 页