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

New-scheduledtasktrigger, atlogon and repetitioninterval, is it possible?

$
0
0
Hey. I'm trying to write a script that sets task scheduler to run another script. The problem I am having is that I can't get it to work with both "-AtLogOn" and "Repetitioninterval". It also says I have to have a "-once [date]" as well but I don't want that.

Is it possible to actually have both -atlogon and -repetitioninterval as  triggers for the script to begin?

Verbose switch clutter...

$
0
0

Since installing PowerShellGet and Azure PowerShell v1.0.1 my verbose output is very much more verbose.  I keep seeing many more modules loading when I never saw them loading before so when running a script in -verbose mode, my console output is littered with things I don't want to see.

VERBOSE: Loading module from path 'C:\Program Files (x86)\WindowsPowerShell\Modules\PackageManagement\1.0.0.1\Microsoft.PowerShell.PackageManagement.dll'.
VERBOSE: Loading module from path 'C:\Program Files (x86)\WindowsPowerShell\Modules\PackageManagement\1.0.0.0\Microsoft.PowerShell.PackageManagement.dll'.
VERBOSE: Loading module from path 'C:\Program Files (x86)\WindowsPowerShell\Modules\Pester\3.3.5\Pester.psm1'.
VERBOSE: Loading module from path 'C:\Program Files (x86)\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psm1'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.ODataUtils\Microsoft.PowerShell.ODataUtils.psm1'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Appx\Appx.psm1'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCacheClientSettingData.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCacheContentServerSettingData.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCacheHostedCacheServerSettingData.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCacheNetworkSettingData.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCacheOrchestrator.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCachePrimaryPublicationCacheFile.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCachePrimaryRepublicationCacheFile.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCacheSecondaryRepublicationCacheFile.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\BranchCache\BranchCacheStatus.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\DirectAccessClientComponents\MSFT_DASiteTableEntry.cdxml'.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\DirectAccessClientComponents\MSFT_DAClientExperienceConfiguration.cdxml'
.
VERBOSE: Loading module from path 'C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Dism\Microsoft.Dism.PowerShell.dll'.

.

....and on and on it goes.

Anyone else see this and know how to get rid of it...its making things harder to debug/troubleshoot with all this stuff flying across the screen.



PS Script to automate some minor tasks

$
0
0

HI all, I've found a script that's doing a great job for what it is, but I'm needing help adding to it to add a bit more functionality. 

What it does is it monitors a folder and any time a file is created or deleted, it displays a notification. 

What I'm wanting to add to it is functionality that when say a .txt file is added, it copy's that file to a different directory, and renames the existing file with yyyyMMdd then opens a website. 

I can make things work by themselves, but I can't seem to figure out the nuts-bolts to make it actually work the way I want too. 

I'm using a script I found on TechNet to perform the monitoring, but I'm assuming I need to add in a loop of some sort to make the rest of the functionality I'm wanting to have happen? 

The script I'm using I got from Technet called FileSystemWatcher and like I said, it's perfect, I just want a bit more to it. 

Any help? Please? 

Run Powershell script as Scheduled task, that uses Excel COM object

$
0
0

What am I missing here..

 

I have  Powershell script that uses the Quest AD cmdlets to get computer information from AD and populate an Excel spreadsheet with the data.

The script works fine, so I created a batch file and started the script from there (which works fine as well). It populates the excel spreadsheet, saves and closes the file.

If I run the script as a scheduled task, I can see from the logging that it supposedly gets the computers from AD, and runs through them. But a file is never saved, I have tried to run the scheduled task with admin credentials.

What am I forgetting?

PS Script to look for a file in c: then create report of that result in a file .txt

$
0
0

hello

 I got to create a script that will be on every computer to look if a certain file name  is on the c: ,  then get the result in  .txt file.

so far I was looking at something like this: but it's not automated


#>
"`n"
write-Host "---------------------------------------------" -ForegroundColor Yellow
$filePath = Read-Host "Please Enter File Path to Search"
write-Host "---------------------------------------------" -ForegroundColor Green
$fileName = Read-Host "Please Enter File Name to Search"
write-Host "---------------------------------------------" -ForegroundColor Yellow
"`n"

Get-ChildItem -Recurse -Force $filePath -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and  ( $_.Name -like "*$fileName*") } | Select-Object Name,Directory| Format-Table -AutoSize *
Write-Host "Press any key to continue ..."

$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

write-Host "------------END of Result--------------------" -ForegroundColor Magenta

# end of the script

Thanks

Powershell FileSystem Event/Image manipulation issues

$
0
0

Hello,

I'm working on a project involving FileSystem events, and image manipulation. I've written the attached script, but am having trouble with it. It seems to work about 90% of the time. Unfortunately, about 80% of the time, (2) events will trigger for each file system event that occurs. And occasionally it will just crash. I am not sure if there are any blaring issues with the code, but if someone would be willing to take a look, that would be appreciated.

The FileSystem event itself seems to run smoothly (I.E. I can remove all of my own code, and it produces a message everytime I add a file to the watch folder.) But when I start manipulating the file, and eventually remove it from the watch folder, things start to act funky. The two things I'm seeing weird are that the event will happen twice for each file added to the watchfolder, although the script will run correctly. And then the second weird thing that sometimes happens, is that an error will be thrown and it will just stop. 

It's been frustrating, lol.

See script below:

#By BigTeddy 05 September 2011

#This script uses the .NET FileSystemWatcher class to monitor file events in folder(s).
#The advantage of this method over using WMI eventing is that this can monitor sub-folders.
#The -Action parameter can contain any valid Powershell commands.  I have just included two for example.
#The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true.
#You need not subscribe to all three types of event.  All three are shown for example.
# Version 1.1

<#
$configPath = "C:\Users\Marcus Garfunkel\Dropbox\Projects\PowerShell\Settings.xml"
# Import settings from config file.
 If (Test-Path $configPath){
    $global:configFile = [xml](Get-Content $configPath)
}

Import-Module "..\ImageManipulation\Image.psm1"

$global:watchfolder = $global:configFile.Settings.FolderPaths.Watchfolder
Write-Host "WatchFolder: $global:watchfolder"
$global:destfolder = $global:configFile.Settings.FolderPaths.Destfolder
Write-Host "DestFolder: $global:destfolder"
#>
#$global:watchfolder = 'C:\Users\Marcus Garfunkel\Documents\WorldStage - Local\Projects\PowerShell\DragNewFilesHere' # Enter the root path you want to monitor.
#$global:destfolder = 'C:\Users\Marcus Garfunkel\Documents\WorldStage - Local\Projects\PowerShell\WatchoutFiles'
$filter = '*.*'  # You can enter a wildcard filter here.

# In the following line, you can change 'IncludeSubdirectories to $true if required.
$fsw = New-Object IO.FileSystemWatcher $global:watchfolder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}

# Here, all three events are registerd.  You need only subscribe to events that you need:

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
    $name = $Event.SourceEventArgs.Name
    $changeType = $Event.SourceEventArgs.ChangeType
    $timeStamp = $Event.TimeGenerated

    $configPath = "C:\Users\Marcus Garfunkel\Dropbox\Projects\PowerShell\Settings.xml"
    # Import settings from config file.
     If (Test-Path $configPath){
        $global:configFile = [xml](Get-Content $configPath)
    }

    Import-Module "..\ImageManipulation\Image.psm1"

    $global:watchfolder = $global:configFile.Settings.FolderPaths.Watchfolder
    Write-Host "WatchFolder: $global:watchfolder"
    $global:destfolder = $global:configFile.Settings.FolderPaths.Destfolder
    Write-Host "DestFolder: $global:destfolder"

    $desired_width = $global:configFile.Settings.ImageSettings.ImageWidth
    $desired_height = $global:configFile.Settings.ImageSettings.ImageHeight

    Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
    #Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"

    Try{
        $sourceFile = "$global:watchfolder\$name"
        $underlayFile = $global:configFile.Settings.ImagePaths.BkgdImage
        $tempFile = $global:configFile.Settings.ImagePaths.tempFile
        $outFile = $global:configFile.Settings.ImagePaths.outputFile

        Write-Host "Loading image '$sourceFile'..." -fore DarkGray
        $image = Get-Image $sourceFile

        Write-Host "Loading underlay file '$underlayFile'..." -fore DarkGray
        $otherImage = Get-Image $underlayFile

        Write-Host "Adding appropriate filters."
        $filter = Add-ScaleFilter -width $desired_width -height $desired_height -passThru #|
            #Add-OverLayFilter -Image $otherImage -Left 10 -Top 10 -passThru
        Write-Host "Applying appropriate filters."
        $image = $image | Set-ImageFilter -filter $filter -passThru

        Write-Host "Image width: " $image.width -fore blue
        Write-Host "Image height: " $image.height -fore blue
        Write-Host "Scaling to: $desired_width x $desired_height."
        if ($image.width -lt $desired_width) {
            $left = ($desired_width - $image.width) / 2
            $top = 0
        } else {
            $top = ($desired_height - $image.height) / 2
            $left = 0
        }

        $filter = Add-OverLayFilter -Image $image -Left $left -Top $top -passThru
        $otherImage = $otherImage | Set-ImageFilter -filter $filter -passThru
        Write-Host "Checking if $tempfile already exists." -fore DarkGray
        If (Test-Path $tempFile){
            Remove-Item $tempFile
            Write-Host "Removed file $tempFile" -fore Red
        }
        $otherImage.SaveFile($tempFile)
        Write-Host "Saved file as '$tempFile'." -fore DarkGray

        Write-Host "Now converted file will be moved to '$global:destfolder\$outfile'." -fore DarkGray
        Move-Item -path $tempFile -destination $global:destfolder\$outfile -Force
        Write-Host "Now removing original file '$sourceFile'" -fore DarkGray
    #>
        #Remove-Variable image
        #Remove-Variable otherImage
        Remove-Item $sourceFile

    }Catch
    {
        $ErrorMessage = $_.Exception.Message
        $FailedItem = $_.Exception.ItemName
        Write-Host "Error: $ErrorMessage, $FailedItem"
        #Send-MailMessage -From ExpensesBot@MyCompany.Com -To WinAdmin@MyCompany.Com -Subject "HR File Read Failed!" -SmtpServer EXCH01.AD.MyCompany.Com -Body "We failed to read file $FailedItem. The error message was $ErrorMessage"
        #Break
    }
    #>
}<#
Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore red
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}

Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}
 #><#
Do {
    Start-Sleep -s 0.1
} While (1)
#>

# To stop the monitoring, run the following commands:
# Unregister-Event FileDeleted
# Unregister-Event FileCreated
# Unregister-Event FileChanged

Thanks for any input,

Marcus

Invoke-Command + cmd

$
0
0

Hi,

Recently I installed software by running a setup package like

Invoke-Command -ComputerName $ServerList -ScriptBlock { & cmd /c "C:\temp\software\setup.exe"} 

Now I need to run the exe with some parameters to activate the software, example:

Invoke-Command -ComputerName $ServerList -ScriptBlock { & cmd /c "C:\Program Files\software\setup.exe" /paef }

This is not working, does not return any errors but doesn`t do anything...

Additionally, the software might be at 

C:\Program Files

or

C:\Program Files (x86)

Any example how to solve this?

Thank you.

Powershell get variable from vb.net textbox

$
0
0

hello guys, this link shows how to call PS from vb.net (http://blogs.msdn.com/b/zainnab/archive/2008/07/26/calling-a-powershell-script-from-your-net-code.aspx)

How to run the PowerShell script and get the data from VB.Net textbox?

For example: VB.Net has textbox called "name".

And if I call the PowerShell script from vb.net it will get the data from textbox called name, and the data will be use by PowerShell script.

Thanks, for any help.



Every second counts..make use of it. Disclaimer: This posting is provided AS IS with no warranties or guarantees and confers no rights.
IT Stuff Quick Bytes


Export Data /List view Items To excel by using Export Link Label

$
0
0

Hi ,

I'm planning to export list view items in to excel sheet after clicking Export  link Label. I can open excel sheet but can't  export my data in ito it. Please advise

function Call- {

#----------------------------------------------
#region Import the Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load('mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
[void][reflection.assembly]::Load('System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][reflection.assembly]::Load('System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')
#endregion Import Assemblies

#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object 'System.Windows.Forms.Form'
$linklabelEXPort = New-Object 'System.Windows.Forms.LinkLabel'
$listview1 = New-Object 'System.Windows.Forms.ListView'
$savefiledialog1 = New-Object 'System.Windows.Forms.SaveFileDialog'
$columnheader1 = New-Object 'System.Windows.Forms.ColumnHeader'
$columnheader2 = New-Object 'System.Windows.Forms.ColumnHeader'
$InitialFormWindowState = New-Object 'System.Windows.Forms.FormWindowState'
#endregion Generated Form Objects

#----------------------------------------------
# User Generated Script
#----------------------------------------------
#Event: linklabelEXPort_LinkClicked
$linklabelEXPort_LinkClicked= [System.Windows.Forms.LinkLabelLinkClickedEventHandler]{
#TODO: Place custom script here


}
#End Event

#Event: listview1_SelectedIndexChanged
$listview1_SelectedIndexChanged= {
#TODO: Place custom script here

}
#End Event

#Event: form1_Load
$form1_Load= {
#TODO: Place custom script here

}
#End Event

#Event: savefiledialog1_FileOk
$savefiledialog1_FileOk= [System.ComponentModel.CancelEventHandler]{
#TODO: Place custom script here

}
#End Event

# --End User Generated Script--
#----------------------------------------------
#region Generated Events
#----------------------------------------------

$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}

$Form_Cleanup_FormClosed=
{
#Remove all event handlers from the controls
try
{
$linklabelEXPort.remove_LinkClicked($linklabelEXPort_LinkClicked)
$listview1.remove_SelectedIndexChanged($listview1_SelectedIndexChanged)
$form1.remove_Load($form1_Load)
$savefiledialog1.remove_FileOk($savefiledialog1_FileOk)
$form1.remove_Load($Form_StateCorrection_Load)
$form1.remove_FormClosed($Form_Cleanup_FormClosed)
}
catch [Exception]
{ }
}
#endregion Generated Events

#----------------------------------------------
#region Generated Form Code
#----------------------------------------------
$form1.SuspendLayout()
#
# form1
#
$form1.Controls.Add($linklabelEXPort)
$form1.Controls.Add($listview1)
$form1.ClientSize = '779, 448'
$form1.Name = "form1"
$form1.Text = "Form"
$form1.add_Load($form1_Load)
#
# linklabelEXPort
#
$linklabelEXPort.Location = '615, 35'
$linklabelEXPort.Name = "linklabelEXPort"
$linklabelEXPort.Size = '120, 31'
$linklabelEXPort.TabIndex = 1
$linklabelEXPort.TabStop = $True
$linklabelEXPort.Text = "EXPort"
$linklabelEXPort.add_LinkClicked($linklabelEXPort_LinkClicked)
#
# listview1
#
[void]$listview1.Columns.Add($columnheader1)
[void]$listview1.Columns.Add($columnheader2)
$System_Windows_Forms_ListViewItem_1 = New-Object 'System.Windows.Forms.ListViewItem' ([System.String[]] ("Comp1", "11/2/2015"), -1)
[void]$listview1.Items.Add($System_Windows_Forms_ListViewItem_1)
$System_Windows_Forms_ListViewItem_2 = New-Object 'System.Windows.Forms.ListViewItem' ([System.String[]] ("Comp2", "11/1/2015"), -1)
[void]$listview1.Items.Add($System_Windows_Forms_ListViewItem_2)
$listview1.Location = '29, 66'
$listview1.Name = "listview1"
$listview1.Size = '550, 272'
$listview1.TabIndex = 0
$listview1.UseCompatibleStateImageBehavior = $False
$listview1.View = 'Details'
$listview1.add_SelectedIndexChanged($listview1_SelectedIndexChanged)
#
# savefiledialog1
#
$savefiledialog1.CreatePrompt = $True
$savefiledialog1.DefaultExt = "html,.xls"
$savefiledialog1.FileName = "Devices selected for remediation"
$savefiledialog1.InitialDirectory = "%windir%\EUO\Data"
$savefiledialog1.ShowHelp = $True
$savefiledialog1.SupportMultiDottedExtensions = $True
$savefiledialog1.Title = "Selected Remediated"
$savefiledialog1.add_FileOk($savefiledialog1_FileOk)
#
# columnheader1
#
$columnheader1.Text = "Computer"
#
# columnheader2
#
$columnheader2.Text = "Alert"
$form1.ResumeLayout($false)
#endregion Generated Form Code

#----------------------------------------------

#Save the initial state of the form
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($Form_StateCorrection_Load)
#Clean up the control events
$form1.add_FormClosed($Form_Cleanup_FormClosed)
#Show the Form
return $form1.ShowDialog()

} #End Function

#Call the form
Call- | Out-Null

Powershell Remote command not allowing database access

$
0
0

I am new to powershell and after following numerous tutorials I have manahed to get something to work but another is failing.
I suspect it is my application but if someone could check my code and let me know it would be appreciated.

I have a batch file that runs a command line version of an application using a parameter file. All the parameters are stored on the remote machine and if I run my batch file on the remote machine, it works fine.

If I use the following command from a powershell on another machine, it runs but fails to connect to the database from my remote application.

Invoke-Command -Computername xxxxxx -ScriptBlock {& cmd.exe /c "c:\temp\runacq.bat"}

If I run invoke-expression 'cmd /c "whoami > c:\temp\whoremote.txt" ' it provides the correct credentials on the remote machine.

If the above powershell command is correct, can I assume that my application is at fault and not the powershell command?

Thanks

Get Computername, Bios, Logged in user, and IP as well as Service Tag for Dell, HP or IBM systems

$
0
0

Thanks in advance for the help!!!!

I am working on a powershell script to gather all of the above information at once that will work for multiple systems in our environment.  I am using Rob VanderWoudes WMIGen located at www.robvanderwoude.com/wmigen.php it has been very helpful Thanks Rob for that tool, but I would like to elaborate to gather all of the information above.

I have made a BIOS.ps1 file (See Below) I need some assistance on gathering additional info from WMI-ComputerName, WMI-NetworkAdapter, and WMI-ComputerSystem to gather all of the information unless someone has a better method.  Please help with this as it will be useful I am sure for many in multiple areas.

Begin BIOS.PS1
--------------------------

# WMI query to list all properties and values of the Win32_BIOS class
# This PowerShell script was generated using the WMI Code Generator, Version 1.30
# http://www.robvanderwoude.com/updates/wmigen.html
 
param( [string]$strComputer = "." )
 
$colItems = get-wmiobject -class "Win32_BIOS" -namespace "root\CIMV2" -computername $strComputer

foreach ($objItem in $colItems) {
write-host "BIOS                           :" $objItem.Name
write-host "Version                        :" $objItem.Version
write-host "Manufacturer                   :" $objItem.Manufacturer
write-host "SMBIOSBIOS Version             :" $objItem.SMBIOSBIOSVersion
write-host "Service Tag                    :" $objItem.Serialnumber
write-host
}

____________

Which firewall port(s) required for using get-adgroupmember -server option

$
0
0
I need to query out DMZ domain from our internal network by using get-adgroupmember, instead build remote PS session (port 5985/5986).  I found that get-adgroupmember could specific -server option, but which port is this option use to make connection through DMZ firewall?  That to say if I issue get-adgroupmember -server "server1.dmz.com:XXXX"?  Thanks a lot.

Need to check WMI Connectivity between 2 Remote Server using Powershell

$
0
0

Hi,

         I need to check WMI Connectivity between 2 Remote Server using Powershell. Ex: I need to run a Powershell Script from Server A, to check the WMI Connectivity between 2 remote machine Server B and Server C. Is there any straight forward way altogether?

My Approch

The Approch I took is , I used Powershell remoting at Server A to initiate an Invoke-Command. There I used  the Get-WMIObject

At Server A :

Invoke-Command -Computername "Server B" -Credential $Credential -Authentication Credssp -ScriptBlock {gwmi win32_bios -ComputerName "Server B" -ErrorAction SilentlyContinue}

and as a Prereq, I enabled CredentialsDelegation at Server A as per this link. (http://blogs.technet.com/b/heyscriptingguy/archive/2012/11/14/enable-powershell-quot-second-hop-quot-functionality-with-credssp.aspx)

But here issue is we need to pass the credential to Server B, to talk to Server C's WMI hive. I dont want to send the Username and Password

NOTE:

The Account with which I am running the Powershell Script in Server A, is the admin in BothServer B and Server C.

Convert the AD property 'accountExpires' to readable date time

$
0
0

Why does my Get-AdAcctExpDate work as intended and the ConvertTo-Date does not.  It gives error, "String was not recognized as a valid DateTime."

Function Get-ADAcctExpDate {
    Param (
        [Parameter(mandatory=$true)][String]$sam
    )
    $User = Get-ADUser -Identity $sam -Properties accountExpires
    $lngValue = $User.accountExpires
    if(($lngValue -eq 0) -or ($lngValue -gt [DateTime]::MaxValue.Ticks)) {
        $AcctExpires = "<Never>"
    } else {
        $Date = [DateTime]$lngValue
        $AcctExpires = $Date.AddYears(1600).ToLocalTime()
    }
    $AcctExpires
}
Function ConvertTo-Date {
    Param (
        [Parameter(ValueFromPipeline=$true,mandatory=$true)][String]$accountExpires
    )

    $lngValue = $accountExpires
    if(($lngValue -eq 0) -or ($lngValue -gt [DateTime]::MaxValue.Ticks)) {
        $AcctExpires = "<Never>"
    } else {
        $Date = [DateTime]$lngValue
        $AcctExpires = $Date.AddYears(1600).ToLocalTime()
    }
    $AcctExpires
}

So here is is in use:

PS D:\PowerShell> (Get-ADUser user1 -Properties accountExpires).accountExpires | ConvertTo-Date Cannot convert value "130158288000000000" to type "System.DateTime". Error: "String was not recognized as a valid DateTime." At D:\PowerShell\User-PerDiem.ps1:169 char:36+ $Date = [DateTime]$lngValue <<<<+ CategoryInfo : NotSpecified: (:) [], RuntimeException+ FullyQualifiedErrorId : RuntimeException<...> PS D:\PowerShell> (Get-ADUser user1 -Properties accountExpires).accountExpires 130158288000000000 PS D:\PowerShell> Get-ADAcctExpDate user1 Sunday, June 16, 2013 12:00:00 AM PS D:\PowerShell>

I found other posts with other methods, but really I am just trying to figure out why my one way works and other doesn't.  I assume it is the variable type or "string" in my Param, but haven't been able to resolve the issue.

one of those other posts:  http://social.technet.microsoft.com/forums/en-us/winserverpowershell/thread/37A38AF1-C9FA-4292-907E-F43113394402


Find this post helpful? Does this post answer your question? Be sure to mark it appropriately to help others find answers to their searches.

WIndows 10: Preventing PSReadline without removing it

$
0
0

Hi guys,

I have a somewhat tricky question about Windows 10 and PowerShell:

Windows 10 now ships with PSReadline, which generally is a vast enhancement for the user experience. I want to prevent it from loading automatically.

Yes, prevent it. I do not however want to remove it. Just this one time for this one user,it should never have been loaded in the first place.

Now why would I want to do this?
Well, we're using a PowerShell console that uses the default host, but loads our own modules, cmdlets and functions. It too comes with a customized version of PSReadline, and the two libraries don't play together, since they are named just the same and have just the same namespaces/classes inside.

However, the default Version does not provide all the features we need (which is why I customized it to begin with). Removing the module after loading it does me no good, since I only get one appdomain and can't remove libraries from it (so, the first loaded PSReadline library wins). Removing the module that shipped with Windows 10 however is no good either, since this would affect regular users just as well (Users who some time down the road might easily work on the same computer at the same time, once our customers start using Server 2016).

Sooo ... any ideas how I can prevent it from loading?

Cheers,
Fred


There's no place like 127.0.0.1


PowerShell + iscsicli

$
0
0

Hi

I am having issue with issuing iscsicli.exe in remote session via script.

Following lines are failing:

$command = "iscsicli RefreshTargetPortal $using:ISCSITargetIP 3260 ROOT\ISCSIPRT\0000_0 1"
Invoke-Expression $command

Write-host "Adding ISCSI target - on port $using:index"
$command = "iscsicli addtargetportal $using:ISCSITargetIP 3260 ROOT`\ISCSIPRT`\0000_0 $using:index * * * * * * * * * *"

Invoke-Expression $command

When command are executed in script they are failing - when i execute those commands via entering pssession and executing one by one - all works, when i logon to target server and execute them one by one ... all works.

Can anyone tell me why this is happening?

Michał

CSV File manipulation

$
0
0

I have a CSV file like below



but I need to convert to below using Powershell

is this possible?

scriptblock fails to create

$
0
0

I'm trying to create a script block to run using invivoke-command but fails to create

$scr = [scriptblock]::Create(@"
[Hashtable]$owners
gwmi win32_process | Foreach {$owners[$_.handle] = $_.getowner().user}
Get-Process | select processname,CommandLine,Id,@{l="Owner";e={$owners[$_.id.tostring()]}}"@)

Invoke-Command -Session $s -ScriptBlock $scr

Any ideas?

PowerShell - Check registry value (install path) and correct it if needed

$
0
0

Hello,

I'm a little bit confused with Get-ItemProperty usage in registry when looking for file path. My problem is, that on all computers I've got registry key HKLM:\Software\Altiris with subkeys, where there are multiple entries with wrong path "D:\Program Files\Altiris\...". Ideally what I want to do is to:

1. Check "Altiris" key and all subkeys for "D:\Program Files\Altiris*" occurrence (not every computer got wrong entry),

2. If the path is correct "C:\Program Files\Altiris\..." leave it,

3. If not - replace D: with C:

I thought that it will be easy think to do, but maybe I wrongly use Get-ItemProperty, because when looking for "D:\Program Filese\Altiris*" got error message that I use escape character.

Can anyone can help me with this?

Thanks,

Michal


Script to find non-domain servers on a subnet

$
0
0
Does anyone know of a way with powershell to search a subnet for all windows servers that are NOT domain members?  I looked a round but cant seem to find a good way to do this.  Thanks
Viewing all 21975 articles
Browse latest View live


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