QuestionBank

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

### 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"))

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

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+"rn"+ (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.

### Need to parse a text file line by line with a certain search string using powershell

I need to parse a text file line by line with a certain search string and if that string is not found in any line, then code should output that entire line to separate text file.

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

### 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 How to use wscript.shell to ALT+Tab?

Is it possible to use wscript.shell to send an ALT+TAB ? $wshell = New-Object -ComObject wscript.shell;$wshell.SendKeys('\t')

### PowerShell - remove first character if a specific character

I want to simply remove the first \ how do I do that? I don't want to remove the first character if it's a letter, only if it's \

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

### How to use wildcard in an xml file using powershell

I want it to return the all nodes where the attribute is ending with "_FG". But it doesn't seem to work if i write the entire name ([@NAME='AKG_PP_GY_FG']) it returns the node. Why is wildcard not working in this situation???

### 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 页