w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Simple PowerShell Script to loop through 1 CSV file to create a new CSV file from another
Borrowing Shay's awesome CSV field enumeration code: $offices = Import-Csv 'C:path ooffices.csv' Import-Csv 'C:path ousers.csv' | % { foreach ($prop in $_.PSObject.Properties) { $offices | select @{n=$prop.Name;e={$prop.Value}}, OFFICES } } | Export-Csv 'C:path ocombined.csv' -NoTypeInformation

Categories : Powershell

Invoke one PowerShell script from Another PowerShell script with passing arguments
PS C:> gc . est2.ps1 . est1.ps1 'foo' Write-Host 'bar' PS C:> gc . est1.ps1 $a = $ARGS[0] -split '' [array]::Reverse($a) Write-Host ($a -join '') PS C:> . est2.ps1 oof bar

Categories : Powershell

Powershell script to create an xml file
You can try and pipe to the ConvertTo-Xml cmdlet. Here's how the output looks like for 3 process objects. You can then pipe it out to a file : PS> gps | select name,id -first 3 | ConvertTo-Xml -As String -NoTypeInformation <?xml version="1.0"?> <Objects> <Object> <Property Name="Name">AppleMobileDeviceService</Property> <Property Name="Id">1568</Property> </Object> <Object> <Property Name="Name">audiodg</Property> <Property Name="Id">5140</Property> </Object> <Object> <Property Name="Name">Babylon</Property> <Property Name="Id">4908</Property> </Object> </Objects>

Categories : SQL

Converting .rtf files to .doc and then .doc back to .rtf in PowerShell (WMF registry fix) - file size optimization
Here is the final working script ( without deleting , I decided I do not need it ) param([string]$rtfpath,[string]$docpath = $rtfpath,[string]$docpath2 = $rtfpath2) $srcfiles = Get-ChildItem $rtfPath -filter "*.rtf" $docfiles = Get-ChildItem $docPath -filter "*.doc" $saveFormat =[Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatDocument"); $saveFormat_back =[Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], "wdFormatRTF"); $word = new-object -comobject word.application $word.Visible = $False function saveas-DOC { $name = $rtf.basename $savepath ="$docpath tf" + $name + ".doc" write-host $name Write-Host $savepath $opendoc = $word.documents.open($rtf.FullName); $opendoc.saveas([ref]$savepath, [ref]$saveFormat); $opendoc.c

Categories : Powershell

script file: name editing and renaming using PowerShell
You can use Get-Child item with recursive option to load all the jpg files and rename it using Rename-item command. Get-ChildItem -r -path "C: est" *.jpg | % { if(!$_.PSIsContainer -and $_.Name.Contains('_')) {Rename-item $_.FullName ( $_.BaseName.Split('_')[1] +"p" + $_.Extension) } }

Categories : Windows

powershell script too slow (file enumeration)
Get-ChildItem may be slowish (though it appears to be about twice as fast in PowerShell 3 as it was in v2), write-host is slowing you down a lot too. On a directory structure containing 27000+ files, the following code ran in 16.15 seconds vs 21.08 seconds for your code. On a smaller directory containing about 2400 files, it was 1.15s vs 1.22s. gci $path -file -Recurse | select @{name="fpath";expression={$_.fullname.replace($src,"").replace("","/")}},lastwritetime,@{Name="size";Expression={$_.length}},@{Name="id";Expression={$_.basename}}| select id,size| ConvertTo-Json The resulting JSON doesn't have the header yours does, but you should be able to handle that after the fact.

Categories : Powershell

Powershell script can't find module when run via -File param
I'm dumb :P There is a dropdown in TeamCity where you can select the runmode of x86 or x64. It was set to x86. I changed it to x64. Now it executes under the correct version. Still curious why the modules wouldn't load in x86 though... Also, it's weird that SysWOW64 correlates to x86 and System32 correlates to x64

Categories : Powershell

Running PowerShell script from a batch file successful on 32 bit but fails on 64 bit
You are running your script from C:Windowssystem32 and there's no such script (usually this happens when the bat is started with admin privileges ). Change the directory or call it with a full path. The easiest way to fix this - set cd /d %~dp0 at the start of the batch script to change the directory on the location where the script is

Categories : Powershell

PowerShell - How to execute script and save results in text file
If you want to sample every 2 seconds, and show max,min,ave for the whole period that cmd.exe is running then the code below will work. But if you want to sample the data every two seconds and show the max,min,ave for that 2 second interval then all 3 will be the same (because you only have 1 sample during that interval). You'll have to sample more frequently (like every .2 seconds) and then reset the $stats array after every two second interval. The code below isn't designed for that. $cmdProcess = start-process cmd -passthru $delay = 2 $stats = @() $previous = ($cmdProcess|Get-Process).cpu while (-not $cmdProcess.HasExited) { $latest = $cmdProcess|Get-Process $delta = $latest.cpu - $previous $delta $stats += $delta $previous = $latest.CPU sleep $delay } $stats|% {$_/$delay}

Categories : Powershell

Need a powershell script to use a parameter to manipulate/read in fields from another csv file
You can react to the server name like this: $csv = Import-Csv 'C:path oyour.csv' ... if ( $alert.PrincipalName -eq 'MYSTSERVER.CONTOSO.COM' ) { if ( $alert.MonitoringObjectDisplayName -match '.*[(.*?)]' ) { $targetserver = $matches[1] } } else { $targetserver = $alert.PrincipalName } $newdata = $csv | ? { $_.ServerName -eq $targetserver } ` | select ServiceOwner, 'Application Tier' ... $alert.CustomField2 = $newdata.ServiceOwner $alert.CustomField3 = $newdata.'Application Tier' ...

Categories : Powershell

Powershell script to check if a file exists on remote computer list
The equality comparison operator is -eq, not eq. The boolean value "true" in PowerShell is $true. And if you want to compare the result of Test-Path to something the way you do, you must run the cmdlet in a subexpression, otherwise -eq "True" would be treated as an additional option eq with the argument "True" to the cmdlet. Change this: if(Test-Path "\$_c$Windowssvchosts" eq "True") into this: if ( (Test-Path "\$_c$Windowssvchosts") -eq $true ) Or (better yet), since Test-Path already returns a boolean value, simply do this: if (Test-Path "\$_c$Windowssvchosts")

Categories : Powershell

Executing Powershell script as different User in Exchange 2007 Powershell
I just found out that executing Remote Powershell Commands/Skripts is not supported with Exchange 2007 (http://howexchangeworks.com/2009/11/exchange-2007-sp2-supports-powershell.html). So I need to wait until the upgrade to 2013. Some workarounds: http://social.technet.microsoft.com/Forums/en-US/exchangesvrgeneral/thread/4596035a-cede-4541-8b8e-e2e9bf1b40dc Or: http://peerfect.blogspot.co.at/2012/10/re-blog-of-my-exchange-remote.html

Categories : Powershell

Powershell start-process script calls a second script - how to make one script only
Windows does not allow a process to elevate while running. There are some tricks but in one way or another they will spawn a new process with the elevated rights. See here for more info. So the easiest way for PowerShell is still using one script to Start-Process the other script elevated.

Categories : Powershell

Powershell-script: Read Contacts from excel file, and create Mailboxes for them on Microsoft Exchange
CSV is certainly the easiest. You can then use Import-CSV foo.csv to read the file. Provided you used the appropriate column header names in the first row you can use them directly: Import-CSV foo.csv | ForEach-Object { $_.Lastname; $_.'Display Name', <# etc. #> } Enable-Mailbox seems to be the command to create Exchange mailboxes.

Categories : Powershell

Powershell Script that will login into powershell for office 365
For the exchange powershell use: $SecPass1 = convertto-securestring -asplaintext -string "PasSword" -force $MSOLM = new-object System.Management.Automation.PSCredential -argumentlist "GlobalAdmin@some.com",$SecPass1 $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $MSOLM -Authentication Basic -AllowRedirection Import-Module MSOnline Import-PSSession $Session –AllowClobber

Categories : Actionscript

Using Powershell FileSystemWatcher on iSeries share
I have not been able to get FileSystemWatcher to work unless the target directory was a Windows NTFS drive. If I specify the drive letter of the mapped directory I get Exception setting "Path": "The directory name W: is invalid." If I use the UNC I get Exception calling "WaitForChanged" with "2" argument(s): "Error reading the \\path.to.my.ibm.i\root directory." Against a Novell file server I get the directory name is invalid if I use a drive letter. If I use a UNC against a Novell drive it does run, but doesn't detect any changes to the file system. Works fine against a local drive and also against a Windows file server on my network.

Categories : Windows

PowerShell - script 1 calls script 2 - how to return value from script 2 to script 1
You could make use of ProcessStartInfo and Process which would allow you to read the StandardOutput. Here's an example of what you might do: $startInfo = New-Object System.Diagnostics.ProcessStartInfo $startInfo.FileName = "powershell.exe" $startInfo.Arguments = "C:scriptscript2.ps1" $startInfo.RedirectStandardOutput = $true $startInfo.UseShellExecute = $false $startInfo.CreateNoWindow = $false $startInfo.Username = "DOMAINUsername" $startInfo.Password = $password $process = New-Object System.Diagnostics.Process $process.StartInfo = $startInfo $process.Start() | Out-Null $standardOut = $process.StandardOutput.ReadToEnd() $process.WaitForExit() # $standardOut should contain the results of "C:scriptscript2.ps1" $standardOut

Categories : Powershell

Batch script checking file size methods?
The only thing I can think of is the file must not exist, in which case %%~zi expands to nothing (not 0). That is easily fixed by explicitly setting size to 0 afterward if size is not defined. for /f %%i in ("file.txt") do set "size=%%~zi" if not defined size set size=0 if %size% gtr 0 ( type file.txt >> %FNAME% ) else ( echo No Data Found On System >> %FNAME% )

Categories : Batch File

How can I share share read/write access to a file within the same process, but forbid it externally?
Files are generally not for multi-user interactions such as this. A database is what is needed here. Then the data you need written can be saved to the database and all the synchronous handling would now be the databases responsibility. If you still require a file, after the data has been input, it would be an idea to generate the file when needed based off the database data.

Categories : C

powershell share permisssion level on a folder
I am using win32_Share.create() in next function: function shareFolder { Param ($folder, $uname) $name = $folder.Name $path = $folder.Fullname $sd = ([WMIClass] "Win32_SecurityDescriptor").CreateInstance() $ace = ([WMIClass] "Win32_ACE").CreateInstance() $Trustee = ([WMIClass] "Win32_Trustee").CreateInstance() $Trustee.Name = $uname $Trustee.Domain = $null $ace.AccessMask = 524288 $ace.AceFlags = 3 $ace.AceType = 0 $ACE.Trustee = $Trustee $sd.DACL += $ace.psObject.baseobject $mc = [WmiClass]"Win32_Share" $InParams = $mc.psbase.GetMethodParameters("create") $InParams.Access = $sd $InParams.Description = "Share" $InParams.MaximumAllowed = $Null $InParams.Name = "test" $InParams.Password = $Null $InParams.Path = $folder $InParams.Type = [uint32]0 $mc.PSBase.InvokeMethod

Categories : Powershell

Starting VB Script from Powershell script - works from PS environment, but not scheduled task
Try running this batch script as a scheduled task: @echo off setlocal set "programdir=C:Program Files (x86)LNGoogleCalSync" set "script=%programdir%lngsync.vbs" pushd "%programdir%" wmic process get commandline | findstr /r [l]ngs >nul || cscript "%script%" popd If that doesn't work: try replacing all MsgBox statements in the VBScript with WScript.Echo.

Categories : Powershell

Passing argument from batch script to PowerShell script fails
Change this command: C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -command "D: estBluebird_1.2.0_RTMReplaceTagsOnConfigFiles.ps1;REPLACE" > C:Temp.out into this: C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -File "D: estBluebird_1.2.0_RTMReplaceTagsOnConfigFiles.ps1" REPLACE > C:Temp.out Is the first command supposed to change the execution policy? If so, you need to specify an actual policy. Set-ExecutionPolicy without any arguments won't work. Besides, it'd be simpler to just add -ExecutionPolicy Bypass to the second command: C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -ExecutionPolicy Bypass -File "D: estBluebird_1.2.0_RTMReplaceTagsOnConfigFiles.ps1" REPLACE > C:Temp.out

Categories : Powershell

Powershell Script : Unzip files and execute bat file within the zip files
Why not embed the one line from the batch file in the powershell script, then you can use the variables in your powershell script. Simply put cmd /c before the copy: cmd /c copy "$NewLocation*.prn" /b \PCPrinter

Categories : Windows

Powershell script works interactively, not within a script
In my opinion: it fails in script because: you start script, define function and variables in script scope script exits once it defines 2 initial jobs job complete, registered action runs, but your function is not visible to it (defined in script scope) so it fails. Two options to solve/ work around it: define RunJobFromQueue function in global scope (function Global:RunJobFromQueue, $global:queue) dot-source a script (. .YourScript.ps1) This works fine interactively, because in that case you define function/ variable in global scope, so -Action can find them just fine.

Categories : Powershell

powershell script Ad script group
Some properties are not included in the default property set of a user object. In that case you need to query the user with the additional (or all) properties, e.g.: Get-ADGroupMember "test" ` | Get-ADUser -Properties * ` | select samaccountname, name, distinguishedname, mail ` | Export-CSV "C: est.csv" -NoTypeInformation AFAIK the (DNS) domain name is not an AD attribute, but you could derive it from the distinguished name: (Get-ADUser "name").distinguishedName -replace '^.*?,dc=' -replace ',dc=', '.' so you could add another property in the select statement like this: @{n="domain";e={$_.distinguishedName -replace '^.*?,dc=' -replace ',dc=', '.'}} As for the referral error: the group seems to be containing members from another domain. AFAIK all of the following requirement

Categories : Powershell

How to get size of zip files in a folder and save the name of file and size of zip file in excel
(for %%I in (*.zip) do echo(%%~nI,%%~zI)>C:UsersanoopnDesktopout.csv To get only the folder's name with the calculated size of all ZIP files together use this: @ECHO OFF &SETLOCAL FOR /f "tokens=3" %%a IN ('dir *.zip') DO ( CALL SET "size=%%free%%" SET "free=%%a" ) (ECHO(%cd%,%size%)>C:UsersanoopnDesktopout.csv

Categories : Batch File

How to share CPU resource to run PHP script faster?
You could use the APC extension http://www.php.net/manual/de/book.apc.php. And store big array's etc. If I am not mistaken this will get stored into the Shared Memory and will be accessable trough all your processors. Also since those variables etc. are cached php won't compile it again that should increase the perfomance of your php application . Thats the only think I could come up with.

Categories : PHP

How do I get total physical memory size using PowerShell without WMI?
If you don't want to use WMI, I can suggest systeminfo.exe. But, there may be a better way to do that. (systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()

Categories : Powershell

Is there any possible way to give share programs not code in Google Apps Script
You may want to investigate Libraries. You can put the segments of the code you want to protect into a library, and then give them code (macros, scripts, whatever) that just calls that library - they will be able to see the code you gave, but not the library. However I don't know how "foolproof" this is if someone was really determined to dig. https://developers.google.com/apps-script/guide_libraries?hl=en

Categories : Google Apps Script

Get-Service in a Powershell Script
The code that you posted is fine. It's something else that you are not showing that does not work. Try this: $script = @" Write-Host "Enumerating installed Services..." -ForegroundColor Green Get-Service | Sort-Object status,displayname "@ $script | Set-Content ./test.ps1 ./test.ps1 The above writes your two lines in a script file and then executes the script. As you would expect it produces desired output. Update 1 Having seen the input, I can now reproduce the problem. Basically if you run this: $a= Get-WmiObject -Class win32_volume -cn $s | Select-Object @{LABEL='Comptuer';EXPRESSION={$s}},DriveLetter, Label,@{LABEL='Free Space (GB)';EXPRESSION={"{0:N2}" -f ($_.freespace/1GB)}} $b = Get-Service | Sort-Object status,displayname $a $b you will see that it does not quite wor

Categories : Powershell

TFS commands in PowerShell script
One option is to run the TF.exe program with the necessary arguments from within your PowerShell script, as you would with any other executable: PS> & "$env:ProgramFilesMicrosoft Visual Studio 10.0Common7IDETF.exe" @("workspace", "/new", "WS1", "/noprompt", "/login:foo,bar", "/collection:baz/tfs") Or you could use the TFS PowerShell cmdlets included in the TFS Power Tools: PS> Add-PSSnapin Microsoft.TeamFoundation.PowerShell PS> Get-TfsChangeset -Latest -Server "http://mytfsserver"

Categories : Powershell

Get-SPSite in Powershell Script
This could be a permissions issue. When run from the command prompt, you have permission to get the Sharepoint site. Investigate how you're running your script when it doesn't work. Make sure the user has permission.

Categories : Sharepoint

cant return right value from powershell script
I'm not sure I understand what you are attempting to accomplish, but I think just adding to the filter will mostly provide the same functionality. Get-WmiObject -class Win32_Share -computername "." -filter "Type=0 and name='TEST12'" | select Name or if you're looking for the Share name associated with a physical path. Get-WmiObject -class Win32_Share -computername "." -filter "Type=0 and path='S:TEST12'" | select Name

Categories : Powershell

PowerShell script ffmpeg
Try this: $oldvids = Get-ChildItem *.mkv -Recurse foreach ($oldvid in $oldvids) { $newvid = [io.path]::ChangeExtension($oldvid.FullName, '.mp4') .ffmpeg.exe -i $oldvid.FullName -y -vcodec copy -acodec ac3 $newvid } $oldvid is a .NET FileInfo object and when it needs to be converted to a string, it can be just the filename and not the whole path. That won't work for files not in the current dir. So just use the FullName property to get the full path.

Categories : Powershell

Script not runing at powershell
For your first question, you need to include the path using double quotes. A suggestion if you can then remove the space in the testing 2 "C: asks esting_2 esting2_$actDate.xml" To log result of the job use Receive-Job cmdlet. One more try: Try to put all paths in double quotes and then surround everything with a single quote after the cmd.exe /c part as shown below. Try to achieve something simpler with a simple task and then try to add complexity $job = Start-Job -name "Hel" -Command { cmd.exe /c '"C:Program Files (x86)Mozilla Firefoxfirefox.exe" /?'}

Categories : Powershell

vbscript to powershell script
Output file names that begin with a particular string: str = "foobar" For Each f In fso.GetFolder("C:JetInfo").Files If LCase(Left(f.Name, Len(str))) = LCase(str) Then WScript.Echo f.Name End If Next Output file names that contain a particular string: str = "foobar" For Each f In fso.GetFolder("C:JetInfo").Files If InStr(LCase(f.Name), str) > 0 Then WScript.Echo f.Name End If Next Write a file name to the registry: Set f = fso.GetFile("C:path osome.file") WshShell.RegWrite "HKCUSoftwareMicrosoftOffice14.0CommonNewSignature" _ , Chr(34) & Replace(f.Path, "", "\") & Chr(34), "REG_EXPAND_SZ" As for your third question: what values do you want to create from the files? It would be quite pointless to overwrite the same value again and again.

Categories : Powershell

T4 Scaffolding - Powershell Script
I would check if the PK was found in the PS, and if not call another template... Personally I would force all the classes in the model to inherit a abstract base class that already has a primary key. That way this will never be an issue. But then again, your purpose might be something I do not know of...

Categories : Misc

Google script: Create and publicly share a folder within existing parent
A combination of DocsList and DriveApp can be useful. /* CODE FOR DEMONSTRATION PURPOSES */ function main() { var parentFolder = DocsList.getFolder('September 2013'); var idNewFolder = parentFolder.createFolder('New Folder').getId(); var newFolder = DriveApp.getFolderById(idNewFolder); newFolder.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.EDIT); }

Categories : Google Apps Script

PowerShell Script and Form Authentication
Need a little more information. You may be able to solve your issue with the following answer how to post data to specific URL using WebClient in C# But I'm curious, what page you are submitting your authentication form to? That page would have this information. If the form is returning data into PS variables. Then the above link shows how to post directly to a page

Categories : Powershell

PowerShell Script Load Aseemblies
That should be associated with this dll: C:Program Files (x86)Microsoft Visual Studio 11.0Common7IDEReferenceAssembliesv2.0Microsoft.TeamFoundation.Client.dll It should be in a similar location for VS 2010. One solution would be to use Add-Type to load it to the current session: Add-Type -Path "$FilePathMicrosoft.TeamFoundation.Client.dll" This solution may be preferable because your script will always check for that dll and it shouldn't break across environments. Your description of the problem makes it sound like the script is very dependent upon your environment, and relied on PowerGUI to execute correctly. Depending on the version of the powershell console you're running, this question offers more suggestions for running assemblies from different versions of .NET. Your

Categories : Powershell



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.