spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » POWERSHELL » Page 1
PowerShell, Display My TXT Log file with different Colors:
Look at the following: (Get-Host).UI.RawUI.ForegroundColor This should give you some ideas. You could use a switch -regex to change the foreground color based on the content of the string.

Categories : Powershell

Powershell Test-Path Not returning correct result
$ADComputer will be an object, with several properties.. not a string with computer name. Assuming that $Computer is the computer name, you could either use $Computer like so - Test-Path -Path "\$Computerc$Users*AppDataLocalMicrosoftOutlook*Internet Calendar*.pst" Or, if $Computer is not the name of the computer, check the properties of $ADComputer object, in the interactive shell, and find the

Categories : Powershell

Cannot process argument transformation on parameter
This worked in a simple script: param([System.Tuple[string,string][]]$files) foreach ($file in $files) { [console]::WriteLine("Item1: {0}, Item2: {1}", $file.Item1, $file.Item2) } Then setting up the data and calling the script. PS C:data> $fileList = @([System.Tuple]::Create("Flinstone","Rubble"), [System.Tuple]::Create("Simpsons","Flanders")) PS C:data> .soTuple.ps1 -files $fileL

Categories : Powershell

Powershell convert value to type "System32 error
Remove the hyphen from the beginning of the second line: $str1 = "Number of files in " + $ErrorFiles.ToString() + " was " + $PreCountErrorFiles.ToString() + " number of files deleted " + ($PreCountErrorFiles - $PostCountErrorFiles).ToString() + " and " + $PostCountErrorFiles.ToString() + " are left." + "`n" + - "Number of files in " + $Archivefiles.ToString() + " was " + $PreCountArchiv

Categories : Powershell

Execute Powershell Script from powershell indicate it executed successfully
Exceptions bubble up automatically... If you still have concern, there must be something else, please clarify in the question.. As for the success / failure of the scripts. the scripts can also be thought of as a function in a file.. i.e. they can have a param block to take parameters, and return data. In your case. you can have it return a flag indicating success or failure.

Categories : Powershell

How to join the output of object array to a string in PowerShell?
You can join $s using a comma. Try this: $s -join ',' Edit, I noticed you want a space after the comma, so: $s -join ', ' Output is this: abc, def, ghi Edit, if you want to save the result in $s do the following: $s = $s -join ', ' New Edit. I didn't see your code, now it's clearer. Try the following: [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.RMO") | Out-N

Categories : Powershell

Get-Process : A positional parameter cannot be found that accepts argument 'Get-ChildItem'
Since you appear to be copying and pasting this to the command line I will assume there was a typo that caused this issue. After a couple of quick tests to try and guess what the accident was I was unable to replicate exactly. Not being a scripter might make this harder but I recommend saving this code to a ps1 file so that you can just double click on it. Get-ChildItem "F:My MusicKaraoke*.mp3"

Categories : Powershell

Powershell move files with special characters
Did you try: Move-Item -LiteralPath $sDir$File -Destination $dFold Move-Item allows wildcard matches when using the -Path parameter, so a substring [SP2] is interpreted as a single character 'S', 'P', or '2' instead of the string '[SP2]'. Using the parameter -LiteralPath instead of -Path prevents that.

Categories : Powershell

Create Variables from CSV
You can do it like this: $csv = Import-Csv k:keys.csv | Where-Object {$_.School -eq $School} then you can access the data by dot notation, for example $csv.WindowsKey note that the properties contain arrays and not string data if you select multiple values so you will have to loop through it Regards

Categories : Powershell

Moving files based on file name with powershell
Rely on the fact that everything in the file name up until the Sxx block is the destination if you just replace the . with a space: # Retrieve the filenames $Directory = "C:SYSLOGServer and FirewallLogs" $FileNames = (Get-Item $Directory).GetFiles() foreach($FileName in $FileNames) { # Split the filename on "." $Pieces = $FileName-split"." # Counting backwords, grab the pieces up un

Categories : Powershell

Function-scoped variable in PowerShell (with Advanced Methods)?
I have to assume that you're using Powershell 2.0 for this. In that version, when you set the value of a parameter in the Begin block, it will not retain that value in the Process or End blocks. This was changed in Powershell 3.0+. For v2.0, assign a non-parameter variable the value of the parameter and use that throughout all 3 blocks: function Test-Cmdlet { [CmdletBinding()] Param (

Categories : Powershell

Receive-Job: Not Getting Results
Your job isn't returning anything. Basically a job is like running a new console in the background. Any output made to that console can be retrieved with Receive-Job. However in your case, you assigned the result to your variable and that's it. The following should help: Start-Job -Name 'GroupName' -ScriptBlock { Get-PSSnapin -Registered | Add-PSSnapin; $aryProperties = @( "SamAccoun

Categories : Powershell

How to get effective permissions with PowerShell for an attribute on the AD user object
Check out the PowerShell Access Control module. Version 3.0 is implemented almost completely in PowerShell, which makes it pretty slow compared to using Get-Acl, but I think it can do what you're asking for (and I'm working on the speed issue). It has a function named Get-EffectiveAccess that can compute the effective access of a principal over a securable object, but I don't think that's what yo

Categories : Powershell

PowerShell - Create list/array of Folder Names to run a Script Against
Get all of the top-level directories, then iterate through them. Get-childitem \fileserverhomeshare -directory | foreach-object {.get-orphanhomefolder.ps1 -homefolderpath $_.fullname} If you have sufficient system resources available, you could run multiple instances of the script in parallel using start-job to reduce the overall execution time - but I would recommend limiting to no more than N

Categories : Powershell

User Get-ADUser to list all properties and export to .csv
Query all users and filter by the list from your text file: $Users = gc "C:scriptsUsers.txt" Get-ADUser -Filter '*' -Properties DisplayName,Office | ? { $Users -contains $_.SamAccountName } | select DisplayName, Office | Export-Csv 'C:path oyour.csv' -NoType Get-ADUser -Filter '*' returns all AD user accounts. This stream of user objects is then piped into a Where-Object filter (? is an a

Categories : Powershell

How to use Powershell to list duplicate files in a folder structure that exist in one of the folders
I'd do more or less the same, except I'd build the hashtable from the contents of the includes folder and then run over everything else to check for duplicates: $root = 'C:s' $includes = "$rootincludes" $includeList = @{} Get-ChildItem -Path $includes -Filter '*.cs' -Recurse -File | % { $includeList[$_.Name] = $_.DirectoryName } Get-ChildItem -Path $root -Filter '*.cs' -Recurse -File |

Categories : Powershell

powershell or vbs; split a file into sections based on a line delimiter
Get-Content $inputFileName | Foreach-Object { if ($_ -match "NMAP for") { $outputFileName = "$($_ -replace "NMAP for ").txt" } if ($outputFileName -ne $null) { $_ | Add-Content $outputFileName } }

Categories : Powershell

Getting essential computer info for network admins
function Get-MACAddress { ipconfig /all | findstr "Physical" | Where-Object {$_.length -lt 58} } function Get-IPAddress { ipconfig | findstr "IPv4 Address" } function Get-HostName { get-content env:computername } function Get-UserName{ get-content env:UserName } function Get-DomainName{ get-content env:USERDOMAIN } function CreateCSVdocument { Get-MACAddress | New-Item C:Users$

Categories : Powershell

How to memoize a function in PowerShell?
Well, here's a shot at it. I definitely cannot claim this is a good or efficient method; in fact, even coming up with something that works was tricky and a PowerShell expert might do better. This is massive overkill in a scripting language, by the way (a global variable is far simpler), so this is definitely more of an intellectual exercise. function Memoize($func) { $cachedResults = @{}

Categories : Powershell

Limited powershell start-jobs
Are you sure your code is fine? If you're calling separate powershell sessions multiple times memory can be consumed very quickly. Check process monitor for high CPU or memory usage and ensure your blocks are terminating. Or post the code.

Categories : Powershell

Can I add title rows to a CSV export in Powershell?
You should not need to output to file with export-csv just to read the file back in to make a change. Lets output the data all at once without reading the back in again. $rep = $rep | ConvertTo-Csv -NoTypeInformation $title | Set-Content -Path $reportpath $rep | Add-Content -Path $reportpath Not what I intended since I think you could get this in one line but you dont need to read the file ba

Categories : Powershell

Using Wildcard with WMIC Version Query
The Name property of a CIM_DataFile can't contain wildcards. I don't believe any of them can. However, you can specify the Drive, Path, and Extension to get a list: Get-WmiObject -ComputerName $comp -Class CIM_DataFile -Filter "Drive='C:' AND Path='\Windows\System32\Macromed\Flash\' AND Extension='ocx'" The syntax of Path is a bit flaky. You need the trailing backslashes, for example. You c

Categories : Powershell

Verify if an AD account is locked
The LockedOut property is what you are looking for. When you select * in properties you would get the complete output which would be much larger then what you have in your question. PS M:Scripts> get-aduser mcameron -Properties * | Select-Object LockedOut LockedOut ---------

Categories : Powershell

Delete files recursively in multiple zip folders
This script will find all the files that end with the extension zip" within the root folder. Pass in the root folder (where all the zips live) in as the $path variable. param([string]$limit, [string]$path) $zips = Get-ChildItem -Path $path -recurse *.zip foreach ($zipfile in $zips) { $stream = New-Object IO.FileStream($zipfile.FullName, [IO.FileMode]::Open) $mode = [IO.Compression.Zip

Categories : Powershell

Suppress Console Window when running Start-Job with -Credential
Yes. You can suppress the credential request window by creating a credential object before running any cmdlets/scripts/functions that need it. Of course, there are security considerations when using any stored credentials. Example: $username = 'UserName' $password = ConvertTo-SecureString -String 'Password' -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential $u

Categories : Powershell

power shell two dimensional array comparison error
How did you create $run and $data? Here is how I gave it a try: $run = @() $run += ,@("d13", "m0051") $run += ,@("d13", "m0052") $run += ,@("d21", "m0083") $run += ,@("d21", "m0084") $run += ,@("d26", "m0103") $run += ,@("d33", "m0131") $run += ,@("d34", "m0136") $data = @() $data += ,@("d13", "m0052") $data += ,@("d21", "m0084") $data += ,@("d26", "m0103") $data += ,@("d33", "m0132") $data +=

Categories : Powershell

Powershell file name check
_ is a valid character for variable names, so the expression evaluated $FileDate_, which is not defined. This can be prevented by using a subexpression: $FileDate = Get-Date -format yyyyMMdd $FileExists = (Test-Path "\UNCTestShareSuperFile_$($FileDate)_*") or by putting the variable name in curly braces: $FileDate = Get-Date -format yyyyMMdd $FileExists = (Test-Path "\UNCTestShareSuperFile_${Fi

Categories : Powershell

Date format to show month as text
Can be done like this: [datetime]::now.toString("dd MMM yyyy") Or if you want yesterday: [datetime]::now.addDays(-1).toString("dd MMM yyyy")

Categories : Powershell

How to get data from TXT file?
This should work: $data >> "$env:USERPROFILE/sc.txt" $result = Get-Content "$env:USERPROFILE/sc.txt" | foreach { if ($_ -match "<h2>(.*?)</h2>"){ $matches[1]}}

Categories : Powershell

Powershell open Ps1 if true
The error is rather self-explanatory. The script doesn't find sdsSysMain.ps1 in the current working directory. You can output the current working directory in your script like this: (Get-Location).Path If you want to run sdsSysMain.ps1 from the same directory as the script calling it, change this: Powershell -noexit ".sdsSysMain.ps1" into this: $scriptPath = Split-Path -Parent $script:MyInv

Categories : Powershell

Include Script1 with a declared variable whose value will be determined when called by Script2
For dynamically updated values you need a function: PS C:> Get-Content .source.ps1 function Get-Invocation { "Running: {0}" -f $script:MyInvocation.MyCommand.Name } PS C:> Get-Content . un.ps1 . .source.ps1 Get-Invocation PS C:> . un.ps1 Running: run.ps1 or at least a scriptblock that you invoke in the script: PS C:> Get-Content .source.ps1 $invocation = { "Running: {0}" -f $script:MyInvoca

Categories : Powershell

why run diskpart with script can't get correct result?
Most likely you saved script.txt in Unicode format. Open the file in notepad, click File → Save As..., select "ANSI" from the dropdown list Encoding at the bottom of the dialog, and click "OK". PowerShell uses Unicode as the default encoding, so you need to explicitly set the encoding to ascii when creating such files from PowerShell: @" select disk 0 select partition 1 ... "@ | Out-File 's

Categories : Powershell

Powershell - Unable to retrieve active directory attribute after clearing it
You might be removing the property from the AD object and not it's value during the command: $directoryEntry.Properties["netbootmachinefilepath"].Clear() You Could try something like this to clear the Value of the property not the property its self. $directoryEntry.Properties["netbootmachinefilepath"].Value = $null Or $directoryEntry.Properties["netbootmachinefilepath"].Value.Clear() Also

Categories : Powershell

Azure Traffice Manager External End Points
In the scenario you describe you would first need to define a new hostname for your external endpoint in DNS (i.e. www-1.mysite.com) and configure your webserver to accept requests for that hostname. Once that is working you add the www-1.mysite.com to Traffic Manager as an external endpoint and the finally update DNS for www.mysite.com to point to Traffic Manager.

Categories : Powershell

Conditionally Supply 'Credential' Parameter to Functions
Since you're already using splatting, can't you just supply a Credentials entry in the $params hashtable (instead of calling it Creds)? Then, you will only supply credentials if it's in the hashtable...you don't need an "else". That isn't quite what you want, though. When I want to "conditionally" supply credentials parameter (or any other parameter), I create a separate hashtable that is eith

Categories : Powershell

Export Powershell output to CSV
Nate, In Powershell v3.0, the Export-CSV cmdlet introduced the -Append parameter. Reference: http://technet.microsoft.com/en-us/library/hh849932.aspx Not knowing the version of Powershell you are using, this may require an update on your side to make use of the new functionality. In my own cases, I generally see the opposite issue if I forget to -Append to my CSV; I will only end up with the

Categories : Powershell

How to show progress in powershell script (determine OS version of computers from input list)
I think you're looking for something like this: $ips = Get-Content 'C:psservers.txt' for ($i=0; $i -lt $ips.Count; $i++) { Write-Progress -Activity 'Getting OS information ...' -status 'Scanning server' ` -PercentComplete ($i*100/ $ips.Count) ` -CurrentOperation $ips[$i] $server = Get-WmiObject -Computer $ips[$i] -Class Win32_OperatingSystem New-Object PSObject -Property @{ 'H

Categories : Powershell

Is it possible to deploy code to an Azure Cloud Service without a build step?
One thing that may be helpful is to realize that the web role in Cloud Services are just VM's using IIS. For that reason, you can connect to them just like any other server, via RDP, FTP, etc. Our team often bypasses the overhead of simple things, like deploying a new CSS file, an image, etc. by simply copying it in the old school way. Again, not sure if this helps you, but old school techniques

Categories : Powershell

Merge 2 columns of a CSV such as first+.+last to first.last with powershell
You could do something like this: Import-Csv -Path 'C:lahusers.csv' | select @{n='FullName';e={"{0}.{1}" -f $_.first, $_.last}} | Export-Csv -Path 'C:lahfullname.csv' -NoType

Categories : Powershell


Recently Add
Errors to Enable PSRemoting on win2008R2 and Win7
PowerShell, Display My TXT Log file with different Colors:
Powershell Test-Path Not returning correct result
Cannot process argument transformation on parameter
Powershell convert value to type "System32 error
Execute Powershell Script from powershell indicate it executed successfully
How to join the output of object array to a string in PowerShell?
Get-Process : A positional parameter cannot be found that accepts argument 'Get-ChildItem'
Powershell move files with special characters
Create Variables from CSV
Moving files based on file name with powershell
Function-scoped variable in PowerShell (with Advanced Methods)?
Receive-Job: Not Getting Results
How to get effective permissions with PowerShell for an attribute on the AD user object
PowerShell - Create list/array of Folder Names to run a Script Against
User Get-ADUser to list all properties and export to .csv
How to use Powershell to list duplicate files in a folder structure that exist in one of the folders
powershell or vbs; split a file into sections based on a line delimiter
Getting essential computer info for network admins
How to memoize a function in PowerShell?
Limited powershell start-jobs
Can I add title rows to a CSV export in Powershell?
Using Wildcard with WMIC Version Query
Verify if an AD account is locked
Delete files recursively in multiple zip folders
Suppress Console Window when running Start-Job with -Credential
power shell two dimensional array comparison error
Powershell file name check
Date format to show month as text
How to get data from TXT file?
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.