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

+ CategoryInfo : NotSpecified: (:String) [], RemoteException

$
0
0
Please help me.
via cmd this works but in powershell.
via cmd
symdisk -sid 910 list -failed

Symmetrix ID                 : 000198700910

No devices were found

via powershell
$Fail = symdisk -sid 910 list -failed 
$Fail
gives an error
symdisk : 
At line:1 char:9
+ $Fail = symdisk -sid 910 list -failed
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 
No devices were found

Symmetrix ID                 : 000198700910

Find DL's with a group member and missing group members.

$
0
0

Hello ,
someone can please guide me how to add - and -notcontains to this?


Get-DistributionGroup -ResultSize Unlimited -erroraction 'silentlycontinue' | where { (Get-DistributionGroupMember $_.Name -erroraction 'silentlycontinue'| foreach {$_.PrimarySmtpAddress}) -contains "$Gmember" -and -notcontains "$GmemberNot" }

basically i want to find DL's with a group member and without specific group member

thank you



PowerShell script works in ISI, but not from command line

$
0
0

Greetings,

I created a simple PowerShell script that has a file select dialog box to in turn, compress the file after it is selected.  This works as expected, but when I try to run the command line ofpowershell -file test.ps1 it receives the following error code:

You cannot call a method on a null-valued expression.
At C:\test.ps1:13 char:4
+ if($OpenFileDialog.ShowDialog() -eq "OK")
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Code below.  Any ideas on how to fix this?:

Function Get-FileName($initialDirectory)
{   
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
 $OpenFileDialog.initialDirectory = "C:\"  
 $OpenFileDialog.filter = "All files (*.*)| *.*"
 $OpenFileDialog.ShowDialog()
 $OpenFileDialog.filename
}


if($OpenFileDialog.ShowDialog() -eq "OK")


{

        # Get full path including file name
        $GetSourceFilePath = ($OpenFileDialog.filename)

        # Strip file extension from selected file so when file is compressed, it won't have the file extension as part of the compressed file
        $StripFileExtension = [System.IO.Path]::GetFileNameWithoutExtension($GetSourceFilePath)

        # Get file path without file name
        $GetFilePath = Get-ChildItem "$GetSourceFilePath"
        $DirectoryOnly = $GetFilePath.DirectoryName

        # Compress specified file and overwrite existing file if same name via the -Force option
        Compress-Archive -LiteralPath $GetSourceFilePath -CompressionLevel Optimal -DestinationPath $DirectoryOnly\$StripFileExtension".zip" -Force
}
else { Write-Host "Operation cancelled" -ForegroundColor Red

} 


remote invoke a bat

$
0
0

Support I have server A and Server B. there is a script in Server B C:\temp\script\test.bat

how to invoke C:\temp\script\test.bat in Server B from Server A using powershell in ServerA ?

Active Directory - Disabled Account/Users

$
0
0

Hi,

Good day.

Please HELP! I have lists of ID (UserIDs) that is already disabled and I want to remove their member groups for every listed disabled user in AD. Is this possible?

Thanks a lot in advance.

Create folder with current timestamp using powershell

$
0
0

how to Create folder with current time-stamp mm-dd-yyyy HH:MM:SS using powershell?

I was able to create thefolder with mm-dd-yyyy but not mm-dd-yyyy HH:MM:SS? Is it possible to create the folder with mm-dd-yyyy HH:MM:SS?

PowerShell Forms - Textbox Input Check - Forward Content to a new Form

$
0
0

Hello Everyone,

I am struggling with a form, in combination with a Textbox and data entered into it. I started to build a test script that works as shown in example 1 and then extended it and need to do some minor changes to make it work.

In example 1: I generate a Form, ask for a Name and after a data input and pressing OK, a second form opens to present the data in a label. That works fine and I would like to have it on such way.

CLS
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

#New User Form
$TestForm = New-Object System.Windows.Forms.Form
$TestForm.Text = "Test Name Input"
$TestForm.AutoScroll = $True
$TestForm.AutoSizeMode = "GrowAndShrink"
$TestForm.MinimizeBox = $True
$TestForm.MaximizeBox = $True
$TestForm.WindowState = "Normal"
$TestForm.Size = New-Object System.Drawing.Size(1000,1000)
$TestForm.StartPosition = 'CenterScreen'


#New User Form Title
$TestFormTitle = New-Object System.Windows.Forms.Label
$TestFormTitle.Location = New-Object System.Drawing.Point(10,30)
$TestFormTitle.Size = New-Object System.Drawing.Size(450,50)
$TestFormTitleFont = New-Object System.Drawing.Font("Times New Roman",26,[System.Drawing.FontStyle]::Bold)
$TestFormTitle.Font = $TestFormTitleFont
$TestFormTitle.Text = "This is a Test"
$TestForm.Controls.Add($TestFormTitle)

#New User Form Label Firstname
$TestFormFormLabelFirstname = New-Object System.Windows.Forms.Label
$TestFormFormLabelFirstname.Location = New-Object System.Drawing.Point(10,100)
$TestFormFormLabelFirstname.Size = New-Object System.Drawing.Size(885,40)
$TestFormFormLabelFirstnameFont = New-Object System.Drawing.Font("Arial",16,[System.Drawing.FontStyle]::Italic)
$TestFormFormLabelFirstname.ForeColor = "DarkBlue"
$TestFormFormLabelFirstname.Font = $TestFormFormLabelFirstnameFont
$TestFormFormLabelFirstname.Text = "Please Enter Firstname"
$TestForm.Controls.Add($TestFormFormLabelFirstname)

#New User Form Textbox Firstname
$TestFormTextBoxFirstname = New-Object System.Windows.Forms.TextBox
$TestFormTextBoxFirstname.Location = New-Object System.Drawing.Point(10,140)
$TestFormTextBoxFirstname.Size = New-Object System.Drawing.Size(885,100)
$TestFormTextBoxFirstnameFont = New-Object System.Drawing.Font("Arial",20,[System.Drawing.FontStyle]::Italic)
$TestFormTextBoxFirstname.Font = $TestFormTextBoxFirstnameFont
$TestForm.Controls.Add($TestFormTextBoxFirstname)

#Create OK Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(190,860)
$OKButton.Size = New-Object System.Drawing.Size(200,75)
$OKButton.Font = New-Object System.Drawing.Font("Arial",16,[System.Drawing.FontStyle]::Regular)
$OKButton.Text = 'OK'               
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK           
$TestForm.AcceptButton = $OKButton
$TestForm.Controls.Add($OKButton)           


$result = $TestForm.ShowDialog()

#Confirmation Name Form
$ConfirmatonNameform = New-Object System.Windows.Forms.Form
$ConfirmatonNameform.Text = "Confirmation Name"
$ConfirmatonNameform.Size = "1300, 780"
$ConfirmatonNameform.StartPosition = "CenterScreen"
$ConfirmatonNameform.Icon = $ConfirmatonNewUserformIcon
$ConfirmatonNameform.AutoSize = $False
$ConfirmatonNameform.BringToFront()

#Confirmation New User Firstname Label
$ConfirmatonNameLabel = New-Object System.Windows.Forms.Label
$ConfirmatonNameLabel.Location = New-Object System.Drawing.Point(10,80)
$ConfirmatonNameLabel.Size = New-Object System.Drawing.Size(200,50)
$ConfirmatonNameLabelFont = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$ConfirmatonNameLabel.ForeColor = "DarkBlue"
$ConfirmatonNameLabel.Font = $ConfirmatonNameLabelFont
$ConfirmatonNameLabel.Text = "Firstname:"
$ConfirmatonNameform.Controls.Add($ConfirmatonNameLabel)

#Confirmation New User Firstname Data
$ConfirmatonNamevar = New-Object System.Windows.Forms.Label
$ConfirmatonNamevar.Location = New-Object System.Drawing.Point(400,80)
$ConfirmatonNamevar.Size = New-Object System.Drawing.Size(700,50)
$ConfirmatonNamevarFont = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$ConfirmatonNamevar.ForeColor = "Black"
$ConfirmatonNamevar.Font = $ConfirmatonNamevarFont
$ConfirmatonNamevar.text = $TestFormTextBoxFirstname.text
$ConfirmatonNameform.Controls.Add($ConfirmatonNamevar)



if ($result -eq [System.Windows.Forms.DialogResult]::OK)
{$ConfirmatonNameform.ShowDialog()}

I have extended this form and because I have several Textboxes, I wanted to have a mechanism, to prevent a textbox left-out without any data entered.

In example 2 you can see how the code looks slightly different.

CLS
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing

#New User Form
$TestForm = New-Object System.Windows.Forms.Form
$TestForm.Text = "Test Name Input"
$TestForm.AutoScroll = $True
$TestForm.AutoSizeMode = "GrowAndShrink"
$TestForm.MinimizeBox = $True
$TestForm.MaximizeBox = $True
$TestForm.WindowState = "Normal"
$TestForm.Size = New-Object System.Drawing.Size(1000,1000)
$TestForm.StartPosition = 'CenterScreen'


#New User Form Title
$TestFormTitle = New-Object System.Windows.Forms.Label
$TestFormTitle.Location = New-Object System.Drawing.Point(10,30)
$TestFormTitle.Size = New-Object System.Drawing.Size(450,50)
$TestFormTitleFont = New-Object System.Drawing.Font("Times New Roman",26,[System.Drawing.FontStyle]::Bold)
$TestFormTitle.Font = $TestFormTitleFont
$TestFormTitle.Text = "This is a Test"
$TestForm.Controls.Add($TestFormTitle)

#New User Form Label Firstname
$TestFormFormLabelFirstname = New-Object System.Windows.Forms.Label
$TestFormFormLabelFirstname.Location = New-Object System.Drawing.Point(10,100)
$TestFormFormLabelFirstname.Size = New-Object System.Drawing.Size(885,40)
$TestFormFormLabelFirstnameFont = New-Object System.Drawing.Font("Arial",16,[System.Drawing.FontStyle]::Italic)
$TestFormFormLabelFirstname.ForeColor = "DarkBlue"
$TestFormFormLabelFirstname.Font = $TestFormFormLabelFirstnameFont
$TestFormFormLabelFirstname.Text = "Please Enter Firstname"
$TestForm.Controls.Add($TestFormFormLabelFirstname)

#New User Form Textbox Firstname
$TestFormTextBoxFirstname = New-Object System.Windows.Forms.TextBox
$TestFormTextBoxFirstname.Location = New-Object System.Drawing.Point(10,140)
$TestFormTextBoxFirstname.Size = New-Object System.Drawing.Size(885,100)
$TestFormTextBoxFirstnameFont = New-Object System.Drawing.Font("Arial",20,[System.Drawing.FontStyle]::Italic)
$TestFormTextBoxFirstname.Font = $TestFormTextBoxFirstnameFont
$TestForm.Controls.Add($TestFormTextBoxFirstname)

#Create OK Button
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(190,860)
$OKButton.Size = New-Object System.Drawing.Size(200,75)
$OKButton.Font = New-Object System.Drawing.Font("Arial",16,[System.Drawing.FontStyle]::Regular)
$OKButton.Text = 'OK'               
$TestForm.AcceptButton = $OKButton
$TestForm.Controls.Add($OKButton)           

#Check if Name has been entered
$OKButtonClickEvent = (
    {if (!$TestFormTextBoxFirstname.text -and !$TestFormTextBoxFirstname.text -eq 'True') {[System.Windows.MessageBox]::Show('No data entered in Firstname','Ooops','OK','Warning')}
            Else {$TestForm.Hide(),$ConfirmationNameform.ShowDialog()}
    }
)

$OKButton.Add_Click($OKButtonClickEvent) 
$TestForm.ShowDialog()


#Confirmation Name Form
$ConfirmationNameform = New-Object System.Windows.Forms.Form
$ConfirmationNameform.Text = "Confirmation Name"
$ConfirmationNameform.Size = "1300, 780"
$ConfirmationNameform.StartPosition = "CenterScreen"
$ConfirmationNameform.Icon = $ConfirmationNewUserformIcon
$ConfirmationNameform.AutoSize = $False
$ConfirmationNameform.BringToFront()

#Confirmation New User Firstname Label
$ConfirmationNameLabel = New-Object System.Windows.Forms.Label
$ConfirmationNameLabel.Location = New-Object System.Drawing.Point(10,80)
$ConfirmationNameLabel.Size = New-Object System.Drawing.Size(200,50)
$ConfirmationNameLabelFont = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$ConfirmationNameLabel.ForeColor = "DarkBlue"
$ConfirmationNameLabel.Font = $ConfirmationNameLabelFont
$ConfirmationNameLabel.Text = "Firstname:"
$ConfirmationNameform.Controls.Add($ConfirmationNameLabel)

#Confirmation New User Firstname Data
$ConfirmationNamevar = New-Object System.Windows.Forms.Label
$ConfirmationNamevar.Location = New-Object System.Drawing.Point(400,80)
$ConfirmationNamevar.Size = New-Object System.Drawing.Size(700,50)
$ConfirmationNamevarFont = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Regular)
$ConfirmationNamevar.ForeColor = "Black"
$ConfirmationNamevar.Font = $ConfirmationNamevarFont
$ConfirmationNamevar.text = $TestFormTextBoxFirstname.text
$ConfirmationNameform.Controls.Add($ConfirmationNamevar)


The ClickEvent (thanx jrv) checks if data has been entered and if not, will give a warning. This also works perfectly and I was happy but then, I faced a new problem:

As soon as the second form opens, for some reason, the content of the textbox in the example called "$TestFormTextBoxFirstname.text" is empty.

What I was able to find out is, that if I run the Script a second time, I get the UserInput from the first try and if I understand correctly, that means, that the name entered in example 2 and stored as a variable, runs through without being forwarding to the second form to "$ConfirmationNamevar.text". I was playing around, trying different approaches but was not able to fix it.

I tried this approach, because I had no clue, how to show "$TestFormTextBoxFirstname.text" directly in the Label. Here,  I also tried several ways but failed also.

What am I doing wrong? Can someone help with a solution, so I can keep the ClickEvent and have the content of the Textbox transferred into the Second Form, so the name is shown, as it works correctly in example 1?

Thank you very much for your help,

Mike

Powershell script to look for files from each year and zip them

$
0
0

Hello, I am new to PS programming and need to create a script that goes into a specific folder and zips files from each year into corresponding zip and naming the folder the year of data. For example:

C:\Archive contains text files from as long ago as 2013. What the script needs to accomplish is to identify files from 2013 and compress them into a zip called "2013.zip", and identify files from 2014 then zip them into "2014.zip" all the way until 2017. It should also delete the original files since this whole exercise is trying cleanup space on the drive.

I have figured out how to look for files older than certain days and zip them but haven't figured out how to do it on a yearly basis. Please provide your thoughts.

Thanks!


Adding tag in Web.config

$
0
0
Dear All,



In my web.config I want to add the following tags through Windows Powershell Script

this tag should go between <assemblies></assemblies>
<add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

This tag should go between <handlers></handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="/v1/*" verb="GET,POST,DELETE" type="System.Web.Handlers.TransferRequestHandler"preCondition="integratedMode,runtimeVersionv4.0" />



I have started to write script but I could only go this far


$webConfig = '.\web.config'
[xml]$web =  (Get-Content $webConfig)


Any help would be greatly appreciated


%username conversion to correct SamAccountName.

$
0
0

Dear Community,

I am currently creating a script to ease user creation on Windows Server 2019 ST.

its a very basic script i got from the internet and created my own.

New-ADuser -Name "" -DisplayName "" -HomeDrive "H:" -HomeDirectory "\\Shares\%USERNAME% -GivenName "" -Surname "" -SamAccountName "test" -UserPrincipalName "" -Path "OU=Users,OU=Active Users,DC=Domain,DC=local" -AccountPassword(Read-Host -AsSecureString "Input Password") -Enabled $true

this script works almost 100% the only problem i am facing is that when using the HomeDirectory parameter with the %username% input it does not convert this to the samAccountName automatically. it just inputs it as soon.

with the little language knowledge i have i know everything between "" is seen as a string so it writes it down as seen.

But upon running the script i would like it to recognize it and convert the %username% to test.

Thank you in advanced and will kindly wait for any suggestions.

Trimming XML output

$
0
0

Hi Everyone

I am stuck with a problem that i haven't been able to solve, so i am asking for your help :)

Long story short, i pull data from our BigFix servers with Powershell. This works.

My code to run the request and save output to XML.

Invoke-WebRequest -Uri $request2 -Credential $login | Select-Object * | Out-File D:\bigfix\bigfix_Output.xml -Width 1000

The Output is a fairly well formated XML file. I then want to trim the XML file and prepare it for further processing.

Example of XML file output:

I want to trim the document and remove all text above the <?xml version="1.0" encoding="UTF-8"?> line.

I have tried to read up on trimming with Powershell, but i haven't been able to solve the problem. Perhaps i could simply edit my Invoke-Webrequest code and justuse Select-Object to select the part i need. But i have not been able to identify an object that returns only the essential XML body.

Can anyone help with an example of trimming all text before <?xml version="1.0" encoding="UTF-8"?> or should i edit my Invoke-Webrequest code?

Any help are more than welcome.

Thanks in advance.

Script for AD OU permissions

$
0
0

I am trying to right a script, that will allow me to hide/restrict access to OUs to certain security groups.  Essentially I am trying to replace the old Active Roles server's functionality.

Currently I have a script that creates the OUs (and sub OUs), creates the security groups, all fed by form entry.  Once the groups are created, I need to be able to apply restrictions on them to block previously created OUs:

OU1 contains SG 1

OU2 contains SG 2

I need to block SG2 from seeing the contents of OU1 and vice versa.

I have gotten close with a few ACE and ACL scripts but I can't quite get the results I want.  Can anyone help?

Replacing generated Image file instead of creating a new one at every run

$
0
0

HI,

We found this code at this location. https://github.com/octan3/img-clipboard-dump. We are beginner in Powershell and we are having a difficult time trying to understand the code.

Add-Type -Assembly PresentationCore
$img = [Windows.Clipboard]::GetImage()
if ($img -eq $null) {
    Write-Host "Clipboard contains no image."
    Exit
}

$file = "{0}\clipboard-{1}.jpg" -f [Environment]::GetFolderPath('MyPictures'),((Get-Date -f s) -replace '[-T:]','')
Write-Host ("`n Found picture. {0}x{1} pixel. Saving to {2}`n" -f $img.PixelWidth, $img.PixelHeight, $file)

$stream = [IO.File]::Open($file, "OpenOrCreate")
$encoder = New-Object Windows.Media.Imaging.JpegBitmapEncoder
$encoder.QualityLevel = 90
$encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($img))
$encoder.Save($stream)
$stream.Dispose()& explorer.exe /select,$file

We would need to get this modified so that the files gets overwritten at every run instead of creating a new one at each run. How can we edit the script so that it would save to a specific folder with a file name provided that the path and the file name has been hard-coded inside the script. Please assist. 

For example : Say, we need the file to be saved into this path : --> C:\Images and the filename should be --> Image01.jpg resulting in this --> C:\Images\Image01.jpg

IP Address Configuration in powershell

$
0
0

Hello everybody 

I have to configure add an IP address to my interface.

I use this command : New-NetIPAddress -InterfaceIndex 20 -IPAddress "192.168.10.1" -PrefixLength 24 -AddressFamily IPv4

The IP address is configured (after verification with ping) but if check the property of network configuration , the new ip address is not present , I see only the old address .

Is someone have a solution ? 

how to change powershell languagemode to FullLanguage

$
0
0

Hi,

on my windows 10 machine powershell script execution started failing with below error :

 Cannot dot-source this command because it was defined in a different language
  mode. To invoke this command without importing its contents, omit the '.' operator.

I check my language mode and it was : ConstrainedLanguage

I tried to set environment variable __PSLockdownPolicy to 0 and 

$ExecutionContext.SessionState.LanguageMode=[System.Management.Automation.PSLanguageMode]::FullLanguage

but no luck at all.

Can you guys help me how to change language mode or any other pointer in microsoft's powershell team to contact.


How to run a local function on a remote server

$
0
0

I have a function defined in a local PowerShell script file (.ps1 file). The script is located in a local hard drive on my workstation. In this script I have a function declared which I would like to be able to run on a remote server. I know that with a remote server you can use the import-pssession command, but that takes a function that is declared on the remote server and allows me to execute it from my workstation while it still runs on the server. I also know there is anexport-pssession command, but that also seems to bring a function from the server to my workstation.

Is there a way to run a locally declared function on a remote server?

As an example, I have a locally defined function named Add-LBAppShortcut.

If I run the below, it fails:

#perform operation on remote server
$homeServer = $user.Location.Server
Write-Verbose "[ $functionName ] Opening session to $homeServer"
$session = New-PSSession $homeServer
try
{
	Import-PSSession $session -DisableNameChecking -CommandName Copy-Item,Remove-Item -AllowClobber | Out-Null
	Invoke-Command -Session $session -ScriptBlock {
		param($innerEmployee)
		$DebugPreference = "Continue"
		$VerbosePreference = "Continue"
		$functionName = 'Add-LBEmployeeFileProcessing'

		Write-Verbose "[ $functionName ] Removing old shortcuts if found"
		$oldShortcuts = @("Export to Optima3 Capture.lnk", "Optima3 Workstation.rdp" `
			, "WVWWKP02.rdp", "Export to CSI.lnk", "Export to Optima.lnk" `
			, "OPTIMA EXPORT.lnk", "X937Export.exe - Shortcut.lnk")

		$desktopPath = "D:\Users\Home\$($innerEmployee.SamAccountName)\SysFiles\Profile\Desktop"
		foreach($shortcut in $oldShortcuts)
		{
			$oldShortcutPath = [System.IO.Path]::Combine($desktopPath, $shortcut)
			if([System.IO.File]::Exists($oldShortcutPath))
			{
				Write-Debug "  [ $functionName ] Removing $shortcut"
				Remove-Item $oldShortcutPath
			}
		}

		Write-Verbose "[ $functionName ] adding shortcuts"
		Add-LBAppShortcut $desktopPath "Export to CSI" "M:\Apps\OpenCheck\X937 Output\X937Export.exe" "Export End of Day images to CSI" "M:\Apps\OpenCheck\X937 Output"
		Add-LBAppShortcut $desktopPath "Export to Optima3 Capture" "C:\X937 Output\X937Export.exe" "Export End of Day images to Optima3 Capture" "C:\X937 Output"
		Copy-Item -LiteralPath "\\Svfs0102\it\Shortcuts\Optima3 Workstation.rdp" $desktopPath

	} -ArgumentList $user
}
finally
{
	Write-Verbose "[ $functionName ] Closing session to $homeServer"
	if(($session.State -ne $null) -and ($session.State -ne "Closed"))
	{
		Receive-PSSession $session
		Remove-PSSession $session
	}
}

To work around this I have to define the function twice like below. The problem is that this means you are defining the function in multiple places which is bad.

Is there any way to avoid this?

#perform operation on remote server
$homeServer = $user.Location.Server
Write-Verbose "[ $functionName ] Opening session to $homeServer"
$session = New-PSSession $homeServer
try
{
	Import-PSSession $session -DisableNameChecking -CommandName Copy-Item,Remove-Item -AllowClobber | Out-Null
	Invoke-Command -Session $session -ScriptBlock {
		param($innerEmployee)
		$DebugPreference = "Continue"
		$VerbosePreference = "Continue"
		$functionName = 'Add-LBEmployeeFileProcessing'

		function Add-LBAppShortcut()
		{
			[CmdletBinding()]
			Param([Parameter(Mandatory=$true)][String]$Directory
				, [Parameter(Mandatory=$true)][String]$Name
				, [Parameter(Mandatory=$true)][String]$TargetPath
				, [Parameter(Mandatory=$false)][String]$Comment
				, [Parameter(Mandatory=$false)][String]$StartIn)
			# CREDIT: timdunn @ https://blogs.msdn.microsoft.com/timid/2009/09/24/powershell-one-liner-whats-the-function-name/
			$functionName = (Get-Variable MyInvocation -Scope 0).Value.MyCommand.Name
			# CREDIT: Boe Prox @ https://learn-powershell.net/2014/06/01/prevent-write-debug-from-bugging-you/
			if($PSBoundParameters["Debug"]) {$DebugPreference = "Continue"}
			Write-Debug "  [ $functionName ] Method started"
			Write-Debug "  [ $functionName ] Directory = $Directory"
			Write-Debug "  [ $functionName ] Name = $Name"
			Write-Debug "  [ $functionName ] TargetPath = $TargetPath"
			Write-Debug "  [ $functionName ] Comment = $Comment"
			Write-Debug "  [ $functionName ] StartIn = $StartIn"

			$fileName = $Name + '.lnk'
			$shortcutPath = [System.IO.Path]::Combine($Directory, $fileName)
			Write-Debug "  [ $functionName ] shortcutPath = $shortcutPath"

			$shell = New-Object -ComObject WScript.Shell
			$shortcut = $shell.CreateShortcut($shortcutPath)
			$shortcut.TargetPath = $TargetPath
			$shortcut.Description = $Comment
			$shortcut.WorkingDirectory = $StartIn
			$shortcut.Save()
			$shell = $null

			Write-Debug "  [ $functionName ] Method finished"
		}
		Write-Verbose "[ $functionName ] Removing old shortcuts if found"
		$oldShortcuts = @("Export to Optima3 Capture.lnk", "Optima3 Workstation.rdp" `
			, "WVWWKP02.rdp", "Export to CSI.lnk", "Export to Optima.lnk" `
			, "OPTIMA EXPORT.lnk", "X937Export.exe - Shortcut.lnk")

		$desktopPath = "D:\Users\Home\$($innerEmployee.SamAccountName)\SysFiles\Profile\Desktop"
		foreach($shortcut in $oldShortcuts)
		{
			$oldShortcutPath = [System.IO.Path]::Combine($desktopPath, $shortcut)
			if([System.IO.File]::Exists($oldShortcutPath))
			{
				Write-Debug "  [ $functionName ] Removing $shortcut"
				Remove-Item $oldShortcutPath
			}
		}

		Write-Verbose "[ $functionName ] adding shortcuts"
		Add-LBAppShortcut $desktopPath "Export to CSI" "M:\Apps\OpenCheck\X937 Output\X937Export.exe" "Export End of Day images to CSI" "M:\Apps\OpenCheck\X937 Output"
		Add-LBAppShortcut $desktopPath "Export to Optima3 Capture" "C:\X937 Output\X937Export.exe" "Export End of Day images to Optima3 Capture" "C:\X937 Output"
		Copy-Item -LiteralPath "\\Svfs0102\it\Shortcuts\Optima3 Workstation.rdp" $desktopPath

	} -ArgumentList $user
}
finally
{
	Write-Verbose "[ $functionName ] Closing session to $homeServer"
	if(($session.State -ne $null) -and ($session.State -ne "Closed"))
	{
		Receive-PSSession $session
		Remove-PSSession $session
	}
}

Issues running Get-Service with Invoke-command session

$
0
0

I am trying get service information via a PS session, with the service name being in a variable that is declared depending on which version of the software is installed.  When I run the command with the Variable name I get an out put of every service name and the status.  However if I hard code the service name the command works.  Is there something I need to do when setting the name of the services in a variable?

Invoke-Command -Session $PSSession -ScriptBlock {                
                Try {$UmbrellaStatus = Get-Service -name $UmbrellaService -ErrorAction SilentlyContinue}
                Catch { Write-Host 'Error Occured' }
                if (!$error)
                {
                    Write-Host 'The service' $UmbrellaStatus.Name 'is currently' $UmbrellaStatus.Status 'on computer' $ComputerName

                    $ExitScript = Read-Host -Prompt 'Would you like to Exit? 1 - Yes, 2 -No:'

                }
                Else
                {
                    Write-Host 'Service does not exist on' $ComputerName'.'
                    Write-Host 'Most likely cause is Umbrella is not installed'
                    $ExitScript = Read-Host -Prompt 'Would you like to Exit? 1 - Yes, 2 -No:'
                }

I have tried setting the variable the following ways, all with similar results. The last will throw an error but it will continue.

$UmbrellaService = 'Umbrella_RC'
$UmbrellaService = "Umbrella_RC"
$UmbrellaService = Umbrella_RC

need help converting VB script to PowerShell

$
0
0

was given this VB Script so not to much documents on it but need to convert it to PowerShell 

Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists("CreateReports.dll") Then   
'wscript.Echo "Installing Create Reports Active X..."
' Copy a File
Const OverwriteExisting = TRUE
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CopyFile "CreateReports.dll" , "c:\windows\CreateReports.dll", OverwriteExisting
objFSO.CopyFile "CreateReports3704.txt" , "c:\windows\CreateReports3704.txt", OverwriteExisting 
commandreg="CreateReports.dll"
Set WshShell = CreateObject("WScript.Shell") 
WshShell.Run "regsvr32 /s "& commandreg 
Set WshShell = CreateObject("WScript.Shell") 
End If
Wscript.Quit

Powershell query - Executing an ISPAC file

$
0
0


Hi Guys

Know some of you are experts in this stuff

I have

1) A PS1 script location

X:\SomeVarDir\SomeVarDir2\TFS_apps209\Recertisure\Development\PResentation\Recertisure.Database\Post-Deployment\PoweShell\Script1.ps1

2) A project deployment file at:

X:\SomeVarDir\SomeVarDir2\TFS_apps209\Recertisure\Development\SSIS\SSIS_Recert_Final\bin\Development\DeployProject.ispac

The problem is everyone has different locations for X:\SomeVarDir\SomeVarDir2 up to the point where the TFS_Apps209 comes from tfs so the folder structure is fixed from there on in

I need to:

1) get the path up to the start of TFS_Apps209 segment of the directory and store it nomatter where on the network or what folder its deployed to I just need to get the filepath up to that point

2) Head down a fixed filepath and execute the ispac file which will do the deployment

3) The result needs to populate a variable $ProjectFilePath

Can this be achieved?

No VmName in output

$
0
0

My powershell script will not display vm name in output csv. What am I missing?

$allvms = @()
$vms = Get-Content C:\Users\XXXXX\Documents\Linux\ALPtest.csv

foreach($vm in $vms)
{
  $vmstat = "" | Select VmName, MemMax, MemAvg, MemMin, CPUMax, CPUAvg, CPUMin
  $vmstat.VmName = $vm.name
  
  $statcpu = Get-Stat -Entity ($vm)-start (get-date).AddDays(-30) -Finish (Get-Date)-MaxSamples 10000 -stat cpu.usage.average
  $statmem = Get-Stat -Entity ($vm)-start (get-date).AddDays(-30) -Finish (Get-Date)-MaxSamples 10000 -stat mem.usage.average

  $cpu = $statcpu | Measure-Object -Property value -Average -Maximum -Minimum
  $mem = $statmem | Measure-Object -Property value -Average -Maximum -Minimum
  
  $vmstat.CPUMax = $cpu.Maximum
  $vmstat.CPUAvg = $cpu.Average
  $vmstat.CPUMin = $cpu.Minimum
  $vmstat.MemMax = $mem.Maximum
  $vmstat.MemAvg = $mem.Average
  $vmstat.MemMin = $mem.Minimum
  $allvms += $vmstat
}
$allvms | Select VmName, MemMax, MemAvg, MemMin, CPUMax, CPUAvg, CPUMin | Export-Csv "C:\Perf\Alp-VMstest.csv" -noTypeInformation

Viewing all 21975 articles
Browse latest View live


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