Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

$Image.DrawString centering string with left and right padding

$
0
0

I'm trying draw string on image in vertical middle, but I don't know how do padding from left and right of this text. If I have very big string, it does not fit on image, not making new line...

I have now second powershell code:

$swp_curr_dir = split-path -parent $MyInvocation.MyCommand.Definition[void][reflection.assembly]::loadwithpartialname("system.windows.forms")FunctionAddTextToImage{# Orignal code from http://www.ravichaganti.com/blog/?p=1012[CmdletBinding()]
    PARAM ([Parameter(Mandatory=$true)][String] $sourcePath,[Parameter(Mandatory=$true)][String] $destPath,[Parameter(Mandatory=$true)][String] $Title,[Parameter()][String] $Description = $null)Write-Verbose"Load System.Drawing"[Reflection.Assembly]::LoadWithPartialName("System.Drawing")|Out-NullWrite-Verbose"Get the image from $sourcePath"
    $srcImg =[System.Drawing.Image]::FromFile($sourcePath)Write-Verbose"Create a bitmap as $destPath"
    $outputIImg = new-object System.Drawing.Bitmap([int]($srcImg.width)),([int]($srcImg.height))Write-Verbose"Intialize Graphics"
    $Image =[System.Drawing.Graphics]::FromImage($outputIImg)
    $Image.SmoothingMode="AntiAlias"

    $Rectangle =New-ObjectDrawing.Rectangle0,0, $srcImg.Width, $srcImg.Height
    $Image.DrawImage($srcImg, $Rectangle,0,0, $srcImg.Width, $srcImg.Height,([Drawing.GraphicsUnit]::Pixel))Write-Verbose"Draw title: $Title"
    $Font = new-object System.Drawing.Font("Bauhaus 93",130,"Bold","Pixel")#get font size
    $font_size =[System.Windows.Forms.TextRenderer]::MeasureText($Title, $Font)
    $font_size_width = $font_size.Width
    $font_size_height = $font_size.Height# calc text in middle
    $text_in_middle_top_offset =($srcImg.Height- $font_size_height)/2
    $text_in_middle_left_offset =($srcImg.Width- $font_size_width)/2#styling font
    $Brush =New-ObjectDrawing.SolidBrush([System.Drawing.Color]::FromArgb(255,255,255,255))#lets draw font
    $Image.DrawString($Title, $Font, $Brush, $text_in_middle_left_offset, $text_in_middle_top_offset)Write-Host $text_in_middle_left_offsetWrite-Verbose"Save and close the files"
    $outputIImg.save($destPath,[System.Drawing.Imaging.ImageFormat]::jpeg)
    $outputIImg.Dispose()
    $srcImg.Dispose()}AddTextToImage-sourcePath ($swp_curr_dir +"\image.jpg")-destPath ($swp_curr_dir +"\output.jpg")-Title"Some long long long long long long long long long long long long string here"

cmd /c pause

Search AD computer under entire active directory except one OU "disabled"

$
0
0

Hi Guy

i want a script to move the computer in disable OU which are inactive form 60 day i am using following script.

but it is searching in all OU "disable" OU also but i want to skip disable OU to search.. 

kindly advise..

# Gets time stamps for all computers in the domain that have NOT logged in since after specified date

import-module activedirectory 

$domain = "domain.mydom.com" 

$DaysInactive = 60 

$time = (Get-Date).Adddays(-($DaysInactive)) 

# Get all AD computers with lastLogonTimestamp less than our time

Get-ADComputer -Filter {LastLogonTimeStamp -lt $time} -Properties LastLogonTimeStamp |

 # Output hostname and lastLogonTimestamp into CSV

select-object Name,@{Name="Stamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}} | export-csv OLD_Computer.csv -notypeinformation

Move-ADObject $ADcomputer -targetpath OU=computers,OU=disable,DC=ad,DC=mydom,DC=com"

Exchange 2010 Delete all mails till a date for all users

$
0
0

Hi , 

I want to delete on my exchange for all users till a date 20/07/2016 .

in all folders , and do not move it to the trash box .

I used this command but this will not work : 

get-mailbox | search-mailbox -SearchQuery "Received:<$(20/07/2016)" -deletecontent

Powershell Application Deployment Toolkit

$
0
0

Hi All, 

I know this isn`t directly a Microsoft question but since you guys have been really helpful and I`m having no luck on forums associated with this tool I thought I would ask here, any help would be greatly appreciated. 

I`m currently using PSAPPdeployment toolkit with SCCM to deploy applications to end users, this has been working really well but I need to customise the Welcome message to remove the "Continue" button as clicking this won`t actually do anything as such.

Is there a way I can completely remove the "Continue" button? I`ve hashed out the "Continue" button box but it still shows some of the box next to "Close Programs" which isn`t a huge problem but looks unprofessional. 

Thanks in advance, 

Scott

		## Form
		$formWelcome.Controls.Add($pictureBanner)
		$formWelcome.Controls.Add($buttonAbort)

		##----------------------------------------------
		## Create padding object
		$paddingNone = New-Object -TypeName 'System.Windows.Forms.Padding'
		$paddingNone.Top = 0
		$paddingNone.Bottom = 0
		$paddingNone.Left = 0
		$paddingNone.Right = 0

		## Generic Label properties
		$labelPadding = '20,0,20,0'

		## Generic Button properties
		$buttonWidth = 110
		$buttonHeight = 23
		$buttonPadding = 50
		$buttonSize = New-Object -TypeName 'System.Drawing.Size'
		$buttonSize.Width = $buttonWidth
		$buttonSize.Height = $buttonHeight
		$buttonPadding = New-Object -TypeName 'System.Windows.Forms.Padding'
		$buttonPadding.Top = 0
		$buttonPadding.Bottom = 5
		$buttonPadding.Left = 50
		$buttonPadding.Right = 0

		## Picture Banner
		$pictureBanner.DataBindings.DefaultDataSourceUpdateMode = 0
		$pictureBanner.ImageLocation = $appDeployLogoBanner
		$System_Drawing_Point = New-Object -TypeName 'System.Drawing.Point'
		$System_Drawing_Point.X = 0
		$System_Drawing_Point.Y = 0
		$pictureBanner.Location = $System_Drawing_Point
		$pictureBanner.Name = 'pictureBanner'
		$System_Drawing_Size = New-Object -TypeName 'System.Drawing.Size'
		$System_Drawing_Size.Height = 50
		$System_Drawing_Size.Width = 450
		$pictureBanner.Size = $System_Drawing_Size
		$pictureBanner.SizeMode = 'CenterImage'
		$pictureBanner.Margin = $paddingNone
		$pictureBanner.TabIndex = 0
		$pictureBanner.TabStop = $false

		## Label App Name
		$labelAppName.DataBindings.DefaultDataSourceUpdateMode = 0
		$labelAppName.Name = 'labelAppName'
		$System_Drawing_Size = New-Object -TypeName 'System.Drawing.Size'
		If (-not $showCloseApps) {
			$System_Drawing_Size.Height = 40
		}
		Else {
			$System_Drawing_Size.Height = 65
		}
		$System_Drawing_Size.Width = 450
		$labelAppName.Size = $System_Drawing_Size
		$System_Drawing_Size.Height = 0
		$labelAppName.MaximumSize = $System_Drawing_Size
		$labelAppName.Margin = '0,15,0,15'
		$labelAppName.Padding = $labelPadding
		$labelAppName.TabIndex = 1

		## Initial form layout: Close Applications / Allow Deferral
		If ($showCloseApps) {
			$labelAppNameText = $configClosePromptMessage
		}
		ElseIf (($showDefer) -or ($forceCountdown)) {
			$labelAppNameText = "$configDeferPromptWelcomeMessage `n$installTitle"
		}
		If ($CustomText) {
			$labelAppNameText = "$labelAppNameText `n`n$configWelcomePromptCustomMessage"
		}
		$labelAppName.Text = $labelAppNameText
		$labelAppName.TextAlign = 'TopCenter'
		$labelAppName.Anchor = 'Top'
		$labelAppName.AutoSize = $true
		$labelAppName.add_Click($handler_labelAppName_Click)

		## Listbox Close Applications
		$listBoxCloseApps.DataBindings.DefaultDataSourceUpdateMode = 0
		$listBoxCloseApps.FormattingEnabled = $true
		$listBoxCloseApps.HorizontalScrollbar = $true
		$listBoxCloseApps.Name = 'listBoxCloseApps'
		$System_Drawing_Size = New-Object -TypeName 'System.Drawing.Size'
		$System_Drawing_Size.Height = 100
		$System_Drawing_Size.Width = 300
		$listBoxCloseApps.Size = $System_Drawing_Size
		$listBoxCloseApps.Margin = '75,0,0,0'
		$listBoxCloseApps.TabIndex = 3
		$ProcessDescriptions | ForEach-Object { $null = $listboxCloseApps.Items.Add($_) }

		## Label Defer
		$labelDefer.DataBindings.DefaultDataSourceUpdateMode = 0
		$labelDefer.Name = 'labelDefer'
		$System_Drawing_Size = New-Object -TypeName 'System.Drawing.Size'
		$System_Drawing_Size.Height = 90
		$System_Drawing_Size.Width = 450
		$labelDefer.Size = $System_Drawing_Size
		$System_Drawing_Size.Height = 0
		$labelDefer.MaximumSize = $System_Drawing_Size
		$labelDefer.Margin = $paddingNone
		$labelDefer.Padding = $labelPadding
		$labelDefer.TabIndex = 4
		$deferralText = "$configDeferPromptExpiryMessage`n"

		If ($deferTimes -ge 0) {
			$deferralText = "$deferralText `n$configDeferPromptRemainingDeferrals $([int32]$deferTimes + 1)"
		}
		If ($deferDeadline) {
			$deferralText = "$deferralText `n$configDeferPromptDeadline $deferDeadline"
		}
		If (($deferTimes -lt 0) -and (-not $DeferDeadline)) {
			$deferralText = "$deferralText `n$configDeferPromptNoDeadline"
		}
		$deferralText = "$deferralText `n`n$configDeferPromptWarningMessage"
		$labelDefer.Text = $deferralText
		$labelDefer.TextAlign = 'MiddleCenter'
		$labelDefer.AutoSize = $true
		$labelDefer.add_Click($handler_labelDefer_Click)

		## Label Countdown
		$labelCountdown.DataBindings.DefaultDataSourceUpdateMode = 0
		$labelCountdown.Name = 'labelCountdown'
		$System_Drawing_Size = New-Object -TypeName 'System.Drawing.Size'
		$System_Drawing_Size.Height = 40
		$System_Drawing_Size.Width = 450
		$labelCountdown.Size = $System_Drawing_Size
		$System_Drawing_Size.Height = 0
		$labelCountdown.MaximumSize = $System_Drawing_Size
		$labelCountdown.Margin = $paddingNone
		$labelCountdown.Padding = $labelPadding
		$labelCountdown.TabIndex = 4
		$labelCountdown.Font = 'Microsoft Sans Serif, 9pt, style=Bold'
		$labelCountdown.Text = '00:00:00'
		$labelCountdown.TextAlign = 'MiddleCenter'
		$labelCountdown.AutoSize = $true
		$labelCountdown.add_Click($handler_labelDefer_Click)

		## Panel Flow Layout
		$System_Drawing_Point = New-Object -TypeName 'System.Drawing.Point'
		$System_Drawing_Point.X = 0
		$System_Drawing_Point.Y = 50
		$flowLayoutPanel.Location = $System_Drawing_Point
		$flowLayoutPanel.AutoSize = $true
		$flowLayoutPanel.Anchor = 'Top'
		$flowLayoutPanel.FlowDirection = 'TopDown'
		$flowLayoutPanel.WrapContents = $true
		$flowLayoutPanel.Controls.Add($labelAppName)
		If ($showCloseApps) { $flowLayoutPanel.Controls.Add($listBoxCloseApps) }
		If ($showDefer) {
			$flowLayoutPanel.Controls.Add($labelDefer)
		}
		If ($showCountdown) {
			$flowLayoutPanel.Controls.Add($labelCountdown)
		}

		## Button Close For Me
		$buttonCloseApps.DataBindings.DefaultDataSourceUpdateMode = 0
		$buttonCloseApps.Location = '15,0'
		$buttonCloseApps.Name = 'buttonCloseApps'
		$buttonCloseApps.Size = $buttonSize
		$buttonCloseApps.TabIndex = 5
		$buttonCloseApps.Text = $configClosePromptButtonClose
		$buttonCloseApps.DialogResult = 'Yes'
		$buttonCloseApps.AutoSize = $true
		$buttonCloseApps.UseVisualStyleBackColor = $true
		$buttonCloseApps.add_Click($buttonCloseApps_OnClick)

		## Button Defer
		$buttonDefer.DataBindings.DefaultDataSourceUpdateMode = 0
		If (-not $showCloseApps) {
			$buttonDefer.Location = '15,0'
		}
		Else {
			$buttonDefer.Location = '170,0'
		}
		$buttonDefer.Name = 'buttonDefer'
		$buttonDefer.Size = $buttonSize
		$buttonDefer.TabIndex = 6
		$buttonDefer.Text = $configClosePromptButtonDefer
		$buttonDefer.DialogResult = 'No'
		$buttonDefer.AutoSize = $true
		$buttonDefer.UseVisualStyleBackColor = $true
		$buttonDefer.add_Click($buttonDefer_OnClick)

		## Button Continue
		##$buttonContinue.DataBindings.DefaultDataSourceUpdateMode = 0
		##$buttonContinue.Location = '325,0'
		##$buttonContinue.Name = 'buttonContinue'
		##$buttonContinue.Size = $buttonSize
		##$buttonContinue.TabIndex = 7
		##$buttonContinue.Text = $configClosePromptButtonContinue
		##$buttonContinue.DialogResult = 'OK'
		##$buttonContinue.AutoSize = $true
		##$buttonContinue.UseVisualStyleBackColor = $true
		##$buttonContinue.add_Click($buttonContinue_OnClick)
		#If ($showCloseApps) {
			#  Add tooltip to Continue button
			##$toolTip.BackColor = [Drawing.Color]::LightGoldenrodYellow
			##$toolTip.IsBalloon = $false
			##$toolTip.InitialDelay = 100
			##$toolTip.ReshowDelay = 100
			##$toolTip.SetToolTip($buttonContinue, $configClosePromptButtonContinueTooltip)
		##}

		## Button Abort (Hidden)
		$buttonAbort.DataBindings.DefaultDataSourceUpdateMode = 0
		$buttonAbort.Name = 'buttonAbort'
		$buttonAbort.Size = '1,1'
		$buttonAbort.TabStop = $false
		$buttonAbort.DialogResult = 'Abort'
		$buttonAbort.TabIndex = 5
		$buttonAbort.UseVisualStyleBackColor = $true
		$buttonAbort.add_Click($buttonAbort_OnClick)

		## Form Welcome
		$System_Drawing_Size = New-Object -TypeName 'System.Drawing.Size'
		$System_Drawing_Size.Height = 0
		$System_Drawing_Size.Width = 0
		$formWelcome.Size = $System_Drawing_Size
		$formWelcome.Padding = $paddingNone
		$formWelcome.Margin = $paddingNone
		$formWelcome.DataBindings.DefaultDataSourceUpdateMode = 0
		$formWelcome.Name = 'WelcomeForm'
		$formWelcome.Text = $installTitle
		$formWelcome.StartPosition = 'CenterScreen'
		$formWelcome.FormBorderStyle = 'FixedDialog'
		$formWelcome.MaximizeBox = $false
		$formWelcome.MinimizeBox = $false
		$formWelcome.TopMost = $TopMost
		$formWelcome.TopLevel = $true
		$formWelcome.Icon = New-Object -TypeName 'System.Drawing.Icon' -ArgumentList $AppDeployLogoIcon
		$formWelcome.AutoSize = $true
		$formWelcome.Controls.Add($pictureBanner)
		$formWelcome.Controls.Add($flowLayoutPanel)

		## Panel Button
		$System_Drawing_Point = New-Object -TypeName 'System.Drawing.Point'
		$System_Drawing_Point.X = 0
		# Calculate the position of the panel relative to the size of the form
		$System_Drawing_Point.Y = (($formWelcome.Size | Select-Object -ExpandProperty 'Height') - 10)
		$panelButtons.Location = $System_Drawing_Point
		$System_Drawing_Size = New-Object -TypeName 'System.Drawing.Size'
		$System_Drawing_Size.Height = 40
		$System_Drawing_Size.Width = 450
		$panelButtons.Size = $System_Drawing_Size
		$panelButtons.AutoSize = $true
		$panelButtons.Anchor = 'Top'
		$padding = New-Object -TypeName 'System.Windows.Forms.Padding'
		$padding.Top = 0
		$padding.Bottom = 0
		$padding.Left = 0
		$padding.Right = 0
		$panelButtons.Margin = $padding
		If ($showCloseApps) { $panelButtons.Controls.Add($buttonCloseApps) }
		If ($showDefer) { $panelButtons.Controls.Add($buttonDefer) }
		$panelButtons.Controls.Add($buttonContinue)

		## Add the Buttons Panel to the form
		$formWelcome.Controls.Add($panelButtons)

		## Save the initial state of the form
		$formWelcomeWindowState = $formWelcome.WindowState
		#  Init the OnLoad event to correct the initial state of the form
		$formWelcome.add_Load($Form_StateCorrection_Load)
		#  Clean up the control events
		$formWelcome.add_FormClosed($Form_Cleanup_FormClosed)

		Function Refresh-InstallationWelcome {
			$formWelcome.BringToFront()
			$formWelcome.Location = "$($formWelcomeStartPosition.X),$($formWelcomeStartPosition.Y)"
			$formWelcome.Refresh()
		}

		## Minimize all other windows
		If ($minimizeWindows) { $null = $shellApp.MinimizeAll() }

		## Show the form
		$result = $formWelcome.ShowDialog()
		$formWelcome.Dispose()


.


problems with null-valued expression error

$
0
0

I run my code that gathers certain parameters against multiple machines to create a report. I gather the parameters in a hashtable. Problem is when running the script against one of the machines which in theory should be identical like the others I get

You cannot call a method on a null-valued expression.

+$properties = @{

+~~~~~~~

       +CategoryInfo : InvalidOperation: (:) [], RuntimeException

       +FullyQualifiedErrorID : InvokeMethodNull

I checked all the variables that go to the hashtable and all return values unless I have some caching I'm not aware of. How can I pinpoint the one causing the error? 


yaro

Foreach loop not working

$
0
0

Hello every body,

I am trying to filter a result using a foreach loop but can't seem to be able to do it... any help would be greatl apreciated :)

This is working :

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | 
where {$_.DisplayName -split " " -notcontains "Update" } | 
where {$_.DisplayName -split " " -notcontains "Service" } | 
where {$_.DisplayName -split " " -notcontains "Proofing" } | 
where {$_.DisplayName -split " " -notcontains "C++" } | 
Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | ft –AutoSize

But of course it would be easier for me to grab everything that should not appear in file with :

$file = get-Content C:\_Scripts\SoftwareInstalled\exceptions.txt

And then use a loop 

foreach ( $args in $file) { 
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | where {$_.DisplayName -split " " -notcontains $args } |

Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | ft –AutoSize

But if course it is not that easy... does anyone have an idea how I can script this correctly ?

Many thanks !!

"Copy but keep both Files" in any of xcopy, copy, or robocopy

$
0
0

Hello

I am building a batch file to move some files from 1 part of the network to the another. From time to time some files will have the same name, but not necessarily be the same file. I would like to replicate the "Copy but keep both Files" functionality you get when copy and pasting from the GUI, but cannot see it as an option in 'copy', 'xcopy' or 'robocopy'.

Does anyone know if this is possible please?


Paddy

Script to automate MBSA scan and download missing patches

$
0
0

Hi,

Not a PowerShell guy so go easy on me here. I just found a script that I would like to use. This script scans for missing patches via MS's MBSA, downloads them and then generates a batch file to install the missing ones. Issue I am having is the command that downloads the patches doesn't download anything. The author of the script has closed what he wrote on his site from future comment. Any ideas?

 $UpdateXML = “updates.xml”
    $toFolder = “c:\temp\”
    $installFile = $toFolder +”\_Install.bat”

    #Initialize webclient for downloading files
    $webclient = New-Object Net.Webclient
    $webClient.UseDefaultCredentials = $true

    # Get the content of the XML file
    $Updates = [xml](Get-Content $UpdateXML)

    “@Echo Off” | Out-File $installFile
    “REM This will install all patches” | Out-File $installFile -Append

    foreach ($Check in $Updates.XMLOut.Check)
    {
    Write-Host “Checking for”, $Check.Name
    Write-Host $Check.Advice.ToString()

    #Checking for files to download
    foreach ($UpdateData in $Check.Detail.UpdateData)
    {
    if ($UpdateData.IsInstalled -eq $false)
    {
    Write-Host “Download the file for KB”, $UpdateData.KBID
    Write-Host “Starting download “, $UpdateData.Title, “.”
    $url = [URI]$UpdateData.References.DownloadURL
    $fileName = $url.Segments[$url.Segments.Count – 1]
    $toFile = $toFolder +”\”+ $fileName
    #$webClient.DownloadFile($url, $toFile)
    Write-Host “Done downloading”

    “@ECHO Starting installing “+ $fileName | Out-File $installFile -Append
    if ($fileName.EndsWith(“.msu”))
    {
    “wusa.exe “+ $fileName + ” /quiet /norestart /log:%SystemRoot%\Temp\KB”+$UpdateData.KBID+”.log” | Out-File $installFile -Append
    }
    elseif ($fileName.EndsWith(“.cab”))
    {
    “start /wait pkgmgr.exe /ip /m:”+ $fileName + ” /quiet /nostart /l:%SystemRoot%\Temp\KB”+$UpdateData.KBID+”.log” | Out-File $installFile -Append
    }
    else
    {
    $fileName + ” /passive /norestart /log %SystemRoot%\Temp\KB”+$UpdateData.KBID+”.log” | Out-File $installFile -Append
    }
    “@ECHO Installation returned %ERRORLEVEL%” | Out-File $installFile -Append
    “@ECHO.” | Out-File $installFile -Append
    Write-Host
    }
    }

    Write-Host
    }
 

Using PSDSC to add users to IIS Manager

$
0
0

Hi, 

Is it possible to add users to  IIS Manager using PowerShell DSC. I've written the script to deploy IIS and sub features but need to be able to set users with IIS Manager?

Any help would be much appreciated

Thanks

Invoking PowerShell.exe with "-Command -" (reading input from StdIn) broken in Windows 10 14393?

$
0
0

I have a C# app that contains an embedded PowerShell script.  Not that this matters, it could be external--the important point is that I execute the script by invoking powershell.exe with "-Command -".  That is, using the -Command parameter followed by a hyphen, which allows you to then provide the body of the script to execute through StdIn.

I like this technique, and I've been using it for over a year as, among other reasons, the script doesn't have to be a single command, it can span many lines, declare functions etc, all the while without ever having the script written to disk in plain text or base64-encoded.

After having installed the Anniversary Update of Windows 10 (1607 aka build 14393), this appears to be broken; the captured StdErr shows it complains about missing function bodies, while StdOut shows--and I find this part rather mind-blowing--the script got mangled in such a way that *all* lines that contain a function declaration, and the following opening *and* closing curly braces, are gone.  The rest of the script appears intact.  Obviously that would cascade into all sorts of errors.

I managed to write a short(-ish) sample that demonstrates this problem.  The same EXE demonstrates that it's broken on Windows 10 14393 (all 3 machines I have that run this version exhibit the same behavior), but it works perfectly fine on Windows 10 10586 as well as Windows 7.

One thing I've discovered is that if I substitute the CR/LF characters from the script with a single space, the error goes away, but what happens then is that the StdOut stream I capture comes back empty--even on other OSes that otherwise previously managed to handle the unmodified script just fine--rather than containing the expected output, which comes from one of the script's functions (which simply does a Write-Host).

Another thing I've discovered is that if I add "-version 2.0" as an argument when invoking powershell.exe, everything reverts back to normal behavior.  While this works around the immediate problem, obviously I'd like to remain version-agnostic, so even though I tend to write my scripts so they can run against the "lowest common denominator", I'd rather not explicitly restrict myself in this fashion, as I may eventually need to write a script that relies on some features that have only been introduced in more recent versions.  So I don't view this as a long-term or permanent solution.

If anyone with a compiler cares to try this out, here's my sample cut-down C# program.  It just needs to be built as a console EXE.

Is anyone else getting the same results?  Any workaround that doesn't require me to change the script itself (as I won't necessarily have any knowledge of what the scripts provided to me actually do, other than the fact that they're all expected to end with a single Write-Host as the final output value I'm interested in)...

using System;
using System.Text;
using System.Diagnostics;

namespace PsTest
{
	class Program
	{
		static void Main( string[] args )
		{
			string strMyScript = @"
function GetFunctionValue()
{
	# This comment is in the GetFunctionValue function
	return $true
}

function ShowValue( [string] $theValue )
{
	# This comment is in the ShowValue function
	Write-Host $theValue
}

# This comment is at the script level, before the function call
ShowValue( GetFunctionValue )

# This comment is at the script level, after the function call
";
			//strMyScript = strMyScript.Replace( "\n", " " ).Replace( "\r", " " );
			//strMyScript = strMyScript.Replace( Environment.NewLine, " " );
			RunScript( strMyScript );
		}

		private static string RunScript( string strScriptBody )
		{
			var stdOutBuilder = new StringBuilder();
			var stdErrBuilder = new StringBuilder();

			int nExitCode = 0;
			using ( var p = new Process() )
			{
				p.StartInfo = new ProcessStartInfo( "powershell.exe" )
				{
					Arguments = " -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -Command -",
					// The following line makes the problem go away, even on Win10 14393, unlike the line above
					//Arguments = " -version 2.0 -NoLogo -NonInteractive -ExecutionPolicy Unrestricted -Command -",

					CreateNoWindow = true,
					WindowStyle = ProcessWindowStyle.Hidden,
					UseShellExecute = false,
					RedirectStandardInput = true,
					RedirectStandardOutput = true,
					RedirectStandardError = true,
					Verb = "runas" // Elevate
				};

				p.OutputDataReceived += ( sender, e ) =>
				{
					if ( !String.IsNullOrEmpty( e.Data ) )
						stdOutBuilder.AppendLine( e.Data );
				};
				p.ErrorDataReceived += ( sender, e ) =>
				{
					if ( !String.IsNullOrEmpty( e.Data ) )
						stdErrBuilder.AppendLine( e.Data );
				};

				try
				{
					p.Start();
				}
				catch ( System.ComponentModel.Win32Exception x )
				{
					Console.WriteLine( "Process.Start() threw a Win32Exception:  " + x.Message + Environment.NewLine + x.StackTrace );
					return String.Empty;
				}
				catch ( Exception x )
				{
					Console.WriteLine( "Process.Start() threw an exception:  " + x.Message + Environment.NewLine + x.StackTrace );
					return String.Empty;
				}
				p.BeginOutputReadLine();
				p.BeginErrorReadLine();

				var sw = p.StandardInput;
				sw.WriteLine( strScriptBody );
				sw.Close();

				p.WaitForExit();
				nExitCode = p.ExitCode;
				p.Close();
			}

			string strError = stdErrBuilder.ToString().TrimEnd();
			if ( !String.IsNullOrEmpty( strError ) )
			{
				Console.WriteLine( $"stderr contains the following" + Environment.NewLine + ">>>>>" + Environment.NewLine + strError + Environment.NewLine + "<<<<<" );
				Console.WriteLine( Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine );
			}

			string strOutput = stdOutBuilder.ToString().TrimEnd();
			Console.WriteLine( "stdout contains the following" + Environment.NewLine + ">>>>>" + Environment.NewLine + strOutput + Environment.NewLine + "<<<<<" );

			return String.Empty;
		} // RunScript()
	} // class
}


Here's the expected output on a working machine:

stdout contains the following>>>>>
True<<<<<

...and here's the output on 14393.  Notice the very messed up script body in stdout, at the very end:

stderr contains the following>>>>>
At line:1 char:28+ function GetFunctionValue()+                            ~
Missing function body in function declaration.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordExce
ption+ FullyQualifiedErrorId : MissingFunctionBody

At line:1 char:41
+ function ShowValue( [string] $theValue )+                                         ~
Missing function body in function declaration.+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordExce
ption+ FullyQualifiedErrorId : MissingFunctionBody

GetFunctionValue : The term 'GetFunctionValue' is not recognized as the name of
a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, ver
ify that the path is correct and try
again.
At line:1 char:12
+ ShowValue( GetFunctionValue )+            ~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (GetFunctionValue:String) [], Comm
andNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException<<<<<





stdout contains the following
>>>>>
        # This comment is in the GetFunctionValue function
        return $true
        # This comment is in the ShowValue function
        Write-Host $theValue<<<<<


SQL Agent job step fails after upgrading to Powershell 5

$
0
0

I have a brand new HP DL380 running SQL Server 2008R2 standard. It's not yet in production, and I'm testing SQL Agent jobs. The server is running Windows Server 2012R2 Standard, and came with Powershell 4 installed.

I upgraded to Windows Management Framework 5 (Powershell 5), ran the first script through Powershell ISE and everything was ok. Then I executed the same script from SQL Agent and it failed with: "The term 'New-Object' is not recognized as the name of a cmdlet, function, script file, or operable program."

The job step is a CmdExec type, uses a proxy account, and calls powershell.exe to execute the script. If I make the proxy account a member of the local administrators group it works. If I roll back to Powershell 4 it works (no other changes than uninstalling WMF 5). But if I again upgrade to Powershell 5, the job step fails.

It's obviously some type of permissions issue, but there is no clue as to what part of the security universe to investigate.

Jobstep command:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "D:\dbsoftware\Insert-Records.ps1 -InsertType LogCopyOnly" 

Thanks in advance for any suggestions.

Getting data from files

$
0
0

I have a config file containing text with values as per below...

Name="Fred Dagg"

Address="1 West Drive"

Address2="Fairbanks"

City="Waikato"

:

:

:

I would like to use import each field in to a variable with the value to the right

For example read the text file and

$Name = "Fred Dagg"

$Address = "1 West Drive"

$Address2 = "Fairbanks"

etc

I am happy to code the variable names but I want the best way to get the value.

I have tried the following...

$Conf=Get-Content -Path C:\temp\File.conf -Encoding String

$Name=$Conf | select-string "Name=" | %{$_.trimstart("Name=")

But I get an error saying that the method trimstart doesn't exist.

Thanks

Gopha

How to output to multiple lines

$
0
0

Hi Powershell Guru's,

I wrote this script to compare the difference between two files and put the differences into a result file. (It's meant to compare the members of the domain admins group between two points in time.)

When there are multiple differences, it prints everything on one line, I tried to follow the example on this link, but it doesn't seem to work, it all still prints on one line. Any help is appreciated! [I'm also a newbie to PS,  as you can probably tell this script is hacked together 8-) ]

This is the lijnk I was referring to above: https://powershell.org/forums/topic/writing-array-elements-one-per-line-in-a-string/

##############################################

# Define Working Directory
$WORKDIR = "c:\Domain_Admin_check_working_ish"

# Change to Working Directory
cd $WORKDIR

# Import Active Directory Module for Powershell
import-module activedirectory

# Get list of members in the Domain Admins group, and put it into a file.
get-adgroupmember "domain admins" | findstr "name" | sort | out-file "$WORKDIR\Dadmins.now"

# Make a comparison between the existing list of Domain Admin Group Members.
$COMPARE = compare-object -ReferenceObject (Get-Content $WORKDIR\Dadmins.last) -differenceobject (get-content $WORKDIR\Dadmins.now)

# Create report file depending on whether the membership list has changed from the last time this script was run.
if ($COMPARE) {

$NEWADMINS = echo $COMPARE | findstr "=>"
$NEWADMINS = $NEWADMINS -join "`n"
$REMOVEDADMINS = echo $COMPARE | findstr "<="
$REMOVEDADMINS = $REMOVEDADMINS -join "`n"
echo "Admins that have been added since last check: $NEWADMINS" | sort | Out-file "$WORKDIR\CheckResults.txt"
echo "Admins that have been removed since last check: $REMOVEDADMINS" |sort | Out-File "$WORKDIR\CheckResults.txt" -Append
             }
else
{
echo "The state is the same as the last time this check was run" | Out-file "$WORKDIR\CheckResults.txt"
}


copy-item "Dadmins.now" "Dadmins.$(get-date -f yyyy-MM-dd).txt"

copy-item -Force -Path "Dadmins.now" "Dadmins.last"
remove-item -path "Dadmins.now"

rename-item -Path "$WORKDIR\CheckResults.txt" -NewName "$WORKDIR\CheckResults.$(get-date -f yyyy-MM-dd).txt"

Power CLI - error handling

$
0
0

I have a Power-CLI script that presents a menu to the operator to make configuration changes to a vSphere host.

Some of the options are as follows:

1. Test connectivity

2. Connect to the host

9. Exit and Disconnect 

If the operator launches the script and decide to do nothing and exit the script by selecting 9.  An error will be displayed because, he didn't select option 2 (Make a connection).

Appreciate your help

Here is the portion of the script:

9 { "** Exit and Disconnect **"
Write-Host "Exit and Disconnect"; 
# Remember to disconnect from the ESXi Host
disconnect-viserver $MGMT_IP -confirm:$false
break; 
}

How to calculate physical disks size belong one computer

$
0
0

I knew use below PowerShell command to get the physical disk size from many computer, but I want to summary the result to one table just  contain computer name and total physical disk size. Anyone tips ? Many thanks.

Get-WmiObject -Class win32_diskdrive -ComputerName (Get-Content computer_list.txt)|Select-Object pscomputername,deviceid,size

Result now:

PScomputername, deviceid, size

Computer01,\\.\PHYSICALDRIVE1,10241024

Computer01,\\.\PHYSICALDRIVE0,20242024

Computer02,\\.\PHYSICALDRIVE11,10241024

Computer02,\\.\PHYSICALDRIVE10,30243024

Result needed:

PScomputername, size

Computer01,xxxxxxx

Computer02,xxxxxxx


automate logon to exchange in a script

$
0
0

I'm trying to automate the running of a powershell script for exchange.  The issue I am having is getting logged into exchange properly.  I have several scripts from the internet for it but none of them work.

$password = type C:\users\user\password.txt
$userid = “user@dpisd.org"
$cred = New-Object System.Management.Automation.PSCredential $userid,$password
$global:session365 = New-PSSession -configurationname Microsoft.Exchange -connectionuri https://ps.outlook.com/powershell/ -credential $cred -authentication Basic -AllowRedirection
Import-PSSession $global:session365

The latest error is "New-Object : Cannot find an overload for "PSCredential" and the argument count: "2"."

How do you powershell script to automate the logon process to the exchange system?  Any help would be greatly appreciated!!

automatic move script

$
0
0

Hello,

I need a script that will automatically move a file from the current folder to another folder I've created name archive. I want the program to automatically move an existing file automatically when a new file is created with the same name in the folder (I hope this makes sense). Is that possible?

Thank you

Remove-Item Requested registry access is not allowed

$
0
0

Help please,

I have written a Powershell script that is trying to use Remove-Item to delete some Registry keys. I am running under Admin. if I go into Regedit it will let me delete the keys but if I run the Powershell script I get "Remove-Item Requested registry access is not allowed."

I have checked the permissions for the key and it says I have Delete permission. I am using the PowerShell ISE and am on Windows 7. I have tried -Force and -Recurse but makes no difference, neither does reducing UAC to minimum. It also makes no difference if I start PowerShell ISE with Administrator privileges. Why can I delete from within Regedit but not from PowerShell?

Be grateful for some help.

Dave

Get SQL Agent Job EnumHistory via Powershell

$
0
0

Hi guys!!

I  am using Powershell through DollarU (Workload automation software) to execute SQL Agent job (all steps) or one specific step at a time.  So far so good, everything is working!!  However, when it gets to the point where I want to get the History log information, I can't seem get what I want.

Here is my program:  

param ([parameter (Mandatory = $true)][string]$ServerName,

       [parameter (Mandatory = $true)][string]$JobName,

       [string]$StepName = "")



write-host "Starting SQL Agent Job $($JobName) on Server $($ServerName)"

$date=Get-Date

write-host "It is now: $($date)"

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

$srv = New-Object Microsoft.SqlServer.Management.SMO.Server("$ServerName")

$job = $srv.jobserver.jobs["$JobName"]
$jobstart="No"

if (($job))
{

   if ($StepName -ne '')
      {
        $job.Start($StepName)
        $jobstart="Yes"
        Start-Sleep -s 5  # Pause for 5 seconds (optional) - was 30 seconds (v1); v2=5
      }

   else
      {
        $job.Start()
        $jobstart="Yes"
        Start-Sleep -s 5
      }
}

else
{
   $jobstart="Not found"
}

if ($jobstart -eq "Yes")
{
   write-host "Job $($JobName) on Server $($ServerName) started"
   $i=0

   do
   {
     $job.Refresh();
     $iRem = $i % 5;
     $jobrunning=$job.CurrentRunStatus.ToString();

     if ($iRem -eq 0)
     {
       $date=Get-Date
       write-host "Job $($JobName) Processing--Run Step:$($job.CurrentRunStep) Status:$($job.CurrentRunStatus.ToString())... at $($date)"
     }

     Start-Sleep -s 10; # Pause for 10 seconds  - was 60 seconds (v1); v2=10
     $i++;
   }

   while ($job.CurrentRunStatus.ToString() -ne "Idle")
     if ($job.LastRunOutcome -ne "Cancelled")
     {
       write-host "Job Processing done"
     }
     else
     {
       write-host "Job Processing cancelled/aborted"
     }

     #   $jobRunning="TRUE"
     write-host "$($srv.name) $($job.name)"
     write-host "Last job outcome $($job.LastRunOutcome)"
     write-host "Last job outcome $($job.LastRunDate)"

        if ($job.EnumHistory().Rows[0] -ne $null)
        {
           write-host "xxxx $($job.EnumHistory().Rows[0].Message)"
        }

        if ($job.EnumHistory().Rows[1] -ne $null)
        {
           write-host "yyyyy $($job.EnumHistory().Rows[1].Message)"
        }


        $LastRun=$job.LastRunOutcome

        if ($StepName -ne '')
        {
           $JobStep = $Job.JobSteps[$StepName]
           Write-Host "Name: $($JobStep.Name) RunDate: $($JobStep.LastRunDate) Status: $($JobStep.LastRunOutCome)"
        }

        else
        {
          $StepCount = $job.JobSteps.Count - 1

        for ($i=0;$i -le $StepCount;$i++)
        {
         $m = $job.JobSteps[$i].LastRunDate
         write-host "Name: $($job.JobSteps[$i].Name) RunDate: $($job.JobSteps[$i].LastRunDate) Status: $($job.JobSteps[$i].LastRunOutCome)"

         if ($job.LastRunDate -gt $m)
             {
                   $LastRun="FailedOrAborted"
             }
       }
     }


     if ($LastRun -eq "Failed")
     {
       write-host "Job returned with Failed status"
       exit 2
     }

     if ($LastRun -ne "FailedOrAborted")
     {
       if ($LastRun -ne "Cancelled")
           {
             exit 0
           }

       else
           {
             write-host "Job Cancelled xxxxx"
             exit 3
           }
        }

     else
     {
             write-host "Job Failed or Aborted"
             exit 2
      }
}

else
{
  write-host "Unable to Start Job $($JobName) on Server $($ServerName)"
  write-host "Reason: Job may not exist or not enabled."
  exit 1
}


When there are no specific step to execute...  when only the jobName is provided, I get the proper information.  When it is only a specific step, the second line (YYYY) returns information from past executions.

 if ($job.EnumHistory().Rows[0] -ne $null)
    {
       write-host "xxxx $($job.EnumHistory().Rows[0].Message)"
    }

    if ($job.EnumHistory().Rows[1] -ne $null)
    {
       write-host "yyyyy $($job.EnumHistory().Rows[1].Message)"
    }


In the following picture, you will see the lines of History log information that I got in return for run executed at 10:42 on August 15th (???)

What I would like to get are the following lines of information:

So I tried the following lines of code without any success...

if ($job.EnumJobStepLogs($StepName).Rows[0] -ne $null)
{
  write-host "xxxx $($job.EnumJobStepLogs($StepName).Rows[0].Message)"
}

if ($job.EnumJobStepLogs($StepName).Rows[1] -ne $null)
{
  write-host "yyyyy $($job.EnumJobStepLogs($StepName).Rows[1].Message)"
}

and this...

if ($job.EnumHistory($stepName).Rows[0] -ne $null)
{
   write-host "xxxx $($job.EnumHistory($stepName).Rows[0].Message)"
}

if ($job.EnumHistory($stepName).Rows[1] -ne $null)
{
   write-host "yyyyy $($job.EnumHistory($stepName).Rows[1].Message)"
}

I really don't understand...  and don't know what to try anymore :-(

Can you help me?

Mylene


Mylene Chalut

Having issues copying file straight out of array

$
0
0

$cp = (dir c:\testps\*.jpeg , c:\testps\*.png -Recurse|Select fullname,CreationTime|Where CreationTime -gt (get-date).AddDays(-2) |select fullname )
copy-item $cp C:\Users\Dest\Desktop\Exercise1

______________________________________

for some reason it copies the memeber aswell :

@{FullName=C:\testps\kokotpng.png}

any way to get rid of that?

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>